p2p.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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::{Hosts, HostsPtr},
  31. message::Message,
  32. protocol::{protocol_registry::ProtocolRegistry, register_default_protocols},
  33. session::{
  34. InboundSession, InboundSessionPtr, ManualSession, ManualSessionPtr, OutboundSession,
  35. OutboundSessionPtr, SeedSyncSession,
  36. },
  37. settings::{Settings, SettingsPtr},
  38. };
  39. use crate::{
  40. system::{ExecutorPtr, Subscriber, SubscriberPtr, Subscription},
  41. Result,
  42. };
  43. /// Set of channels that are awaiting connection
  44. pub type PendingChannels = Mutex<HashSet<Url>>;
  45. /// Set of connected channels
  46. pub type ConnectedChannels = Mutex<HashMap<Url, ChannelPtr>>;
  47. /// Atomic pointer to the p2p interface
  48. pub type P2pPtr = Arc<P2p>;
  49. /// Toplevel peer-to-peer networking interface
  50. pub struct P2p {
  51. /// Global multithreaded executor reference
  52. executor: ExecutorPtr,
  53. /// Channels pending connection
  54. pending: PendingChannels,
  55. /// Connected channels
  56. channels: ConnectedChannels,
  57. /// Subscriber for notifications of new channels
  58. channel_subscriber: SubscriberPtr<Result<ChannelPtr>>,
  59. /// Known hosts (peers)
  60. hosts: HostsPtr,
  61. /// Protocol registry
  62. protocol_registry: ProtocolRegistry,
  63. /// P2P network settings
  64. settings: SettingsPtr,
  65. /// Boolean lock marking if peer discovery is active
  66. pub peer_discovery_running: Mutex<bool>,
  67. /// Reference to configured [`ManualSession`]
  68. session_manual: ManualSessionPtr,
  69. /// Reference to configured [`InboundSession`]
  70. session_inbound: InboundSessionPtr,
  71. /// Reference to configured [`OutboundSession`]
  72. session_outbound: OutboundSessionPtr,
  73. /// Enable network debugging
  74. pub dnet_enabled: Mutex<bool>,
  75. /// The subscriber for which we can give dnet info over
  76. dnet_subscriber: SubscriberPtr<DnetEvent>,
  77. }
  78. impl P2p {
  79. /// Initialize a new p2p network.
  80. ///
  81. /// Initializes all sessions and protocols. Adds the protocols to the protocol
  82. /// registry, along with a bitflag session selector that includes or excludes
  83. /// sessions from seed, version, and address protocols.
  84. ///
  85. /// Creates a weak pointer to self that is used by all sessions to access the
  86. /// p2p parent class.
  87. pub async fn new(settings: Settings, executor: ExecutorPtr) -> P2pPtr {
  88. let settings = Arc::new(settings);
  89. let self_ = Arc::new(Self {
  90. executor,
  91. pending: Mutex::new(HashSet::new()),
  92. channels: Mutex::new(HashMap::new()),
  93. channel_subscriber: Subscriber::new(),
  94. hosts: Hosts::new(settings.clone()),
  95. protocol_registry: ProtocolRegistry::new(),
  96. settings,
  97. peer_discovery_running: Mutex::new(false),
  98. session_manual: ManualSession::new(),
  99. session_inbound: InboundSession::new(),
  100. session_outbound: OutboundSession::new(),
  101. dnet_enabled: Mutex::new(false),
  102. dnet_subscriber: Subscriber::new(),
  103. });
  104. self_.session_manual.p2p.init(self_.clone());
  105. self_.session_inbound.p2p.init(self_.clone());
  106. self_.session_outbound.p2p.init(self_.clone());
  107. register_default_protocols(self_.clone()).await;
  108. self_
  109. }
  110. /// Starts inbound, outbound, and manual sessions.
  111. pub async fn start(self: Arc<Self>) -> Result<()> {
  112. debug!(target: "net::p2p::start()", "P2P::start() [BEGIN]");
  113. info!(target: "net::p2p::start()", "[P2P] Starting P2P subsystem");
  114. // First attempt any set manual connections
  115. for peer in &self.settings.peers {
  116. self.session_manual().await.connect(peer.clone()).await;
  117. }
  118. // Start the inbound session
  119. let inbound = self.session_inbound().await;
  120. if let Err(err) = inbound.start().await {
  121. error!(target: "net::p2p::start()", "Failed to start inbound session!: {}", err);
  122. self.session_manual().await.stop().await;
  123. return Err(err)
  124. }
  125. // Start the outbound session
  126. self.session_outbound().await.start().await;
  127. info!(target: "net::p2p::start()", "[P2P] P2P subsystem started");
  128. Ok(())
  129. }
  130. /// Reseed the P2P network.
  131. pub async fn seed(self: Arc<Self>) -> Result<()> {
  132. debug!(target: "net::p2p::seed()", "P2P::seed() [BEGIN]");
  133. info!(target: "net::p2p::seed()", "[P2P] Seeding P2P subsystem");
  134. // Start seed session
  135. let seed = SeedSyncSession::new(Arc::downgrade(&self));
  136. // This will block until all seed queries have finished
  137. seed.start().await?;
  138. debug!(target: "net::p2p::seed()", "P2P::seed() [END]");
  139. Ok(())
  140. }
  141. /// Stop the running P2P subsystem
  142. pub async fn stop(&self) {
  143. // Stop the sessions
  144. self.session_manual().await.stop().await;
  145. self.session_inbound().await.stop().await;
  146. self.session_outbound().await.stop().await;
  147. }
  148. /// Broadcasts a message concurrently across all active channels.
  149. pub async fn broadcast<M: Message>(&self, message: &M) {
  150. self.broadcast_with_exclude(message, &[]).await
  151. }
  152. /// Broadcasts a message concurrently across active channels, excluding
  153. /// the ones provided in `exclude_list`.
  154. pub async fn broadcast_with_exclude<M: Message>(&self, message: &M, exclude_list: &[Url]) {
  155. let chans = self.channels.lock().await;
  156. let iter = chans.values();
  157. let mut futures = FuturesUnordered::new();
  158. for channel in iter {
  159. if exclude_list.contains(channel.address()) {
  160. continue
  161. }
  162. futures.push(channel.send(message).map_err(|e| {
  163. (
  164. format!("[P2P] Broadcasting message to {} failed: {}", channel.address(), e),
  165. channel.clone(),
  166. )
  167. }));
  168. }
  169. if futures.is_empty() {
  170. warn!(target: "net::p2p::broadcast()", "[P2P] No connected channels found for broadcast");
  171. return
  172. }
  173. while let Some(entry) = futures.next().await {
  174. if let Err((e, chan)) = entry {
  175. error!(target: "net::p2p::broadcast()", "{}", e);
  176. self.remove(chan).await;
  177. }
  178. }
  179. }
  180. /// Check whether we're connected to a given address
  181. pub async fn exists(&self, addr: &Url) -> bool {
  182. self.channels.lock().await.contains_key(addr)
  183. }
  184. /// Add a channel to the set of connected channels
  185. pub(super) async fn store(&self, channel: ChannelPtr) {
  186. // TODO: Check the code path for this, and potentially also insert the remote
  187. // into the hosts list?
  188. self.channels.lock().await.insert(channel.address().clone(), channel.clone());
  189. self.channel_subscriber.notify(Ok(channel)).await;
  190. }
  191. /// Remove a channel from the set of connected channels
  192. pub(super) async fn remove(&self, channel: ChannelPtr) {
  193. self.channels.lock().await.remove(channel.address());
  194. }
  195. /// Add an address to the list of pending channels.
  196. pub(super) async fn add_pending(&self, addr: &Url) -> bool {
  197. self.pending.lock().await.insert(addr.clone())
  198. }
  199. /// Remove a channel from the list of pending channels.
  200. pub(super) async fn remove_pending(&self, addr: &Url) {
  201. self.pending.lock().await.remove(addr);
  202. }
  203. /// Return reference to connected channels map
  204. pub async fn channels(&self) -> &ConnectedChannels {
  205. &self.channels
  206. }
  207. /// Retrieve a random connected channel from the
  208. pub async fn random_channel(&self) -> Option<ChannelPtr> {
  209. let channels = self.channels().await.lock().await;
  210. channels.values().choose(&mut OsRng).cloned()
  211. }
  212. pub async fn is_connected(&self) -> bool {
  213. !self.channels().await.lock().await.is_empty()
  214. }
  215. /// Return an atomic pointer to the set network settings
  216. pub fn settings(&self) -> SettingsPtr {
  217. self.settings.clone()
  218. }
  219. /// Return an atomic pointer to the list of hosts
  220. pub fn hosts(&self) -> HostsPtr {
  221. self.hosts.clone()
  222. }
  223. /// Reference the global executor
  224. pub fn executor(&self) -> ExecutorPtr {
  225. self.executor.clone()
  226. }
  227. /// Return a reference to the internal protocol registry
  228. pub fn protocol_registry(&self) -> &ProtocolRegistry {
  229. &self.protocol_registry
  230. }
  231. /// Get pointer to manual session
  232. pub async fn session_manual(&self) -> ManualSessionPtr {
  233. self.session_manual.clone()
  234. }
  235. /// Get pointer to inbound session
  236. pub async fn session_inbound(&self) -> InboundSessionPtr {
  237. self.session_inbound.clone()
  238. }
  239. /// Get pointer to outbound session
  240. pub async fn session_outbound(&self) -> OutboundSessionPtr {
  241. self.session_outbound.clone()
  242. }
  243. /// Enable network debugging
  244. pub async fn dnet_enable(&self) {
  245. *self.dnet_enabled.lock().await = true;
  246. warn!("[P2P] Network debugging enabled!");
  247. }
  248. /// Disable network debugging
  249. pub async fn dnet_disable(&self) {
  250. *self.dnet_enabled.lock().await = false;
  251. warn!("[P2P] Network debugging disabled!");
  252. }
  253. /// Subscribe to dnet events
  254. pub async fn dnet_subscribe(&self) -> Subscription<DnetEvent> {
  255. self.dnet_subscriber.clone().subscribe().await
  256. }
  257. /// Send a dnet notification over the subscriber
  258. pub async fn dnet_notify(&self, event: DnetEvent) {
  259. self.dnet_subscriber.notify(event).await;
  260. }
  261. }