p2p.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{
  19. collections::{HashMap, HashSet},
  20. sync::Arc,
  21. };
  22. use futures::{stream::FuturesUnordered, TryFutureExt};
  23. use log::{debug, error, info, warn};
  24. use rand::{prelude::IteratorRandom, rngs::OsRng};
  25. use smol::{lock::Mutex, stream::StreamExt};
  26. use url::Url;
  27. use super::{
  28. channel::ChannelPtr,
  29. dnet::DnetEvent,
  30. hosts::{
  31. refinery::{GreylistRefinery, GreylistRefineryPtr},
  32. store::{Hosts, HostsPtr},
  33. },
  34. message::Message,
  35. protocol::{protocol_registry::ProtocolRegistry, register_default_protocols},
  36. session::{
  37. InboundSession, InboundSessionPtr, ManualSession, ManualSessionPtr, OutboundSession,
  38. OutboundSessionPtr, SeedSyncSession,
  39. },
  40. settings::{Settings, SettingsPtr},
  41. };
  42. use crate::{
  43. system::{ExecutorPtr, Subscriber, SubscriberPtr, Subscription},
  44. Result,
  45. };
  46. /// Set of channels that are awaiting connection
  47. pub type PendingChannels = Mutex<HashSet<Url>>;
  48. /// Set of connected channels
  49. pub type ConnectedChannels = Mutex<HashMap<Url, ChannelPtr>>;
  50. /// Atomic pointer to the p2p interface
  51. pub type P2pPtr = Arc<P2p>;
  52. /// Toplevel peer-to-peer networking interface
  53. pub struct P2p {
  54. /// Global multithreaded executor reference
  55. executor: ExecutorPtr,
  56. /// Channels pending connection
  57. pending: PendingChannels,
  58. /// Connected channels
  59. channels: ConnectedChannels,
  60. /// Subscriber for notifications of new channels
  61. channel_subscriber: SubscriberPtr<Result<ChannelPtr>>,
  62. /// Known hosts (peers)
  63. hosts: HostsPtr,
  64. /// Protocol registry
  65. protocol_registry: ProtocolRegistry,
  66. /// P2P network settings
  67. settings: SettingsPtr,
  68. /// Boolean lock marking if peer discovery is active
  69. pub peer_discovery_running: Mutex<bool>,
  70. /// Reference to configured [`ManualSession`]
  71. session_manual: ManualSessionPtr,
  72. /// Reference to configured [`InboundSession`]
  73. session_inbound: InboundSessionPtr,
  74. /// Reference to configured [`OutboundSession`]
  75. session_outbound: OutboundSessionPtr,
  76. /// Enable network debugging
  77. pub dnet_enabled: Mutex<bool>,
  78. /// The subscriber for which we can give dnet info over
  79. dnet_subscriber: SubscriberPtr<DnetEvent>,
  80. // Greylist refinery process
  81. greylist_refinery: Arc<GreylistRefinery>,
  82. }
  83. impl P2p {
  84. /// Initialize a new p2p network.
  85. ///
  86. /// Initializes all sessions and protocols. Adds the protocols to the protocol
  87. /// registry, along with a bitflag session selector that includes or excludes
  88. /// sessions from seed, version, and address protocols.
  89. ///
  90. /// Creates a weak pointer to self that is used by all sessions to access the
  91. /// p2p parent class.
  92. pub async fn new(settings: Settings, executor: ExecutorPtr) -> P2pPtr {
  93. let settings = Arc::new(settings);
  94. let self_ = Arc::new(Self {
  95. executor,
  96. pending: Mutex::new(HashSet::new()),
  97. channels: Mutex::new(HashMap::new()),
  98. channel_subscriber: Subscriber::new(),
  99. hosts: Hosts::new(settings.clone()),
  100. protocol_registry: ProtocolRegistry::new(),
  101. settings,
  102. peer_discovery_running: Mutex::new(false),
  103. session_manual: ManualSession::new(),
  104. session_inbound: InboundSession::new(),
  105. session_outbound: OutboundSession::new(),
  106. dnet_enabled: Mutex::new(false),
  107. dnet_subscriber: Subscriber::new(),
  108. greylist_refinery: GreylistRefinery::new(),
  109. });
  110. self_.session_manual.p2p.init(self_.clone());
  111. self_.session_inbound.p2p.init(self_.clone());
  112. self_.session_outbound.p2p.init(self_.clone());
  113. self_.greylist_refinery.p2p.init(self_.clone());
  114. register_default_protocols(self_.clone()).await;
  115. self_
  116. }
  117. /// Starts inbound, outbound, and manual sessions.
  118. pub async fn start(self: Arc<Self>) -> Result<()> {
  119. debug!(target: "net::p2p::start()", "P2P::start() [BEGIN]");
  120. info!(target: "net::p2p::start()", "[P2P] Starting P2P subsystem");
  121. // First attempt any set manual connections
  122. for peer in &self.settings.peers {
  123. self.session_manual().connect(peer.clone()).await;
  124. }
  125. // Start the inbound session
  126. if let Err(err) = self.session_inbound().start().await {
  127. error!(target: "net::p2p::start()", "Failed to start inbound session!: {}", err);
  128. self.session_manual().stop().await;
  129. return Err(err)
  130. }
  131. info!(target: "net::p2p::start()", "Starting greylist refinery process");
  132. self.greylist_refinery.clone().start().await;
  133. // Start the outbound session
  134. self.session_outbound().start().await;
  135. info!(target: "net::p2p::start()", "[P2P] P2P subsystem started");
  136. Ok(())
  137. }
  138. /// Reseed the P2P network.
  139. pub async fn seed(self: Arc<Self>) -> Result<()> {
  140. debug!(target: "net::p2p::seed()", "P2P::seed() [BEGIN]");
  141. info!(target: "net::p2p::seed()", "[P2P] Seeding P2P subsystem");
  142. // Start seed session
  143. let seed = SeedSyncSession::new(Arc::downgrade(&self));
  144. // This will block until all seed queries have finished
  145. seed.start().await?;
  146. debug!(target: "net::p2p::seed()", "P2P::seed() [END]");
  147. Ok(())
  148. }
  149. /// Stop the running P2P subsystem
  150. pub async fn stop(&self) {
  151. // Stop the sessions
  152. self.session_manual().stop().await;
  153. self.session_inbound().stop().await;
  154. self.session_outbound().stop().await;
  155. // Stop greylist refinery process
  156. self.greylist_refinery().stop().await;
  157. }
  158. /// Broadcasts a message concurrently across all active channels.
  159. pub async fn broadcast<M: Message>(&self, message: &M) {
  160. self.broadcast_with_exclude(message, &[]).await
  161. }
  162. /// Broadcasts a message concurrently across active channels, excluding
  163. /// the ones provided in `exclude_list`.
  164. pub async fn broadcast_with_exclude<M: Message>(&self, message: &M, exclude_list: &[Url]) {
  165. let mut channels = Vec::new();
  166. for channel in self.channels().await {
  167. if exclude_list.contains(channel.address()) {
  168. continue
  169. }
  170. channels.push(channel);
  171. }
  172. self.broadcast_to(message, &channels).await
  173. }
  174. /// Broadcast a message concurrently to all given peers.
  175. pub async fn broadcast_to<M: Message>(&self, message: &M, channel_list: &[ChannelPtr]) {
  176. if channel_list.is_empty() {
  177. warn!(target: "net::p2p::broadcast()", "[P2P] No connected channels found for broadcast");
  178. return
  179. }
  180. let futures = FuturesUnordered::new();
  181. for channel in channel_list {
  182. futures.push(channel.send(message).map_err(|e| {
  183. error!(
  184. target: "net::p2p::broadcast()",
  185. "[P2P] Broadcasting message to {} failed: {}",
  186. channel.address(), e
  187. );
  188. // If the channel is stopped then it should automatically die
  189. // and the session will remove it from p2p.
  190. assert!(channel.is_stopped());
  191. }));
  192. }
  193. let _results: Vec<_> = futures.collect().await;
  194. }
  195. /// Check whether we're connected to a given address
  196. pub async fn exists(&self, addr: &Url) -> bool {
  197. self.channels.lock().await.contains_key(addr)
  198. }
  199. /// Add a channel to the set of connected channels
  200. pub(super) async fn store(&self, channel: ChannelPtr) {
  201. self.channels.lock().await.insert(channel.address().clone(), channel.clone());
  202. self.channel_subscriber.notify(Ok(channel)).await;
  203. }
  204. /// Remove a channel from the set of connected channels
  205. pub(super) async fn remove(&self, channel: ChannelPtr) {
  206. self.channels.lock().await.remove(channel.address());
  207. }
  208. /// Add an address to the list of pending channels.
  209. pub(super) async fn add_pending(&self, addr: &Url) -> bool {
  210. self.pending.lock().await.insert(addr.clone())
  211. }
  212. /// Remove a channel from the list of pending channels.
  213. pub(super) async fn remove_pending(&self, addr: &Url) {
  214. self.pending.lock().await.remove(addr);
  215. }
  216. /// Return all connected channels
  217. pub async fn channels(&self) -> Vec<ChannelPtr> {
  218. self.channels.lock().await.values().cloned().collect()
  219. }
  220. /// Retrieve a random connected channel from the
  221. pub async fn random_channel(&self) -> Option<ChannelPtr> {
  222. let channels = self.channels.lock().await;
  223. channels.values().choose(&mut OsRng).cloned()
  224. }
  225. pub async fn is_connected(&self) -> bool {
  226. !self.channels.lock().await.is_empty()
  227. }
  228. /// Return an atomic pointer to the set network settings
  229. pub fn settings(&self) -> SettingsPtr {
  230. self.settings.clone()
  231. }
  232. /// Return an atomic pointer to the list of hosts
  233. pub fn hosts(&self) -> HostsPtr {
  234. self.hosts.clone()
  235. }
  236. /// Reference the global executor
  237. pub fn executor(&self) -> ExecutorPtr {
  238. self.executor.clone()
  239. }
  240. /// Return a reference to the internal protocol registry
  241. pub fn protocol_registry(&self) -> &ProtocolRegistry {
  242. &self.protocol_registry
  243. }
  244. /// Get pointer to manual session
  245. pub fn session_manual(&self) -> ManualSessionPtr {
  246. self.session_manual.clone()
  247. }
  248. /// Get pointer to inbound session
  249. pub fn session_inbound(&self) -> InboundSessionPtr {
  250. self.session_inbound.clone()
  251. }
  252. /// Get pointer to outbound session
  253. pub fn session_outbound(&self) -> OutboundSessionPtr {
  254. self.session_outbound.clone()
  255. }
  256. /// Get pointer to greylist refinery
  257. pub fn greylist_refinery(&self) -> GreylistRefineryPtr {
  258. self.greylist_refinery.clone()
  259. }
  260. /// Enable network debugging
  261. pub async fn dnet_enable(&self) {
  262. *self.dnet_enabled.lock().await = true;
  263. warn!("[P2P] Network debugging enabled!");
  264. }
  265. /// Disable network debugging
  266. pub async fn dnet_disable(&self) {
  267. *self.dnet_enabled.lock().await = false;
  268. warn!("[P2P] Network debugging disabled!");
  269. }
  270. /// Subscribe to dnet events
  271. pub async fn dnet_subscribe(&self) -> Subscription<DnetEvent> {
  272. self.dnet_subscriber.clone().subscribe().await
  273. }
  274. /// Send a dnet notification over the subscriber
  275. pub(super) async fn dnet_notify(&self, event: DnetEvent) {
  276. self.dnet_subscriber.notify(event).await;
  277. }
  278. }