outbound_session.rs 23 KB

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