p2p.rs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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::sync::{
  19. atomic::{AtomicBool, Ordering},
  20. Arc,
  21. };
  22. use futures::{stream::FuturesUnordered, TryFutureExt};
  23. use futures_rustls::rustls::crypto::{ring, CryptoProvider};
  24. use log::{debug, error, info, warn};
  25. use smol::{
  26. fs::{self, unix::PermissionsExt},
  27. lock::RwLock as AsyncRwLock,
  28. stream::StreamExt,
  29. };
  30. use url::Url;
  31. use super::{
  32. channel::ChannelPtr,
  33. dnet::DnetEvent,
  34. hosts::{Hosts, HostsPtr},
  35. message::Message,
  36. protocol::{protocol_registry::ProtocolRegistry, register_default_protocols},
  37. session::{
  38. InboundSession, InboundSessionPtr, ManualSession, ManualSessionPtr, OutboundSession,
  39. OutboundSessionPtr, RefineSession, RefineSessionPtr, SeedSyncSession, SeedSyncSessionPtr,
  40. },
  41. settings::Settings,
  42. };
  43. use crate::{
  44. system::{ExecutorPtr, Publisher, PublisherPtr, Subscription},
  45. util::path::expand_path,
  46. Result,
  47. };
  48. /// Atomic pointer to the p2p interface
  49. pub type P2pPtr = Arc<P2p>;
  50. /// Toplevel peer-to-peer networking interface
  51. pub struct P2p {
  52. /// Global multithreaded executor reference
  53. executor: ExecutorPtr,
  54. /// Known hosts (peers)
  55. hosts: HostsPtr,
  56. /// Protocol registry
  57. protocol_registry: ProtocolRegistry,
  58. /// P2P network settings
  59. settings: Arc<AsyncRwLock<Settings>>,
  60. /// Reference to configured [`ManualSession`]
  61. session_manual: ManualSessionPtr,
  62. /// Reference to configured [`InboundSession`]
  63. session_inbound: InboundSessionPtr,
  64. /// Reference to configured [`OutboundSession`]
  65. session_outbound: OutboundSessionPtr,
  66. /// Reference to configured [`RefineSession`]
  67. session_refine: RefineSessionPtr,
  68. /// Reference to configured [`SeedSyncSession`]
  69. session_seedsync: SeedSyncSessionPtr,
  70. /// Enable network debugging
  71. pub dnet_enabled: AtomicBool,
  72. /// The publisher for which we can give dnet info over
  73. dnet_publisher: PublisherPtr<DnetEvent>,
  74. }
  75. impl P2p {
  76. /// Initialize a new p2p network.
  77. ///
  78. /// Initializes all sessions and protocols. Adds the protocols to the protocol
  79. /// registry, along with a bitflag session selector that includes or excludes
  80. /// sessions from seed, version, and address protocols.
  81. ///
  82. /// Creates a weak pointer to self that is used by all sessions to access the
  83. /// p2p parent class.
  84. pub async fn new(settings: Settings, executor: ExecutorPtr) -> Result<P2pPtr> {
  85. // Create the datastore
  86. if let Some(ref datastore) = settings.datastore {
  87. let datastore = expand_path(datastore)?;
  88. fs::create_dir_all(&datastore).await?;
  89. fs::set_permissions(&datastore, PermissionsExt::from_mode(0o700)).await?;
  90. }
  91. // Register a CryptoProvider for rustls
  92. let _ = CryptoProvider::install_default(ring::default_provider());
  93. // Wrap the Settings into an Arc<RwLock>
  94. let settings = Arc::new(AsyncRwLock::new(settings));
  95. let self_ = Arc::new_cyclic(|p2p| Self {
  96. executor,
  97. hosts: Hosts::new(Arc::clone(&settings)),
  98. protocol_registry: ProtocolRegistry::new(),
  99. settings,
  100. session_manual: ManualSession::new(p2p.clone()),
  101. session_inbound: InboundSession::new(p2p.clone()),
  102. session_outbound: OutboundSession::new(p2p.clone()),
  103. session_refine: RefineSession::new(p2p.clone()),
  104. session_seedsync: SeedSyncSession::new(p2p.clone()),
  105. dnet_enabled: AtomicBool::new(false),
  106. dnet_publisher: Publisher::new(),
  107. });
  108. register_default_protocols(self_.clone()).await;
  109. Ok(self_)
  110. }
  111. /// Starts inbound, outbound, and manual sessions.
  112. pub async fn start(self: Arc<Self>) -> Result<()> {
  113. debug!(target: "net::p2p::start", "P2P::start() [BEGIN]");
  114. info!(target: "net::p2p::start", "[P2P] Starting P2P subsystem");
  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. return Err(err)
  119. }
  120. // Start the manual session
  121. self.session_manual().start().await;
  122. // Start the seedsync session. Seed connections will not
  123. // activate yet- they wait for a call to notify().
  124. self.session_seedsync().start().await;
  125. // Start the outbound session
  126. self.session_outbound().start().await;
  127. // Start the refine session
  128. self.session_refine().start().await;
  129. info!(target: "net::p2p::start", "[P2P] P2P subsystem started");
  130. Ok(())
  131. }
  132. /// Reseed the P2P network.
  133. pub async fn seed(self: Arc<Self>) {
  134. debug!(target: "net::p2p::seed()", "P2P::seed() [BEGIN]");
  135. info!(target: "net::p2p::seed()", "[P2P] Seeding P2P subsystem");
  136. // Activate the seed session.
  137. self.session_seedsync().notify().await;
  138. debug!(target: "net::p2p::seed()", "P2P::seed() [END]");
  139. }
  140. /// Stop the running P2P subsystem
  141. pub async fn stop(&self) {
  142. // Stop the sessions
  143. self.session_manual().stop().await;
  144. self.session_inbound().stop().await;
  145. self.session_seedsync().stop().await;
  146. self.session_outbound().stop().await;
  147. self.session_refine().stop().await;
  148. }
  149. /// Broadcasts a message concurrently across all active channels.
  150. pub async fn broadcast<M: Message>(&self, message: &M) {
  151. self.broadcast_with_exclude(message, &[]).await
  152. }
  153. /// Broadcasts a message concurrently across active channels, excluding
  154. /// the ones provided in `exclude_list`.
  155. pub async fn broadcast_with_exclude<M: Message>(&self, message: &M, exclude_list: &[Url]) {
  156. let mut channels = Vec::new();
  157. for channel in self.hosts().channels() {
  158. if exclude_list.contains(channel.address()) {
  159. continue
  160. }
  161. channels.push(channel);
  162. }
  163. self.broadcast_to(message, &channels).await
  164. }
  165. /// Broadcast a message concurrently to all given peers.
  166. pub async fn broadcast_to<M: Message>(&self, message: &M, channel_list: &[ChannelPtr]) {
  167. if channel_list.is_empty() {
  168. warn!(target: "net::p2p::broadcast()", "[P2P] No connected channels found for broadcast");
  169. return
  170. }
  171. let futures = FuturesUnordered::new();
  172. for channel in channel_list {
  173. futures.push(channel.send(message).map_err(|e| {
  174. error!(
  175. target: "net::p2p::broadcast()",
  176. "[P2P] Broadcasting message to {} failed: {}",
  177. channel.address(), e
  178. );
  179. // If the channel is stopped then it should automatically die
  180. // and the session will remove it from p2p.
  181. assert!(channel.is_stopped());
  182. }));
  183. }
  184. let _results: Vec<_> = futures.collect().await;
  185. }
  186. pub fn is_connected(&self) -> bool {
  187. !self.hosts().channels().is_empty()
  188. }
  189. /// Return an atomic pointer to the set network settings
  190. pub fn settings(&self) -> Arc<AsyncRwLock<Settings>> {
  191. Arc::clone(&self.settings)
  192. }
  193. /// Return an atomic pointer to the list of hosts
  194. pub fn hosts(&self) -> HostsPtr {
  195. self.hosts.clone()
  196. }
  197. /// Reference the global executor
  198. pub fn executor(&self) -> ExecutorPtr {
  199. self.executor.clone()
  200. }
  201. /// Return a reference to the internal protocol registry
  202. pub fn protocol_registry(&self) -> &ProtocolRegistry {
  203. &self.protocol_registry
  204. }
  205. /// Get pointer to manual session
  206. pub fn session_manual(&self) -> ManualSessionPtr {
  207. self.session_manual.clone()
  208. }
  209. /// Get pointer to inbound session
  210. pub fn session_inbound(&self) -> InboundSessionPtr {
  211. self.session_inbound.clone()
  212. }
  213. /// Get pointer to outbound session
  214. pub fn session_outbound(&self) -> OutboundSessionPtr {
  215. self.session_outbound.clone()
  216. }
  217. /// Get pointer to refine session
  218. pub fn session_refine(&self) -> RefineSessionPtr {
  219. self.session_refine.clone()
  220. }
  221. /// Get pointer to seedsync session
  222. pub fn session_seedsync(&self) -> SeedSyncSessionPtr {
  223. self.session_seedsync.clone()
  224. }
  225. /// Enable network debugging
  226. pub fn dnet_enable(&self) {
  227. self.dnet_enabled.store(true, Ordering::SeqCst);
  228. warn!("[P2P] Network debugging enabled!");
  229. }
  230. /// Disable network debugging
  231. pub fn dnet_disable(&self) {
  232. self.dnet_enabled.store(false, Ordering::SeqCst);
  233. warn!("[P2P] Network debugging disabled!");
  234. }
  235. /// Subscribe to dnet events
  236. pub async fn dnet_subscribe(&self) -> Subscription<DnetEvent> {
  237. self.dnet_publisher.clone().subscribe().await
  238. }
  239. /// Send a dnet notification over the publisher
  240. pub(super) async fn dnet_notify(&self, event: DnetEvent) {
  241. self.dnet_publisher.notify(event).await;
  242. }
  243. }