outbound_session.rs 25 KB

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