outbound_session.rs 25 KB

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