outbound_session.rs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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. //! Outbound connections session. Manages the creation of outbound sessions.
  19. //! Used to create an outbound session and to stop and start the session.
  20. //!
  21. //! Class consists of a weak pointer to the p2p interface and a vector of
  22. //! outbound connection slots. Using a weak pointer to p2p allows us to
  23. //! avoid circular dependencies. The vector of slots is wrapped in a mutex
  24. //! lock. This is switched on every time we instantiate a connection slot
  25. //! and insures that no other part of the program uses the slots at the
  26. //! same time.
  27. use std::{
  28. sync::{
  29. atomic::{AtomicU32, Ordering},
  30. Arc, Weak,
  31. },
  32. time::{Duration, Instant},
  33. };
  34. use async_trait::async_trait;
  35. use futures::stream::{FuturesUnordered, StreamExt};
  36. use smol::lock::Mutex;
  37. use tracing::{debug, error, warn};
  38. use url::Url;
  39. use super::{
  40. super::{
  41. channel::ChannelPtr,
  42. connector::Connector,
  43. dnet::{self, dnetev, DnetEvent},
  44. hosts::{HostColor, HostState},
  45. message::GetAddrsMessage,
  46. p2p::{P2p, P2pPtr},
  47. },
  48. Session, SessionBitFlag, SESSION_OUTBOUND,
  49. };
  50. use crate::{
  51. system::{sleep, timeout::timeout, CondVar, StoppableTask, StoppableTaskPtr},
  52. util::logger::verbose,
  53. Error, Result,
  54. };
  55. pub type OutboundSessionPtr = Arc<OutboundSession>;
  56. /// Defines outbound connections session.
  57. pub struct OutboundSession {
  58. /// Weak pointer to parent p2p object
  59. pub(in crate::net) p2p: Weak<P2p>,
  60. /// Outbound connection slots
  61. slots: Mutex<Vec<Arc<Slot>>>,
  62. /// Peer discovery task
  63. peer_discovery: Arc<PeerDiscovery>,
  64. }
  65. impl OutboundSession {
  66. /// Create a new outbound session.
  67. pub(crate) fn new(p2p: Weak<P2p>) -> OutboundSessionPtr {
  68. Arc::new_cyclic(|session| Self {
  69. p2p,
  70. slots: Mutex::new(Vec::new()),
  71. peer_discovery: PeerDiscovery::new(session.clone()),
  72. })
  73. }
  74. /// Start the outbound session. Runs the channel connect loop.
  75. pub(crate) async fn start(self: Arc<Self>) {
  76. let n_slots = self.p2p().settings().read().await.outbound_connections;
  77. verbose!(target: "net::outbound_session", "[P2P] Starting {n_slots} outbound connection slots.");
  78. // Activate mutex lock on connection slots.
  79. let mut slots = self.slots.lock().await;
  80. let mut futures = FuturesUnordered::new();
  81. let self_ = Arc::downgrade(&self);
  82. for i in 0..n_slots as u32 {
  83. let slot = Slot::new(self_.clone(), i);
  84. futures.push(slot.clone().start());
  85. slots.push(slot);
  86. }
  87. while (futures.next().await).is_some() {}
  88. self.peer_discovery.clone().start().await;
  89. }
  90. /// Stops the outbound session.
  91. pub(crate) async fn stop(&self) {
  92. debug!(target: "net::outbound_session", "Stopping outbound session..");
  93. let slots = &*self.slots.lock().await;
  94. let mut futures = FuturesUnordered::new();
  95. for slot in slots {
  96. futures.push(slot.clone().stop());
  97. }
  98. while (futures.next().await).is_some() {}
  99. self.peer_discovery.clone().stop().await;
  100. debug!(target: "net::outbound_session", "Outbound session stopped!");
  101. }
  102. pub async fn slot_info(&self) -> Vec<u32> {
  103. let mut info = Vec::new();
  104. let slots = &*self.slots.lock().await;
  105. for slot in slots {
  106. info.push(slot.channel_id.load(Ordering::Relaxed));
  107. }
  108. info
  109. }
  110. fn wakeup_peer_discovery(&self) {
  111. self.peer_discovery.notify()
  112. }
  113. async fn wakeup_slots(&self) {
  114. let slots = &*self.slots.lock().await;
  115. for slot in slots {
  116. slot.notify();
  117. }
  118. }
  119. }
  120. #[async_trait]
  121. impl Session for OutboundSession {
  122. fn p2p(&self) -> P2pPtr {
  123. self.p2p.upgrade().unwrap()
  124. }
  125. fn type_id(&self) -> SessionBitFlag {
  126. SESSION_OUTBOUND
  127. }
  128. }
  129. struct Slot {
  130. slot: u32,
  131. process: StoppableTaskPtr,
  132. wakeup_self: CondVar,
  133. session: Weak<OutboundSession>,
  134. connector: Connector,
  135. // For debugging
  136. channel_id: AtomicU32,
  137. }
  138. impl Slot {
  139. fn new(session: Weak<OutboundSession>, slot: u32) -> Arc<Self> {
  140. let settings = session.upgrade().unwrap().p2p().settings();
  141. Arc::new(Self {
  142. slot,
  143. process: StoppableTask::new(),
  144. wakeup_self: CondVar::new(),
  145. session: session.clone(),
  146. connector: Connector::new(settings, session),
  147. channel_id: AtomicU32::new(0),
  148. })
  149. }
  150. async fn start(self: Arc<Self>) {
  151. let ex = self.p2p().executor();
  152. self.process.clone().start(
  153. self.run(),
  154. |res| async {
  155. match res {
  156. Ok(()) | Err(Error::NetworkServiceStopped) => {}
  157. Err(e) => error!("net::outbound_session {e}"),
  158. }
  159. },
  160. Error::NetworkServiceStopped,
  161. ex,
  162. );
  163. }
  164. async fn stop(self: Arc<Self>) {
  165. self.connector.stop();
  166. self.process.stop().await;
  167. }
  168. /// Address selection algorithm that works as follows: up to
  169. /// gold_count, select from the goldlist. Up to white_count,
  170. /// select from the whitelist. For all other slots, select from
  171. /// the greylist. If none of these preferences are satisfied, do
  172. /// peer discovery.
  173. ///
  174. /// Selecting from the greylist for some % of the slots is necessary
  175. /// and healthy since we require the network retains some unreliable
  176. /// connections. A network that purely favors uptime over unreliable
  177. /// connections may be vulnerable to sybil by attackers with good uptime.
  178. async fn fetch_addrs(&self) -> Option<(Url, u64)> {
  179. let hosts = self.p2p().hosts();
  180. let slot = self.slot as usize;
  181. let container = &self.p2p().hosts().container;
  182. // Acquire Settings read lock
  183. let settings = self.p2p().settings().read_arc().await;
  184. let white_count = (settings.white_connect_percent * settings.outbound_connections) / 100;
  185. let gold_count = settings.gold_connect_count;
  186. let transports = settings.active_profiles.clone();
  187. let preference_strict = settings.slot_preference_strict;
  188. // Drop Settings read lock
  189. drop(settings);
  190. let grey_only = hosts.container.is_empty(HostColor::White) &&
  191. hosts.container.is_empty(HostColor::Gold) &&
  192. !hosts.container.is_empty(HostColor::Grey);
  193. // If we only have grey entries, select from the greylist. Otherwise,
  194. // use the preference defined in settings.
  195. let addrs = if grey_only && !preference_strict {
  196. container.fetch_with_schemes(HostColor::Grey as usize, &transports, None)
  197. } else if slot < gold_count {
  198. container.fetch_with_schemes(HostColor::Gold as usize, &transports, None)
  199. } else if slot < white_count {
  200. container.fetch_with_schemes(HostColor::White as usize, &transports, None)
  201. } else {
  202. container.fetch_with_schemes(HostColor::Grey as usize, &transports, None)
  203. };
  204. hosts.check_addrs(addrs).await
  205. }
  206. // We first try to make connections to the addresses on our gold list. We then find some
  207. // whitelist connections according to the whitelist percent default. Finally, any remaining
  208. // connections we make from the greylist.
  209. async fn run(self: Arc<Self>) -> Result<()> {
  210. let hosts = self.p2p().hosts();
  211. loop {
  212. // Activate the slot
  213. debug!(
  214. target: "net::outbound_session::try_connect()",
  215. "[P2P] Finding a host to connect to for outbound slot #{}",
  216. self.slot,
  217. );
  218. // Do peer discovery if we don't have any peers on the Grey, White or Gold list
  219. // (first time connecting to the network).
  220. if hosts.container.is_empty(HostColor::Grey) &&
  221. hosts.container.is_empty(HostColor::White) &&
  222. hosts.container.is_empty(HostColor::Gold)
  223. {
  224. dnetev!(self, OutboundSlotSleeping, {
  225. slot: self.slot,
  226. });
  227. self.wakeup_self.reset();
  228. // Peer discovery
  229. self.session().wakeup_peer_discovery();
  230. // Wait to be woken up by peer discovery
  231. self.wakeup_self.wait().await;
  232. continue
  233. }
  234. let addr = if let Some(addr) = self.fetch_addrs().await {
  235. debug!(target: "net::outbound_session::run()", "Fetched addr={}, slot #{}", addr.0,
  236. self.slot);
  237. addr
  238. } else {
  239. debug!(target: "net::outbound_session::run()", "No address found! Activating peer discovery...");
  240. dnetev!(self, OutboundSlotSleeping, {
  241. slot: self.slot,
  242. });
  243. self.wakeup_self.reset();
  244. // Peer discovery
  245. self.session().wakeup_peer_discovery();
  246. // Wait to be woken up by peer discovery
  247. self.wakeup_self.wait().await;
  248. continue
  249. };
  250. let host = addr.0;
  251. let last_seen = addr.1;
  252. let slot = self.slot;
  253. verbose!(
  254. target: "net::outbound_session::try_connect()",
  255. "[P2P] Connecting outbound slot #{slot} [{host}]"
  256. );
  257. dnetev!(self, OutboundSlotConnecting, {
  258. slot,
  259. addr: host.clone(),
  260. });
  261. let (_, channel) = match self.try_connect(host.clone(), last_seen).await {
  262. Ok(connect_info) => connect_info,
  263. Err(err) => {
  264. debug!(
  265. target: "net::outbound_session::try_connect()",
  266. "[P2P] Outbound slot #{slot} connection failed: {err}"
  267. );
  268. dnetev!(self, OutboundSlotDisconnected, {
  269. slot,
  270. err: err.to_string()
  271. });
  272. self.channel_id.store(0, Ordering::Relaxed);
  273. continue
  274. }
  275. };
  276. // At this point we've managed to connect.
  277. let stop_sub = channel.subscribe_stop().await?;
  278. verbose!(
  279. target: "net::outbound_session::try_connect()",
  280. "[P2P] Outbound slot #{slot} connected [{}]",
  281. channel.display_address()
  282. );
  283. dnetev!(self, OutboundSlotConnected, {
  284. slot: self.slot,
  285. addr: channel.display_address().clone(),
  286. channel_id: channel.info.id
  287. });
  288. // Setup new channel
  289. if let Err(err) =
  290. self.session().register_channel(channel.clone(), self.p2p().executor()).await
  291. {
  292. verbose!(
  293. target: "net::outbound_session",
  294. "[P2P] Outbound slot #{slot} disconnected: {err}"
  295. );
  296. dnetev!(self, OutboundSlotDisconnected, {
  297. slot: self.slot,
  298. err: err.to_string()
  299. });
  300. self.channel_id.store(0, Ordering::Relaxed);
  301. warn!(
  302. target: "net::outbound_session::try_connect()",
  303. "[P2P] Suspending addr=[{}] slot #{slot}",
  304. channel.display_address()
  305. );
  306. // Peer disconnected during the registry process. We'll downgrade this peer now.
  307. if let Err(e) = self
  308. .p2p()
  309. .hosts()
  310. .move_host(channel.address(), last_seen, HostColor::Grey)
  311. .await
  312. {
  313. warn!(target: "net::outbound_session", "Error while moving addr={} to greylist: {e}", channel.display_address());
  314. continue
  315. }
  316. // Mark its state as Suspend, which sends this node to the Refinery for processing.
  317. if let Err(e) =
  318. self.p2p().hosts().try_register(channel.address().clone(), HostState::Suspend)
  319. {
  320. warn!(target: "net::outbound_session", "Error while suspending addr={}: {e}", channel.display_address());
  321. }
  322. continue
  323. }
  324. self.channel_id.store(channel.info.id, Ordering::Relaxed);
  325. // Wait for channel to close
  326. stop_sub.receive().await;
  327. self.channel_id.store(0, Ordering::Relaxed);
  328. }
  329. }
  330. /// Start making an outbound connection, using provided [`Connector`].
  331. /// Tries to find a valid address to connect to, otherwise does peer
  332. /// discovery. The peer discovery loops until some peer we can connect
  333. /// to is found. Once connected, registers the channel, removes it from
  334. /// the list of pending channels, and starts sending messages across the
  335. /// channel. In case of any failures, a network error is returned and the
  336. /// main connect loop (parent of this function) will iterate again.
  337. async fn try_connect(&self, addr: Url, last_seen: u64) -> Result<(Url, ChannelPtr)> {
  338. match self.connector.connect(&addr).await {
  339. Ok((addr_final, channel)) => Ok((addr_final, channel)),
  340. Err(err) => {
  341. verbose!(
  342. target: "net::outbound_session::try_connect()",
  343. "[P2P] Unable to connect outbound slot #{} {err}",
  344. self.slot
  345. );
  346. // Immediately return if the Connector has stopped.
  347. // This indicates a shutdown of the P2P network and
  348. // should not result in hostlist modifications.
  349. if let Error::ConnectorStopped(message) = err {
  350. return Err(Error::ConnectFailed(message));
  351. }
  352. // At this point we failed to connect. We'll downgrade this peer now.
  353. self.p2p().hosts().move_host(&addr, last_seen, HostColor::Grey).await?;
  354. // Mark its state as Suspend, which sends it to the Refinery for processing.
  355. if let Err(e) = self.p2p().hosts().try_register(addr.clone(), HostState::Suspend) {
  356. warn!(target: "net::outbound_session::try_connect()", "Error while suspending addr={addr}: {e}");
  357. }
  358. // Notify that channel processing failed
  359. self.p2p().hosts().channel_publisher.notify(Err(err.clone())).await;
  360. Err(err)
  361. }
  362. }
  363. }
  364. fn notify(&self) {
  365. self.wakeup_self.notify()
  366. }
  367. fn session(&self) -> OutboundSessionPtr {
  368. self.session.upgrade().unwrap()
  369. }
  370. fn p2p(&self) -> P2pPtr {
  371. self.session().p2p()
  372. }
  373. }
  374. /// Defines a common interface for multiple peer discovery processes.
  375. ///
  376. /// NOTE: Currently only one Peer Discovery implementation exists. Making
  377. /// Peer Discovery generic enables us to support network swarming, since
  378. /// the peer discovery process will differ depending on whether it occurs
  379. /// on the overlay network or a subnet.
  380. #[async_trait]
  381. pub trait PeerDiscoveryBase {
  382. async fn start(self: Arc<Self>);
  383. async fn stop(self: Arc<Self>);
  384. async fn run(self: Arc<Self>);
  385. async fn wait(&self) -> bool;
  386. fn notify(&self);
  387. fn session(&self) -> OutboundSessionPtr;
  388. fn p2p(&self) -> P2pPtr;
  389. }
  390. /// Main PeerDiscovery process that loops through connected peers
  391. /// and sends out a `GetAddrs` when it is active. If there are no
  392. /// connected peers after two attempts, connect to our seed nodes
  393. /// and perform `SeedSyncSession`.
  394. struct PeerDiscovery {
  395. process: StoppableTaskPtr,
  396. wakeup_self: CondVar,
  397. session: Weak<OutboundSession>,
  398. }
  399. impl PeerDiscovery {
  400. fn new(session: Weak<OutboundSession>) -> Arc<Self> {
  401. Arc::new(Self { process: StoppableTask::new(), wakeup_self: CondVar::new(), session })
  402. }
  403. }
  404. #[async_trait]
  405. impl PeerDiscoveryBase for PeerDiscovery {
  406. async fn start(self: Arc<Self>) {
  407. let ex = self.p2p().executor();
  408. self.process.clone().start(
  409. async move {
  410. self.run().await;
  411. unreachable!();
  412. },
  413. // Ignore stop handler
  414. |_| async {},
  415. Error::NetworkServiceStopped,
  416. ex,
  417. );
  418. }
  419. async fn stop(self: Arc<Self>) {
  420. self.process.stop().await;
  421. }
  422. /// Activate peer discovery if not active already. For the first two
  423. /// attempts, this will loop through all connected P2P peers and send
  424. /// out a `GetAddrs` message to request more peers. Other parts of the
  425. /// P2P stack will then handle the incoming addresses and place them in
  426. /// the hosts list.
  427. ///
  428. /// On the third attempt, and if we still haven't made any connections,
  429. /// this function will then call `p2p.seed()` which triggers a
  430. /// `SeedSyncSession` that will connect to configured seeds and request
  431. /// peers from them.
  432. ///
  433. /// This function will also sleep `outbound_peer_discovery_attempt_time`
  434. /// seconds after broadcasting in order to let the P2P stack receive and
  435. /// work through the addresses it is expecting.
  436. async fn run(self: Arc<Self>) {
  437. let mut current_attempt = 0;
  438. loop {
  439. dnetev!(self, OutboundPeerDiscovery, {
  440. attempt: current_attempt,
  441. state: "wait",
  442. });
  443. // wait to be woken up by notify()
  444. let sleep_was_instant = self.wait().await;
  445. // Read the current P2P settings
  446. let settings = self.p2p().settings().read_arc().await;
  447. let outbound_peer_discovery_cooloff_time =
  448. settings.outbound_peer_discovery_cooloff_time;
  449. let outbound_peer_discovery_attempt_time =
  450. settings.outbound_peer_discovery_attempt_time;
  451. let outbound_connections = settings.outbound_connections;
  452. let getaddrs_max = settings.getaddrs_max;
  453. let active_profiles = settings.active_profiles.clone();
  454. let seeds = settings.seeds.clone();
  455. drop(settings);
  456. if sleep_was_instant {
  457. // Try again
  458. current_attempt += 1;
  459. } else {
  460. // reset back to start
  461. current_attempt = 1;
  462. }
  463. if current_attempt >= 4 {
  464. verbose!(
  465. target: "net::outbound_session::peer_discovery()",
  466. "[P2P] [PEER DISCOVERY] Sleeping and trying again. Attempt {current_attempt}"
  467. );
  468. dnetev!(self, OutboundPeerDiscovery, {
  469. attempt: current_attempt,
  470. state: "sleep",
  471. });
  472. sleep(outbound_peer_discovery_cooloff_time).await;
  473. current_attempt = 1;
  474. }
  475. // First 2 times try sending GetAddr to the network.
  476. // 3rd time do a seed sync (providing we have seeds
  477. // configured).
  478. if self.p2p().is_connected() && current_attempt <= 2 {
  479. // Broadcast the GetAddrs message to all active peers.
  480. // If we have no active peers, we will perform a SeedSyncSession instead.
  481. verbose!(
  482. target: "net::outbound_session::peer_discovery()",
  483. "[P2P] [PEER DISCOVERY] Asking peers for new peers to connect to...");
  484. dnetev!(self, OutboundPeerDiscovery, {
  485. attempt: current_attempt,
  486. state: "getaddr",
  487. });
  488. let get_addrs = GetAddrsMessage {
  489. max: getaddrs_max.unwrap_or(outbound_connections.min(u32::MAX as usize) as u32),
  490. transports: active_profiles,
  491. };
  492. self.p2p().broadcast(&get_addrs).await;
  493. // Wait for a hosts store update event
  494. let store_sub = self.p2p().hosts().subscribe_store().await;
  495. let result = timeout(
  496. Duration::from_secs(outbound_peer_discovery_attempt_time),
  497. store_sub.receive(),
  498. )
  499. .await;
  500. match result {
  501. Ok(addrs_len) => {
  502. verbose!(
  503. target: "net::outbound_session::peer_discovery()",
  504. "[P2P] [PEER DISCOVERY] Discovered {addrs_len} peers"
  505. );
  506. }
  507. Err(_) => {
  508. warn!(
  509. target: "net::outbound_session::peer_discovery()",
  510. "[P2P] [PEER DISCOVERY] Waiting for addrs timed out."
  511. );
  512. // Just do seed next time
  513. current_attempt = 3;
  514. }
  515. }
  516. // NOTE: not every call to subscribe() in net/ has a
  517. // corresponding unsubscribe(). To do this we need async
  518. // Drop. For now it's sufficient for publishers to be
  519. // de-allocated when the Session completes.
  520. store_sub.unsubscribe().await;
  521. } else if !seeds.is_empty() {
  522. verbose!(
  523. target: "net::outbound_session::peer_discovery()",
  524. "[P2P] [PEER DISCOVERY] Asking seeds for new peers to connect to...");
  525. dnetev!(self, OutboundPeerDiscovery, {
  526. attempt: current_attempt,
  527. state: "seed",
  528. });
  529. self.p2p().seed().await;
  530. }
  531. self.wakeup_self.reset();
  532. self.session().wakeup_slots().await;
  533. // Give some time for new connections to be established
  534. sleep(outbound_peer_discovery_attempt_time).await;
  535. }
  536. }
  537. /// Blocks execution until we receive a notification from notify().
  538. /// `wakeup_self.wait()` resets the condition variable (`CondVar`) and waits
  539. /// for a call from `notify()`. Returns `true` if the function completed
  540. /// instantly (i.e. no wait occured). Returns false otherwise.
  541. async fn wait(&self) -> bool {
  542. let wakeup_start = Instant::now();
  543. self.wakeup_self.wait().await;
  544. let wakeup_end = Instant::now();
  545. let epsilon = Duration::from_millis(200);
  546. wakeup_end - wakeup_start <= epsilon
  547. }
  548. /// Wakeup peer discovery by sending a notification to `wakeup_self`.
  549. /// Uses the underlying `CondVar` method `notify()`. Subsequent calls
  550. /// to this do nothing until `wait()` is called.
  551. fn notify(&self) {
  552. self.wakeup_self.notify()
  553. }
  554. fn session(&self) -> OutboundSessionPtr {
  555. self.session.upgrade().unwrap()
  556. }
  557. fn p2p(&self) -> P2pPtr {
  558. self.session().p2p()
  559. }
  560. }