p2p.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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::sync::{
  19. atomic::{AtomicBool, Ordering},
  20. Arc,
  21. };
  22. use futures::{stream::FuturesUnordered, TryFutureExt};
  23. use futures_rustls::rustls::crypto::{ring, CryptoProvider};
  24. use smol::{fs, lock::RwLock as AsyncRwLock, stream::StreamExt};
  25. use tracing::{debug, error, warn};
  26. use url::Url;
  27. use super::{
  28. channel::ChannelPtr,
  29. dnet::DnetEvent,
  30. hosts::{Hosts, HostsPtr},
  31. message::{Message, SerializedMessage},
  32. protocol::{protocol_registry::ProtocolRegistry, register_default_protocols},
  33. session::{
  34. DirectSession, DirectSessionPtr, InboundSession, InboundSessionPtr, ManualSession,
  35. ManualSessionPtr, OutboundSession, OutboundSessionPtr, RefineSession, RefineSessionPtr,
  36. SeedSyncSession, SeedSyncSessionPtr,
  37. },
  38. settings::Settings,
  39. };
  40. use crate::{
  41. system::{ExecutorPtr, Publisher, PublisherPtr, Subscription},
  42. util::{logger::verbose, path::expand_path},
  43. Result,
  44. };
  45. #[cfg(target_family = "unix")]
  46. use smol::fs::unix::PermissionsExt;
  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. /// Known hosts (peers)
  54. hosts: HostsPtr,
  55. /// Protocol registry
  56. protocol_registry: ProtocolRegistry,
  57. /// P2P network settings
  58. settings: Arc<AsyncRwLock<Settings>>,
  59. /// Reference to configured [`ManualSession`]
  60. session_manual: ManualSessionPtr,
  61. /// Reference to configured [`InboundSession`]
  62. session_inbound: InboundSessionPtr,
  63. /// Reference to configured [`OutboundSession`]
  64. session_outbound: OutboundSessionPtr,
  65. /// Reference to configured [`RefineSession`]
  66. session_refine: RefineSessionPtr,
  67. /// Reference to configured [`SeedSyncSession`]
  68. session_seedsync: SeedSyncSessionPtr,
  69. /// Reference to configured [`DirectSession`]
  70. session_direct: DirectSessionPtr,
  71. /// Enable network debugging
  72. pub dnet_enabled: AtomicBool,
  73. /// The publisher for which we can give dnet info over
  74. dnet_publisher: PublisherPtr<DnetEvent>,
  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) -> Result<P2pPtr> {
  86. // Create the datastore
  87. if let Some(ref datastore) = settings.p2p_datastore {
  88. let datastore = expand_path(datastore)?;
  89. fs::create_dir_all(&datastore).await?;
  90. // Windows only has readonly so don't worry about it
  91. #[cfg(target_family = "unix")]
  92. fs::set_permissions(&datastore, PermissionsExt::from_mode(0o700)).await?;
  93. }
  94. // Register a CryptoProvider for rustls
  95. let _ = CryptoProvider::install_default(ring::default_provider());
  96. // Wrap the Settings into an Arc<RwLock>
  97. let settings = Arc::new(AsyncRwLock::new(settings));
  98. let self_ = Arc::new_cyclic(|p2p| Self {
  99. executor,
  100. hosts: Hosts::new(Arc::clone(&settings)),
  101. protocol_registry: ProtocolRegistry::new(),
  102. settings,
  103. session_manual: ManualSession::new(p2p.clone()),
  104. session_inbound: InboundSession::new(p2p.clone()),
  105. session_outbound: OutboundSession::new(p2p.clone()),
  106. session_refine: RefineSession::new(p2p.clone()),
  107. session_seedsync: SeedSyncSession::new(p2p.clone()),
  108. session_direct: DirectSession::new(p2p.clone()),
  109. dnet_enabled: AtomicBool::new(false),
  110. dnet_publisher: Publisher::new(),
  111. });
  112. register_default_protocols(self_.clone()).await;
  113. Ok(self_)
  114. }
  115. /// Starts inbound, outbound, and manual sessions.
  116. pub async fn start(self: Arc<Self>) -> Result<()> {
  117. debug!(target: "net::p2p::start", "P2P::start() [BEGIN] [magic_bytes={:?}]",
  118. self.settings.read().await.magic_bytes.0);
  119. verbose!(target: "net::p2p::start", "[P2P] Starting P2P subsystem");
  120. // Start the inbound session
  121. if let Err(err) = self.session_inbound().start().await {
  122. error!(target: "net::p2p::start", "Failed to start inbound session!: {err}");
  123. return Err(err)
  124. }
  125. // Start the manual session
  126. self.session_manual().start().await;
  127. // Start the seedsync session. Seed connections will not
  128. // activate yet- they wait for a call to notify().
  129. self.session_seedsync().start().await;
  130. // Start the outbound session
  131. self.session_outbound().start().await;
  132. // Start the refine session
  133. self.session_refine().start().await;
  134. // Start the direct session
  135. self.session_direct().start().await;
  136. verbose!(target: "net::p2p::start", "[P2P] P2P subsystem started successfully");
  137. Ok(())
  138. }
  139. /// Reseed the P2P network.
  140. pub async fn seed(self: Arc<Self>) {
  141. debug!(target: "net::p2p::seed", "P2P::seed() [BEGIN]");
  142. // Activate the seed session.
  143. self.session_seedsync().notify().await;
  144. debug!(target: "net::p2p::seed", "P2P::seed() [END]");
  145. }
  146. /// Stop the running P2P subsystem
  147. pub async fn stop(&self) {
  148. // Stop the sessions
  149. self.session_manual().stop().await;
  150. self.session_inbound().stop().await;
  151. self.session_seedsync().stop().await;
  152. self.session_outbound().stop().await;
  153. self.session_refine().stop().await;
  154. self.session_direct().stop().await;
  155. }
  156. /// Broadcasts a message concurrently across all active peers.
  157. pub async fn broadcast<M: Message>(&self, message: &M) {
  158. self.broadcast_with_exclude(message, &[]).await
  159. }
  160. /// Broadcasts a message concurrently across active peers, excluding
  161. /// the ones provided in `exclude_list`.
  162. pub async fn broadcast_with_exclude<M: Message>(&self, message: &M, exclude_list: &[Url]) {
  163. let mut channels = Vec::new();
  164. for channel in self.hosts().peers() {
  165. if exclude_list.contains(channel.address()) {
  166. continue
  167. }
  168. channels.push(channel);
  169. }
  170. self.broadcast_to(message, &channels).await
  171. }
  172. /// Broadcast a message concurrently to all given peers.
  173. pub async fn broadcast_to<M: Message>(&self, message: &M, channel_list: &[ChannelPtr]) {
  174. if channel_list.is_empty() {
  175. warn!(target: "net::p2p::broadcast", "[P2P] No connected channels found for broadcast");
  176. return
  177. }
  178. // Serialize the provided message
  179. let message = SerializedMessage::new(message).await;
  180. // Spawn a detached task to actually send the message to the channels,
  181. // so we don't block wiating channels that are rate limited.
  182. self.executor.spawn(broadcast_serialized_to::<M>(message, channel_list.to_vec())).detach();
  183. }
  184. /// Check whether this node has connections to any peers. This method will
  185. /// not report seedsync or refinery connections.
  186. pub fn is_connected(&self) -> bool {
  187. !self.hosts().peers().is_empty()
  188. }
  189. /// The number of connected peers. This means channels which are not seed or refine.
  190. pub fn peers_count(&self) -> usize {
  191. self.hosts().peers().len()
  192. }
  193. /// Return an atomic pointer to the set network settings
  194. pub fn settings(&self) -> Arc<AsyncRwLock<Settings>> {
  195. Arc::clone(&self.settings)
  196. }
  197. /// Return an atomic pointer to the list of hosts
  198. pub fn hosts(&self) -> HostsPtr {
  199. self.hosts.clone()
  200. }
  201. /// Reference the global executor
  202. pub fn executor(&self) -> ExecutorPtr {
  203. self.executor.clone()
  204. }
  205. /// Return a reference to the internal protocol registry
  206. pub fn protocol_registry(&self) -> &ProtocolRegistry {
  207. &self.protocol_registry
  208. }
  209. /// Get pointer to manual session
  210. pub fn session_manual(&self) -> ManualSessionPtr {
  211. self.session_manual.clone()
  212. }
  213. /// Get pointer to inbound session
  214. pub fn session_inbound(&self) -> InboundSessionPtr {
  215. self.session_inbound.clone()
  216. }
  217. /// Get pointer to outbound session
  218. pub fn session_outbound(&self) -> OutboundSessionPtr {
  219. self.session_outbound.clone()
  220. }
  221. /// Get pointer to refine session
  222. pub fn session_refine(&self) -> RefineSessionPtr {
  223. self.session_refine.clone()
  224. }
  225. /// Get pointer to seedsync session
  226. pub fn session_seedsync(&self) -> SeedSyncSessionPtr {
  227. self.session_seedsync.clone()
  228. }
  229. /// Get pointer to direct session
  230. pub fn session_direct(&self) -> DirectSessionPtr {
  231. self.session_direct.clone()
  232. }
  233. /// Enable network debugging
  234. pub fn dnet_enable(&self) {
  235. self.dnet_enabled.store(true, Ordering::SeqCst);
  236. warn!("[P2P] Network debugging enabled!");
  237. }
  238. /// Disable network debugging
  239. pub fn dnet_disable(&self) {
  240. self.dnet_enabled.store(false, Ordering::SeqCst);
  241. warn!("[P2P] Network debugging disabled!");
  242. }
  243. /// Subscribe to dnet events
  244. pub async fn dnet_subscribe(&self) -> Subscription<DnetEvent> {
  245. self.dnet_publisher.clone().subscribe().await
  246. }
  247. /// Send a dnet notification over the publisher
  248. pub(super) async fn dnet_notify(&self, event: DnetEvent) {
  249. self.dnet_publisher.notify(event).await;
  250. }
  251. /// Grab the channel pointer of provided channel ID, if it exists.
  252. pub fn get_channel(&self, id: u32) -> Option<ChannelPtr> {
  253. self.hosts.get_channel(id)
  254. }
  255. }
  256. /// Auxiliary function to broadcast a serialized message concurrently to all given peers.
  257. async fn broadcast_serialized_to<M: Message>(
  258. message: SerializedMessage,
  259. channel_list: Vec<ChannelPtr>,
  260. ) {
  261. let futures = FuturesUnordered::new();
  262. for channel in &channel_list {
  263. futures.push(
  264. channel
  265. .send_serialized(&message, &M::METERING_SCORE, &M::METERING_CONFIGURATION)
  266. .map_err(|e| {
  267. error!(
  268. target: "net::p2p::broadcast",
  269. "[P2P] Broadcasting message to {} failed: {e}",
  270. channel.display_address()
  271. );
  272. // If the channel is stopped then it should automatically die
  273. // and the session will remove it from p2p.
  274. assert!(channel.is_stopped());
  275. }),
  276. );
  277. }
  278. let _results: Vec<_> = futures.collect().await;
  279. }