outbound_session.rs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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, SystemTime},
  33. };
  34. use async_trait::async_trait;
  35. use log::{debug, error, info, trace, warn};
  36. use rand::{prelude::SliceRandom, rngs::OsRng};
  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. message::GetAddrsMessage,
  45. p2p::{P2p, P2pPtr},
  46. },
  47. Session, SessionBitFlag, SESSION_OUTBOUND,
  48. };
  49. use crate::{
  50. system::{
  51. sleep, timeout::timeout, CondVar, LazyWeak, StoppableTask, StoppableTaskPtr, Subscriber,
  52. SubscriberPtr,
  53. },
  54. Error, Result,
  55. };
  56. pub type OutboundSessionPtr = Arc<OutboundSession>;
  57. /// Defines outbound connections session.
  58. pub struct OutboundSession {
  59. /// Weak pointer to parent p2p object
  60. pub(in crate::net) p2p: LazyWeak<P2p>,
  61. /// Subscriber used to signal channels processing
  62. channel_subscriber: SubscriberPtr<Result<ChannelPtr>>,
  63. /// Outbound connection slots
  64. slots: Mutex<Vec<Arc<Slot>>>,
  65. /// Peer discovery task
  66. peer_discovery: Arc<PeerDiscovery>,
  67. }
  68. impl OutboundSession {
  69. /// Create a new outbound session.
  70. pub(crate) fn new() -> OutboundSessionPtr {
  71. let self_ = Arc::new(Self {
  72. p2p: LazyWeak::new(),
  73. channel_subscriber: Subscriber::new(),
  74. slots: Mutex::new(Vec::new()),
  75. peer_discovery: PeerDiscovery::new(),
  76. });
  77. self_.peer_discovery.session.init(self_.clone());
  78. self_
  79. }
  80. /// Start the outbound session. Runs the channel connect loop.
  81. pub(crate) async fn start(self: Arc<Self>) {
  82. let n_slots = self.p2p().settings().outbound_connections;
  83. info!(target: "net::outbound_session", "[P2P] Starting {} outbound connection slots.", n_slots);
  84. // Activate mutex lock on connection slots.
  85. let mut slots = self.slots.lock().await;
  86. let self_ = Arc::downgrade(&self);
  87. for i in 0..n_slots as u32 {
  88. let slot = Slot::new(self_.clone(), i);
  89. slot.clone().start().await;
  90. slots.push(slot);
  91. }
  92. self.peer_discovery.clone().start().await;
  93. }
  94. /// Stops the outbound session.
  95. pub(crate) async fn stop(&self) {
  96. let slots = &*self.slots.lock().await;
  97. for slot in slots {
  98. slot.clone().stop().await;
  99. }
  100. self.peer_discovery.clone().stop().await;
  101. }
  102. pub async fn slot_info(&self) -> Vec<u32> {
  103. let mut info = Vec::new();
  104. let slots = &*self.slots.lock().await;
  105. for slot in slots {
  106. info.push(slot.channel_id.load(Ordering::Relaxed));
  107. }
  108. info
  109. }
  110. fn wakeup_peer_discovery(&self) {
  111. self.peer_discovery.notify()
  112. }
  113. async fn wakeup_slots(&self) {
  114. let slots = &*self.slots.lock().await;
  115. for slot in slots {
  116. slot.notify();
  117. }
  118. }
  119. }
  120. #[async_trait]
  121. impl Session for OutboundSession {
  122. fn p2p(&self) -> P2pPtr {
  123. self.p2p.upgrade()
  124. }
  125. fn type_id(&self) -> SessionBitFlag {
  126. SESSION_OUTBOUND
  127. }
  128. }
  129. pub struct Slot {
  130. slot: u32,
  131. process: StoppableTaskPtr,
  132. wakeup_self: CondVar,
  133. session: Weak<OutboundSession>,
  134. // For debugging
  135. channel_id: AtomicU32,
  136. }
  137. impl Slot {
  138. fn new(session: Weak<OutboundSession>, slot: u32) -> Arc<Self> {
  139. Arc::new(Self {
  140. slot,
  141. process: StoppableTask::new(),
  142. wakeup_self: CondVar::new(),
  143. session,
  144. channel_id: AtomicU32::new(0),
  145. })
  146. }
  147. async fn start(self: Arc<Self>) {
  148. // TODO: way too many clones, look into making this implicit. See implicit-clone crate
  149. let ex = self.p2p().executor();
  150. self.process.clone().start(
  151. async move {
  152. self.run2().await;
  153. unreachable!();
  154. },
  155. // Ignore stop handler
  156. |_| async {},
  157. Error::NetworkServiceStopped,
  158. ex,
  159. );
  160. }
  161. async fn stop(self: Arc<Self>) {
  162. self.process.stop().await
  163. }
  164. async fn run(self: Arc<Self>) {
  165. // This is the main outbound connection loop where we try to establish
  166. // a connection in the slot. The `try_connect` function will block in
  167. // case the connection was sucessfully established. If it fails, then
  168. // we will wait for a defined number of seconds and try to fill the
  169. // slot again. This function should never exit during the lifetime of
  170. // the P2P network, as it is supposed to represent an outbound slot we
  171. // want to fill.
  172. // The actual connection logic and peer selection is in `try_connect`.
  173. // If the connection is successful, `try_connect` will wait for a stop
  174. // signal and then exit. Once it exits, we'll run `try_connect` again
  175. // and attempt to fill the slot with another peer.
  176. loop {
  177. // Activate the slot
  178. debug!(
  179. target: "net::outbound_session::try_connect()",
  180. "[P2P] Finding a host to connect to for outbound slot #{}",
  181. self.slot,
  182. );
  183. // Retrieve whitelisted outbound transports
  184. let transports = &self.p2p().settings().allowed_transports;
  185. // Find an address to connect to. We also do peer discovery here if needed.
  186. let addr = if let Some(addr) = self.fetch_address_with_lock(transports).await {
  187. addr
  188. } else {
  189. dnetev!(self, OutboundSlotSleeping, {
  190. slot: self.slot,
  191. });
  192. self.wakeup_self.reset();
  193. // Peer discovery
  194. self.session().wakeup_peer_discovery();
  195. // Wait to be woken up by peer discovery
  196. self.wakeup_self.wait().await;
  197. continue
  198. };
  199. info!(
  200. target: "net::outbound_session::try_connect()",
  201. "[P2P] Connecting outbound slot #{} [{}]",
  202. self.slot, addr,
  203. );
  204. dnetev!(self, OutboundSlotConnecting, {
  205. slot: self.slot,
  206. addr: addr.clone(),
  207. });
  208. let (addr_final, channel) = match self.try_connect(addr.clone()).await {
  209. Ok(connect_info) => connect_info,
  210. Err(err) => {
  211. error!(
  212. target: "net::outbound_session",
  213. "[P2P] Outbound slot #{} connection failed: {}",
  214. self.slot, err,
  215. );
  216. dnetev!(self, OutboundSlotDisconnected, {
  217. slot: self.slot,
  218. err: err.to_string()
  219. });
  220. self.channel_id.store(0, Ordering::Relaxed);
  221. continue
  222. }
  223. };
  224. info!(
  225. target: "net::outbound_session::try_connect()",
  226. "[P2P] Outbound slot #{} connected [{}]",
  227. self.slot, addr_final
  228. );
  229. dnetev!(self, OutboundSlotConnected, {
  230. slot: self.slot,
  231. addr: addr_final.clone(),
  232. channel_id: channel.info.id
  233. });
  234. let stop_sub = channel.subscribe_stop().await.expect("Channel should not be stopped");
  235. // Setup new channel
  236. if let Err(err) = self.setup_channel(addr, channel.clone()).await {
  237. info!(
  238. target: "net::outbound_session",
  239. "[P2P] Outbound slot #{} disconnected: {}",
  240. self.slot, err
  241. );
  242. dnetev!(self, OutboundSlotDisconnected, {
  243. slot: self.slot,
  244. err: err.to_string()
  245. });
  246. self.channel_id.store(0, Ordering::Relaxed);
  247. continue
  248. }
  249. self.channel_id.store(channel.info.id, Ordering::Relaxed);
  250. // Wait for channel to close
  251. stop_sub.receive().await;
  252. self.channel_id.store(0, Ordering::Relaxed);
  253. }
  254. }
  255. // Looks up whitelisted addresses. Tries to connect to them.
  256. // On success, updates the whitelist last_seen field.
  257. async fn run2(self: Arc<Self>) {
  258. // This is the main outbound connection loop where we try to establish
  259. // a connection in the slot. The `try_connect` function will block in
  260. // case the connection was sucessfully established. If it fails, then
  261. // we will wait for a defined number of seconds and try to fill the
  262. // slot again. This function should never exit during the lifetime of
  263. // the P2P network, as it is supposed to represent an outbound slot we
  264. // want to fill.
  265. // The actual connection logic and peer selection is in `try_connect`.
  266. // If the connection is successful, `try_connect` will wait for a stop
  267. // signal and then exit. Once it exits, we'll run `try_connect` again
  268. // and attempt to fill the slot with another peer.
  269. let hosts = self.p2p().hosts();
  270. loop {
  271. // Activate the slot
  272. debug!(
  273. target: "net::outbound_session::try_connect2()",
  274. "[P2P] Finding a host to connect to for outbound slot #{}",
  275. self.slot,
  276. );
  277. // Retrieve outbound transports
  278. let transports = &self.p2p().settings().allowed_transports;
  279. // Find a whitelisted address to connect to. We also do peer discovery here if needed.
  280. let (addr, last_seen) = if let Some(addr) =
  281. hosts.whitelist_fetch_address_with_lock(self.p2p(), transports).await
  282. {
  283. addr
  284. } else {
  285. dnetev!(self, OutboundSlotSleeping, {
  286. slot: self.slot,
  287. });
  288. self.wakeup_self.reset();
  289. // Peer discovery
  290. self.session().wakeup_peer_discovery();
  291. // Wait to be woken up by peer discovery
  292. self.wakeup_self.wait().await;
  293. continue
  294. };
  295. info!(
  296. target: "net::outbound_session::try_connect2()",
  297. "[P2P] Connecting outbound slot #{} [{}]",
  298. self.slot, addr,
  299. );
  300. dnetev!(self, OutboundSlotConnecting, {
  301. slot: self.slot,
  302. addr: addr.clone(),
  303. });
  304. let (addr_final, channel) =
  305. match self.try_connect2(addr.clone(), last_seen.clone()).await {
  306. Ok(connect_info) => connect_info,
  307. Err(err) => {
  308. error!(
  309. target: "net::outbound_session",
  310. "[P2P] Outbound slot #{} connection failed: {}",
  311. self.slot, err,
  312. );
  313. dnetev!(self, OutboundSlotDisconnected, {
  314. slot: self.slot,
  315. err: err.to_string()
  316. });
  317. self.channel_id.store(0, Ordering::Relaxed);
  318. continue
  319. }
  320. };
  321. info!(
  322. target: "net::outbound_session::try_connect2()",
  323. "[P2P] Outbound slot #{} connected [{}]",
  324. self.slot, addr_final
  325. );
  326. // Update the last_seen field for this whitelisted peer.
  327. // TODO: This peer should also be flagged as an "anchor" because we have been
  328. // able to establish a connection to it to it.
  329. let last_seen =
  330. SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
  331. hosts.whitelist_update(&addr_final, last_seen).await;
  332. dnetev!(self, OutboundSlotConnected, {
  333. slot: self.slot,
  334. addr: addr_final.clone(),
  335. channel_id: channel.info.id
  336. });
  337. let stop_sub = channel.subscribe_stop().await.expect("Channel should not be stopped");
  338. // Setup new channel
  339. if let Err(err) = self.setup_channel(addr, channel.clone()).await {
  340. info!(
  341. target: "net::outbound_session",
  342. "[P2P] Outbound slot #{} disconnected: {}",
  343. self.slot, err
  344. );
  345. dnetev!(self, OutboundSlotDisconnected, {
  346. slot: self.slot,
  347. err: err.to_string()
  348. });
  349. self.channel_id.store(0, Ordering::Relaxed);
  350. continue
  351. }
  352. self.channel_id.store(channel.info.id, Ordering::Relaxed);
  353. // Randomly select a peer on the greylist and probe it.
  354. // TODO: put this somewhere better.
  355. // TODO: This frequency of this call can be set in net::Settings.
  356. // Right now we are just doing at the same frequency of outbound_connect_timeout.
  357. let ex = self.p2p().executor();
  358. hosts.refresh_greylist(self.p2p(), ex).await;
  359. // Wait for channel to close
  360. stop_sub.receive().await;
  361. self.channel_id.store(0, Ordering::Relaxed);
  362. }
  363. }
  364. /// Start making an outbound connection, using provided [`Connector`].
  365. /// Tries to find a valid address to connect to, otherwise does peer
  366. /// discovery. The peer discovery loops until some peer we can connect
  367. /// to is found. Once connected, registers the channel, removes it from
  368. /// the list of pending channels, and starts sending messages across the
  369. /// channel. In case of any failures, a network error is returned and the
  370. /// main connect loop (parent of this function) will iterate again.
  371. async fn try_connect(&self, addr: Url) -> Result<(Url, ChannelPtr)> {
  372. let parent = Arc::downgrade(&self.session());
  373. let connector = Connector::new(self.p2p().settings(), parent);
  374. match connector.connect(&addr).await {
  375. Ok((addr_final, channel)) => Ok((addr_final, channel)),
  376. Err(e) => {
  377. error!(
  378. target: "net::outbound_session::try_connect()",
  379. "[P2P] Unable to connect outbound slot #{} [{}]: {}",
  380. self.slot, addr, e
  381. );
  382. // At this point we failed to connect. We'll quarantine this peer now.
  383. self.p2p().hosts().quarantine(&addr).await;
  384. // Remove connection from pending
  385. self.p2p().remove_pending(&addr).await;
  386. // Notify that channel processing failed
  387. self.session().channel_subscriber.notify(Err(Error::ConnectFailed)).await;
  388. Err(Error::ConnectFailed)
  389. }
  390. }
  391. }
  392. async fn try_connect2(&self, addr: Url, last_seen: u64) -> Result<(Url, ChannelPtr)> {
  393. let parent = Arc::downgrade(&self.session());
  394. let connector = Connector::new(self.p2p().settings(), parent);
  395. match connector.connect(&addr).await {
  396. Ok((addr_final, channel)) => Ok((addr_final, channel)),
  397. Err(e) => {
  398. error!(
  399. target: "net::outbound_session::try_connect2()",
  400. "[P2P] Unable to connect outbound slot #{} [{}]: {}",
  401. self.slot, addr, e
  402. );
  403. // At this point we failed to connect.
  404. // Remove this item from the whitelist and add it to the greylist.
  405. self.p2p().hosts().whitelist_downgrade(&addr).await;
  406. // Remove connection from pending
  407. self.p2p().remove_pending(&addr).await;
  408. // Notify that channel processing failed
  409. self.session().channel_subscriber.notify(Err(Error::ConnectFailed)).await;
  410. Err(Error::ConnectFailed)
  411. }
  412. }
  413. }
  414. async fn setup_channel(&self, addr: Url, channel: ChannelPtr) -> Result<()> {
  415. // Register the new channel
  416. self.session().register_channel(channel.clone(), self.p2p().executor()).await?;
  417. // Channel is now connected but not yet setup
  418. // Remove pending lock since register_channel will add the channel to p2p
  419. self.p2p().remove_pending(&addr).await;
  420. // Notify that channel processing has been finished
  421. self.session().channel_subscriber.notify(Ok(channel)).await;
  422. Ok(())
  423. }
  424. /// Loops through host addresses to find an outbound address that we can
  425. /// connect to. Check whether the address is valid by making sure it isn't
  426. /// our own inbound address, then checks whether it is already connected
  427. /// (exists) or connecting (pending).
  428. /// Lastly adds matching address to the pending list.
  429. /// TODO: this method should go in hosts
  430. async fn fetch_address_with_lock(&self, transports: &[String]) -> Option<Url> {
  431. let p2p = self.p2p();
  432. // Collect hosts
  433. let mut hosts = vec![];
  434. // If transport mixing is enabled, then for example we're allowed to
  435. // use tor:// to connect to tcp:// and tor+tls:// to connect to tcp+tls://.
  436. // However, **do not** mix tor:// and tcp+tls://, nor tor+tls:// and tcp://.
  437. let transport_mixing = p2p.settings().transport_mixing;
  438. macro_rules! mix_transport {
  439. ($a:expr, $b:expr) => {
  440. if transports.contains(&$a.to_string()) && transport_mixing {
  441. let mut a_to_b = p2p.hosts().fetch_with_schemes(&[$b.to_string()], None).await;
  442. for addr in a_to_b.iter_mut() {
  443. addr.set_scheme($a).unwrap();
  444. hosts.push(addr.clone());
  445. }
  446. }
  447. };
  448. }
  449. mix_transport!("tor", "tcp");
  450. mix_transport!("tor+tls", "tcp+tls");
  451. mix_transport!("nym", "tcp");
  452. mix_transport!("nym+tls", "tcp+tls");
  453. // And now the actual requested transports
  454. for addr in p2p.hosts().fetch_with_schemes(transports, None).await {
  455. hosts.push(addr);
  456. }
  457. // Randomize hosts list. Do not try to connect in a deterministic order.
  458. // This is healthier for multiple slots to not compete for the same addrs.
  459. hosts.shuffle(&mut OsRng);
  460. // Try to find an unused host in the set.
  461. for host in hosts.iter() {
  462. // Check if we already have this connection established
  463. if p2p.exists(host).await {
  464. trace!(
  465. target: "net::outbound_session::fetch_address_with_lock()",
  466. "Host '{}' exists so skipping",
  467. host
  468. );
  469. continue
  470. }
  471. // Check if we already have this configured as a manual peer
  472. if p2p.settings().peers.contains(host) {
  473. trace!(
  474. target: "net::outbound_session::fetch_address_with_lock()",
  475. "Host '{}' configured as manual peer so skipping",
  476. host
  477. );
  478. continue
  479. }
  480. // Obtain a lock on this address to prevent duplicate connection
  481. if !p2p.add_pending(host).await {
  482. trace!(
  483. target: "net::outbound_session::fetch_address_with_lock()",
  484. "Host '{}' pending so skipping",
  485. host
  486. );
  487. continue
  488. }
  489. trace!(
  490. target: "net::outbound_session::fetch_address_with_lock()",
  491. "Found valid host '{}",
  492. host
  493. );
  494. return Some(host.clone())
  495. }
  496. None
  497. }
  498. fn notify(&self) {
  499. self.wakeup_self.notify()
  500. }
  501. fn session(&self) -> OutboundSessionPtr {
  502. self.session.upgrade().unwrap()
  503. }
  504. fn p2p(&self) -> P2pPtr {
  505. self.session().p2p()
  506. }
  507. }
  508. struct PeerDiscovery {
  509. process: StoppableTaskPtr,
  510. wakeup_self: CondVar,
  511. session: LazyWeak<OutboundSession>,
  512. }
  513. impl PeerDiscovery {
  514. fn new() -> Arc<Self> {
  515. Arc::new(Self {
  516. process: StoppableTask::new(),
  517. wakeup_self: CondVar::new(),
  518. session: LazyWeak::new(),
  519. })
  520. }
  521. async fn start(self: Arc<Self>) {
  522. let ex = self.p2p().executor();
  523. self.process.clone().start(
  524. async move {
  525. self.run().await;
  526. unreachable!();
  527. },
  528. // Ignore stop handler
  529. |_| async {},
  530. Error::NetworkServiceStopped,
  531. ex,
  532. );
  533. }
  534. async fn stop(self: Arc<Self>) {
  535. self.process.stop().await
  536. }
  537. /// Activate peer discovery if not active already. This will loop through all
  538. /// connected P2P channels and send out a `GetAddrs` message to request more
  539. /// peers. Other parts of the P2P stack will then handle the incoming addresses
  540. /// and place them in the hosts list.
  541. /// This function will also sleep `Settings::outbound_connect_timeout` seconds
  542. /// after broadcasting in order to let the P2P stack receive and work through
  543. /// the addresses it is expecting.
  544. async fn run(self: Arc<Self>) {
  545. let mut current_attempt = 0;
  546. loop {
  547. dnetev!(self, OutboundPeerDiscovery, {
  548. attempt: current_attempt,
  549. state: "wait",
  550. });
  551. // wait to be woken up by notify()
  552. let sleep_was_instant = self.wait().await;
  553. let p2p = self.p2p();
  554. if sleep_was_instant {
  555. // Try again
  556. current_attempt += 1;
  557. } else {
  558. // reset back to start
  559. current_attempt = 1;
  560. }
  561. if current_attempt >= 4 {
  562. info!(
  563. target: "net::outbound_session::peer_discovery()",
  564. "[P2P] Sleeping and trying again..."
  565. );
  566. dnetev!(self, OutboundPeerDiscovery, {
  567. attempt: current_attempt,
  568. state: "sleep",
  569. });
  570. sleep(p2p.settings().outbound_peer_discovery_cooloff_time).await;
  571. current_attempt = 1;
  572. }
  573. // First 2 times try sending GetAddr to the network.
  574. // 3rd time do a seed sync.
  575. if p2p.is_connected().await && current_attempt <= 2 {
  576. // Broadcast the GetAddrs message to all active channels.
  577. // If we have no active channels, we will perform a SeedSyncSession instead.
  578. info!(
  579. target: "net::outbound_session::peer_discovery()",
  580. "[P2P] Requesting addrs from active channels. Attempt: {}",
  581. current_attempt
  582. );
  583. dnetev!(self, OutboundPeerDiscovery, {
  584. attempt: current_attempt,
  585. state: "getaddr",
  586. });
  587. let get_addrs = GetAddrsMessage {
  588. max: p2p.settings().outbound_connections as u32,
  589. transports: p2p.settings().allowed_transports.clone(),
  590. };
  591. p2p.broadcast(&get_addrs).await;
  592. // Wait for a hosts store update event
  593. let store_sub = self.p2p().hosts().subscribe_store().await.unwrap();
  594. let result = timeout(
  595. Duration::from_secs(p2p.settings().outbound_peer_discovery_attempt_time),
  596. store_sub.receive(),
  597. )
  598. .await;
  599. match result {
  600. Ok(addrs_len) => {
  601. info!(
  602. target: "net::outbound_session::peer_discovery()",
  603. "[P2P] Discovered {} addrs", addrs_len
  604. );
  605. }
  606. Err(_) => {
  607. warn!(
  608. target: "net::outbound_session::peer_discovery()",
  609. "[P2P] Peer discovery waiting for addrs timed out."
  610. );
  611. // TODO: Just do seed next time
  612. }
  613. }
  614. // TODO: check every subscribe() call has a corresponding unsubscribe()
  615. store_sub.unsubscribe().await;
  616. } else {
  617. info!(
  618. target: "net::outbound_session::peer_discovery()",
  619. "[P2P] Seeding hosts. Attempt: {}",
  620. current_attempt
  621. );
  622. dnetev!(self, OutboundPeerDiscovery, {
  623. attempt: current_attempt,
  624. state: "seed",
  625. });
  626. match p2p.clone().seed().await {
  627. Ok(()) => {
  628. info!(
  629. target: "net::outbound_session::peer_discovery()",
  630. "[P2P] Seeding hosts successful."
  631. );
  632. }
  633. Err(err) => {
  634. error!(
  635. target: "net::outbound_session::peer_discovery()",
  636. "[P2P] Network reseed failed: {}", err,
  637. );
  638. }
  639. }
  640. }
  641. self.wakeup_self.reset();
  642. self.session().wakeup_slots().await;
  643. // Give some time for new connections to be established
  644. sleep(p2p.settings().outbound_peer_discovery_attempt_time).await;
  645. }
  646. }
  647. async fn wait(&self) -> bool {
  648. let wakeup_start = Instant::now();
  649. self.wakeup_self.wait().await;
  650. let wakeup_end = Instant::now();
  651. let epsilon = Duration::from_millis(200);
  652. wakeup_end - wakeup_start <= epsilon
  653. }
  654. fn notify(&self) {
  655. self.wakeup_self.notify()
  656. }
  657. fn session(&self) -> OutboundSessionPtr {
  658. self.session.upgrade()
  659. }
  660. fn p2p(&self) -> P2pPtr {
  661. self.session().p2p()
  662. }
  663. }