outbound_session.rs 25 KB

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