p2p.rs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 smol::{lock::Mutex, stream::StreamExt};
  25. use url::Url;
  26. use super::{
  27. channel::ChannelPtr,
  28. dnet::DnetEvent,
  29. hosts::{
  30. refinery::{GreylistRefinery, GreylistRefineryPtr},
  31. store::{Hosts, HostsPtr},
  32. },
  33. message::Message,
  34. protocol::{protocol_registry::ProtocolRegistry, register_default_protocols},
  35. session::{
  36. InboundSession, InboundSessionPtr, ManualSession, ManualSessionPtr, OutboundSession,
  37. OutboundSessionPtr, SeedSyncSession,
  38. },
  39. settings::{Settings, SettingsPtr},
  40. };
  41. use crate::{
  42. system::{ExecutorPtr, Subscriber, SubscriberPtr, Subscription},
  43. Result,
  44. };
  45. /// Set of channels that are awaiting connection
  46. pub type PendingChannels = Mutex<HashSet<Url>>;
  47. /// Set of connected channels
  48. pub type ConnectedChannels = Mutex<HashMap<Url, ChannelPtr>>;
  49. /// Atomic pointer to the p2p interface
  50. pub type P2pPtr = Arc<P2p>;
  51. /// Toplevel peer-to-peer networking interface
  52. pub struct P2p {
  53. /// Global multithreaded executor reference
  54. executor: ExecutorPtr,
  55. /// Known hosts (peers)
  56. hosts: HostsPtr,
  57. /// Protocol registry
  58. protocol_registry: ProtocolRegistry,
  59. /// P2P network settings
  60. settings: SettingsPtr,
  61. /// Boolean lock marking if peer discovery is active
  62. pub peer_discovery_running: Mutex<bool>,
  63. /// Reference to configured [`ManualSession`]
  64. session_manual: ManualSessionPtr,
  65. /// Reference to configured [`InboundSession`]
  66. session_inbound: InboundSessionPtr,
  67. /// Reference to configured [`OutboundSession`]
  68. session_outbound: OutboundSessionPtr,
  69. /// Enable network debugging
  70. pub dnet_enabled: Mutex<bool>,
  71. /// The subscriber for which we can give dnet info over
  72. dnet_subscriber: SubscriberPtr<DnetEvent>,
  73. /// Greylist refinery process
  74. greylist_refinery: Arc<GreylistRefinery>,
  75. }
  76. impl P2p {
  77. /// Initialize a new p2p network.
  78. ///
  79. /// Initializes all sessions and protocols. Adds the protocols to the protocol
  80. /// registry, along with a bitflag session selector that includes or excludes
  81. /// sessions from seed, version, and address protocols.
  82. ///
  83. /// Creates a weak pointer to self that is used by all sessions to access the
  84. /// p2p parent class.
  85. pub async fn new(settings: Settings, executor: ExecutorPtr) -> P2pPtr {
  86. let settings = Arc::new(settings);
  87. let self_ = Arc::new(Self {
  88. executor,
  89. hosts: Hosts::new(settings.clone()),
  90. protocol_registry: ProtocolRegistry::new(),
  91. settings,
  92. peer_discovery_running: Mutex::new(false),
  93. session_manual: ManualSession::new(),
  94. session_inbound: InboundSession::new(),
  95. session_outbound: OutboundSession::new(),
  96. dnet_enabled: Mutex::new(false),
  97. dnet_subscriber: Subscriber::new(),
  98. greylist_refinery: GreylistRefinery::new(),
  99. });
  100. self_.session_manual.p2p.init(self_.clone());
  101. self_.session_inbound.p2p.init(self_.clone());
  102. self_.session_outbound.p2p.init(self_.clone());
  103. self_.greylist_refinery.p2p.init(self_.clone());
  104. register_default_protocols(self_.clone()).await;
  105. self_
  106. }
  107. /// Starts inbound, outbound, and manual sessions.
  108. pub async fn start(self: Arc<Self>) -> Result<()> {
  109. debug!(target: "net::p2p::start()", "P2P::start() [BEGIN]");
  110. info!(target: "net::p2p::start()", "[P2P] Starting P2P subsystem");
  111. // First attempt any set manual connections
  112. for peer in &self.settings.peers {
  113. self.session_manual().connect(peer.clone()).await;
  114. }
  115. // Start the inbound session
  116. if let Err(err) = self.session_inbound().start().await {
  117. error!(target: "net::p2p::start()", "Failed to start inbound session!: {}", err);
  118. self.session_manual().stop().await;
  119. return Err(err)
  120. }
  121. info!(target: "net::p2p::start()", "Starting greylist refinery process");
  122. self.greylist_refinery.clone().start().await;
  123. // Start the outbound session
  124. self.session_outbound().start().await;
  125. info!(target: "net::p2p::start()", "[P2P] P2P subsystem started");
  126. Ok(())
  127. }
  128. /// Reseed the P2P network.
  129. pub async fn seed(self: Arc<Self>) -> Result<()> {
  130. debug!(target: "net::p2p::seed()", "P2P::seed() [BEGIN]");
  131. info!(target: "net::p2p::seed()", "[P2P] Seeding P2P subsystem");
  132. // Start seed session
  133. let seed = SeedSyncSession::new(Arc::downgrade(&self));
  134. // This will block until all seed queries have finished
  135. seed.start().await?;
  136. debug!(target: "net::p2p::seed()", "P2P::seed() [END]");
  137. Ok(())
  138. }
  139. /// Stop the running P2P subsystem
  140. pub async fn stop(&self) {
  141. // Stop the sessions
  142. self.session_manual().stop().await;
  143. self.session_inbound().stop().await;
  144. self.session_outbound().stop().await;
  145. // Stop greylist refinery process
  146. self.greylist_refinery().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 mut channels = Vec::new();
  156. for channel in self.hosts().channels().await {
  157. if exclude_list.contains(channel.address()) {
  158. continue
  159. }
  160. channels.push(channel);
  161. }
  162. self.broadcast_to(message, &channels).await
  163. }
  164. /// Broadcast a message concurrently to all given peers.
  165. pub async fn broadcast_to<M: Message>(&self, message: &M, channel_list: &[ChannelPtr]) {
  166. if channel_list.is_empty() {
  167. warn!(target: "net::p2p::broadcast()", "[P2P] No connected channels found for broadcast");
  168. return
  169. }
  170. let futures = FuturesUnordered::new();
  171. for channel in channel_list {
  172. futures.push(channel.send(message).map_err(|e| {
  173. error!(
  174. target: "net::p2p::broadcast()",
  175. "[P2P] Broadcasting message to {} failed: {}",
  176. channel.address(), e
  177. );
  178. // If the channel is stopped then it should automatically die
  179. // and the session will remove it from p2p.
  180. assert!(channel.is_stopped());
  181. }));
  182. }
  183. let _results: Vec<_> = futures.collect().await;
  184. }
  185. pub async fn is_connected(&self) -> bool {
  186. !self.hosts().channels().await.is_empty()
  187. }
  188. /// Return an atomic pointer to the set network settings
  189. pub fn settings(&self) -> SettingsPtr {
  190. self.settings.clone()
  191. }
  192. /// Return an atomic pointer to the list of hosts
  193. pub fn hosts(&self) -> HostsPtr {
  194. self.hosts.clone()
  195. }
  196. /// Reference the global executor
  197. pub fn executor(&self) -> ExecutorPtr {
  198. self.executor.clone()
  199. }
  200. /// Return a reference to the internal protocol registry
  201. pub fn protocol_registry(&self) -> &ProtocolRegistry {
  202. &self.protocol_registry
  203. }
  204. /// Get pointer to manual session
  205. pub fn session_manual(&self) -> ManualSessionPtr {
  206. self.session_manual.clone()
  207. }
  208. /// Get pointer to inbound session
  209. pub fn session_inbound(&self) -> InboundSessionPtr {
  210. self.session_inbound.clone()
  211. }
  212. /// Get pointer to outbound session
  213. pub fn session_outbound(&self) -> OutboundSessionPtr {
  214. self.session_outbound.clone()
  215. }
  216. /// Get pointer to greylist refinery
  217. pub fn greylist_refinery(&self) -> GreylistRefineryPtr {
  218. self.greylist_refinery.clone()
  219. }
  220. /// Enable network debugging
  221. pub async fn dnet_enable(&self) {
  222. *self.dnet_enabled.lock().await = true;
  223. warn!("[P2P] Network debugging enabled!");
  224. }
  225. /// Disable network debugging
  226. pub async fn dnet_disable(&self) {
  227. *self.dnet_enabled.lock().await = false;
  228. warn!("[P2P] Network debugging disabled!");
  229. }
  230. /// Subscribe to dnet events
  231. pub async fn dnet_subscribe(&self) -> Subscription<DnetEvent> {
  232. self.dnet_subscriber.clone().subscribe().await
  233. }
  234. /// Send a dnet notification over the subscriber
  235. pub(super) async fn dnet_notify(&self, event: DnetEvent) {
  236. self.dnet_subscriber.notify(event).await;
  237. }
  238. }