outbound_session.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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},
  33. };
  34. use async_trait::async_trait;
  35. use log::{debug, error, info, warn};
  36. use smol::lock::Mutex;
  37. use url::Url;
  38. use super::{
  39. super::{
  40. channel::ChannelPtr,
  41. connector::Connector,
  42. dnet::{self, dnetev, DnetEvent},
  43. message::GetAddrsMessage,
  44. p2p::{P2p, P2pPtr},
  45. },
  46. Session, SessionBitFlag, SESSION_OUTBOUND,
  47. };
  48. use crate::{
  49. system::{
  50. sleep, timeout::timeout, CondVar, LazyWeak, StoppableTask, StoppableTaskPtr, Subscriber,
  51. SubscriberPtr,
  52. },
  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: LazyWeak<P2p>,
  60. /// Subscriber used to signal channels processing
  61. channel_subscriber: SubscriberPtr<Result<ChannelPtr>>,
  62. /// Outbound connection slots
  63. slots: Mutex<Vec<Arc<Slot>>>,
  64. /// Peer discovery task
  65. peer_discovery: Arc<PeerDiscovery>,
  66. }
  67. impl OutboundSession {
  68. /// Create a new outbound session.
  69. pub(crate) fn new() -> OutboundSessionPtr {
  70. let self_ = Arc::new(Self {
  71. p2p: LazyWeak::new(),
  72. channel_subscriber: Subscriber::new(),
  73. slots: Mutex::new(Vec::new()),
  74. peer_discovery: PeerDiscovery::new(),
  75. });
  76. self_.peer_discovery.session.init(self_.clone());
  77. self_
  78. }
  79. /// Start the outbound session. Runs the channel connect loop.
  80. pub(crate) async fn start(self: Arc<Self>) {
  81. let n_slots = self.p2p().settings().outbound_connections;
  82. info!(target: "net::outbound_session", "[P2P] Starting {} outbound connection slots.", n_slots);
  83. // Activate mutex lock on connection slots.
  84. let mut slots = self.slots.lock().await;
  85. let self_ = Arc::downgrade(&self);
  86. for i in 0..n_slots as u32 {
  87. let slot = Slot::new(self_.clone(), i);
  88. slot.clone().start().await;
  89. slots.push(slot);
  90. }
  91. self.peer_discovery.clone().start().await;
  92. }
  93. /// Stops the outbound session.
  94. pub(crate) async fn stop(&self) {
  95. let slots = &*self.slots.lock().await;
  96. for slot in slots {
  97. slot.clone().stop().await;
  98. }
  99. self.peer_discovery.clone().stop().await;
  100. }
  101. pub async fn slot_info(&self) -> Vec<u32> {
  102. let mut info = Vec::new();
  103. let slots = &*self.slots.lock().await;
  104. for slot in slots {
  105. info.push(slot.channel_id.load(Ordering::Relaxed));
  106. }
  107. info
  108. }
  109. fn wakeup_peer_discovery(&self) {
  110. self.peer_discovery.notify()
  111. }
  112. async fn wakeup_slots(&self) {
  113. let slots = &*self.slots.lock().await;
  114. for slot in slots {
  115. slot.notify();
  116. }
  117. }
  118. }
  119. #[async_trait]
  120. impl Session for OutboundSession {
  121. fn p2p(&self) -> P2pPtr {
  122. self.p2p.upgrade()
  123. }
  124. fn type_id(&self) -> SessionBitFlag {
  125. SESSION_OUTBOUND
  126. }
  127. }
  128. pub struct Slot {
  129. slot: u32,
  130. process: StoppableTaskPtr,
  131. wakeup_self: CondVar,
  132. session: Weak<OutboundSession>,
  133. // For debugging
  134. channel_id: AtomicU32,
  135. }
  136. impl Slot {
  137. fn new(session: Weak<OutboundSession>, slot: u32) -> Arc<Self> {
  138. Arc::new(Self {
  139. slot,
  140. process: StoppableTask::new(),
  141. wakeup_self: CondVar::new(),
  142. session,
  143. channel_id: AtomicU32::new(0),
  144. })
  145. }
  146. async fn start(self: Arc<Self>) {
  147. // TODO: way too many clones, look into making this implicit. See implicit-clone crate
  148. let ex = self.p2p().executor();
  149. self.process.clone().start(
  150. async move {
  151. self.run().await;
  152. unreachable!();
  153. },
  154. // Ignore stop handler
  155. |_| async {},
  156. Error::NetworkServiceStopped,
  157. ex,
  158. );
  159. }
  160. async fn stop(self: Arc<Self>) {
  161. self.process.stop().await
  162. }
  163. async fn fetch_address(&self, slot_count: usize, transports: &[String]) -> Option<(Url, u64)> {
  164. let hosts = self.p2p().hosts();
  165. let connects = self.p2p().settings().outbound_connections;
  166. let white_count = connects * self.p2p().settings().white_connection_percent / 100;
  167. let addrs = {
  168. // Up to anchor_connection_count connections:
  169. //
  170. // Select from the anchorlist
  171. // If the anchorlist is empty, select from the whitelist
  172. // If the whitelist is empty, select from the greylist
  173. // If the greylist is empty, do peer discovery
  174. if slot_count < self.p2p().settings().anchor_connection_count {
  175. debug!(target: "net::outbound_session::fetch_address()",
  176. "First two connections- prefer anchor connections");
  177. hosts.anchorlist_fetch_address(transports).await
  178. }
  179. // Up to white_connection_percent connections:
  180. //
  181. // Select from the whitelist
  182. // If the whitelist is empty, select from the greylist
  183. // If the greylist is empty, do peer discovery
  184. else if slot_count < white_count {
  185. debug!(target: "net::outbound_session::fetch_address()",
  186. "Next N connections- prefer white connections");
  187. hosts.whitelist_fetch_address(transports).await
  188. }
  189. // All other connections:
  190. //
  191. // Select from the greylist
  192. // If the greylist is empty, do peer discovery
  193. else {
  194. debug!(target: "net::outbound_session::fetch_address()",
  195. "All other connections- get grey connections");
  196. hosts.greylist_fetch_address(transports).await
  197. }
  198. };
  199. // Check whether:
  200. // * we already have this connection established
  201. // * we already have this configured as a manual peer
  202. // * address is already pending a connection
  203. hosts.check_address_with_lock(self.p2p(), addrs).await
  204. }
  205. // We first try to make connections to the addresses on our anchor list. We then find some
  206. // whitelist connections according to the whitelist percent default. Finally, any remaining
  207. // connections we make from the greylist.
  208. async fn run(self: Arc<Self>) {
  209. let hosts = self.p2p().hosts();
  210. let slot_count = self.p2p().settings().outbound_connections;
  211. loop {
  212. // Activate the slot
  213. debug!(
  214. target: "net::outbound_session::try_connect()",
  215. "[P2P] Finding a host to connect to for outbound slot #{}",
  216. self.slot,
  217. );
  218. // Retrieve outbound transports
  219. let transports = &self.p2p().settings().allowed_transports;
  220. // Do peer discovery if we don't have a hostlist (first time connecting
  221. // to the network).
  222. if hosts.is_empty_hostlist().await {
  223. dnetev!(self, OutboundSlotSleeping, {
  224. slot: self.slot,
  225. });
  226. self.wakeup_self.reset();
  227. // Peer discovery
  228. self.session().wakeup_peer_discovery();
  229. // Wait to be woken up by peer discovery
  230. self.wakeup_self.wait().await;
  231. continue
  232. }
  233. let addr = if let Some(addr) = self.fetch_address(slot_count, transports).await {
  234. debug!(target: "net::outbound_session::run()", "Fetched address: {:?}", addr);
  235. addr
  236. } else {
  237. debug!(target: "net::outbound_session::run()", "No address found! Activating peer discovery...");
  238. dnetev!(self, OutboundSlotSleeping, {
  239. slot: self.slot,
  240. });
  241. self.wakeup_self.reset();
  242. // Peer discovery
  243. self.session().wakeup_peer_discovery();
  244. // Wait to be woken up by peer discovery
  245. self.wakeup_self.wait().await;
  246. continue
  247. };
  248. let host = addr.0;
  249. let slot = self.slot;
  250. info!(
  251. target: "net::outbound_session::try_connect()",
  252. "[P2P] Connecting outbound slot #{} [{}]",
  253. slot, host,
  254. );
  255. dnetev!(self, OutboundSlotConnecting, {
  256. slot,
  257. addr: host.clone(),
  258. });
  259. let (addr, channel) = match self.try_connect(host.clone()).await {
  260. Ok(connect_info) => connect_info,
  261. Err(err) => {
  262. debug!(
  263. target: "net::outbound_session::try_connect()",
  264. "[P2P] Outbound slot #{} connection failed: {}, node {}",
  265. slot, err, self.p2p().settings().node_id
  266. );
  267. dnetev!(self, OutboundSlotDisconnected, {
  268. slot,
  269. err: err.to_string()
  270. });
  271. // Downgrade this host to greylist if it's on the whitelist or anchorlist.
  272. self.session().downgrade_host(&host).await;
  273. self.channel_id.store(0, Ordering::Relaxed);
  274. continue
  275. }
  276. };
  277. info!(
  278. target: "net::outbound_session::try_connect()",
  279. "[P2P] Outbound slot #{} connected [{}]",
  280. slot, addr
  281. );
  282. dnetev!(self, OutboundSlotConnected, {
  283. slot: self.slot,
  284. addr: addr.clone(),
  285. channel_id: channel.info.id
  286. });
  287. // At this point we've managed to connect.
  288. let stop_sub = channel.subscribe_stop().await.expect("Channel should not be stopped");
  289. // Setup new channel
  290. if let Err(err) = self.setup_channel(host.clone(), channel.clone()).await {
  291. info!(
  292. target: "net::outbound_session",
  293. "[P2P] Outbound slot #{} disconnected: {}",
  294. slot, err
  295. );
  296. dnetev!(self, OutboundSlotDisconnected, {
  297. slot: self.slot,
  298. err: err.to_string()
  299. });
  300. self.channel_id.store(0, Ordering::Relaxed);
  301. continue
  302. }
  303. self.channel_id.store(channel.info.id, Ordering::Relaxed);
  304. // Add this connection to the anchorlist, remove it from the [otherlist]
  305. self.session().upgrade_host(&addr).await;
  306. // Wait for channel to close
  307. stop_sub.receive().await;
  308. self.channel_id.store(0, Ordering::Relaxed);
  309. // Downgrade this host to greylist if it's on the whitelist or anchorlist.
  310. self.session().downgrade_host(&addr).await;
  311. }
  312. }
  313. /// Start making an outbound connection, using provided [`Connector`].
  314. /// Tries to find a valid address to connect to, otherwise does peer
  315. /// discovery. The peer discovery loops until some peer we can connect
  316. /// to is found. Once connected, registers the channel, removes it from
  317. /// the list of pending channels, and starts sending messages across the
  318. /// channel. In case of any failures, a network error is returned and the
  319. /// main connect loop (parent of this function) will iterate again.
  320. async fn try_connect(&self, addr: Url) -> Result<(Url, ChannelPtr)> {
  321. let parent = Arc::downgrade(&self.session());
  322. let connector = Connector::new(self.p2p().settings(), parent);
  323. match connector.connect(&addr).await {
  324. Ok((addr_final, channel)) => Ok((addr_final, channel)),
  325. Err(e) => {
  326. debug!(
  327. target: "net::outbound_session::try_connect()",
  328. "[P2P] Unable to connect outbound slot #{} [{}]: {}",
  329. self.slot, addr, e
  330. );
  331. // Remove connection from pending
  332. self.p2p().remove_pending(&addr).await;
  333. // Notify that channel processing failed
  334. self.session().channel_subscriber.notify(Err(Error::ConnectFailed)).await;
  335. Err(Error::ConnectFailed)
  336. }
  337. }
  338. }
  339. async fn setup_channel(&self, addr: Url, channel: ChannelPtr) -> Result<()> {
  340. // Register the new channel
  341. debug!(target: "net::outbound_session::setup_channel", "register_channel {}", channel.clone().address());
  342. self.session().register_channel(channel.clone(), self.p2p().executor()).await?;
  343. // Channel is now connected but not yet setup
  344. // Remove pending lock since register_channel will add the channel to p2p
  345. debug!(target: "net::outbound_session::setup_channel", "removing channel...");
  346. self.p2p().remove_pending(&addr).await;
  347. debug!(target: "net::outbound_session::setup_channel", "channel removed!");
  348. // Notify that channel processing has been finished
  349. self.session().channel_subscriber.notify(Ok(channel)).await;
  350. Ok(())
  351. }
  352. fn notify(&self) {
  353. self.wakeup_self.notify()
  354. }
  355. fn session(&self) -> OutboundSessionPtr {
  356. self.session.upgrade().unwrap()
  357. }
  358. fn p2p(&self) -> P2pPtr {
  359. self.session().p2p()
  360. }
  361. }
  362. struct PeerDiscovery {
  363. process: StoppableTaskPtr,
  364. wakeup_self: CondVar,
  365. session: LazyWeak<OutboundSession>,
  366. }
  367. impl PeerDiscovery {
  368. fn new() -> Arc<Self> {
  369. Arc::new(Self {
  370. process: StoppableTask::new(),
  371. wakeup_self: CondVar::new(),
  372. session: LazyWeak::new(),
  373. })
  374. }
  375. async fn start(self: Arc<Self>) {
  376. let ex = self.p2p().executor();
  377. self.process.clone().start(
  378. async move {
  379. self.run().await;
  380. unreachable!();
  381. },
  382. // Ignore stop handler
  383. |_| async {},
  384. Error::NetworkServiceStopped,
  385. ex,
  386. );
  387. }
  388. async fn stop(self: Arc<Self>) {
  389. self.process.stop().await
  390. }
  391. /// Activate peer discovery if not active already. This will loop through all
  392. /// connected P2P channels and send out a `GetAddrs` message to request more
  393. /// peers. Other parts of the P2P stack will then handle the incoming addresses
  394. /// and place them in the hosts list.
  395. /// This function will also sleep `Settings::outbound_connect_timeout` seconds
  396. /// after broadcasting in order to let the P2P stack receive and work through
  397. /// the addresses it is expecting.
  398. async fn run(self: Arc<Self>) {
  399. let mut current_attempt = 0;
  400. loop {
  401. dnetev!(self, OutboundPeerDiscovery, {
  402. attempt: current_attempt,
  403. state: "wait",
  404. });
  405. // wait to be woken up by notify()
  406. let sleep_was_instant = self.wait().await;
  407. let p2p = self.p2p();
  408. if sleep_was_instant {
  409. // Try again
  410. current_attempt += 1;
  411. } else {
  412. // reset back to start
  413. current_attempt = 1;
  414. }
  415. if current_attempt >= 4 {
  416. debug!("current attempt: {}", current_attempt);
  417. info!(
  418. target: "net::outbound_session::peer_discovery()",
  419. "[P2P] Sleeping and trying again..."
  420. );
  421. dnetev!(self, OutboundPeerDiscovery, {
  422. attempt: current_attempt,
  423. state: "sleep",
  424. });
  425. sleep(p2p.settings().outbound_peer_discovery_cooloff_time).await;
  426. current_attempt = 1;
  427. }
  428. // First 2 times try sending GetAddr to the network.
  429. // 3rd time do a seed sync.
  430. if p2p.is_connected().await && current_attempt <= 2 {
  431. // Broadcast the GetAddrs message to all active channels.
  432. // If we have no active channels, we will perform a SeedSyncSession instead.
  433. info!(
  434. target: "net::outbound_session::peer_discovery()",
  435. "[P2P] Requesting addrs from active channels. Attempt: {}",
  436. current_attempt
  437. );
  438. dnetev!(self, OutboundPeerDiscovery, {
  439. attempt: current_attempt,
  440. state: "getaddr",
  441. });
  442. let get_addrs = GetAddrsMessage {
  443. max: p2p.settings().outbound_connections as u32,
  444. transports: p2p.settings().allowed_transports.clone(),
  445. };
  446. p2p.broadcast(&get_addrs).await;
  447. // Wait for a hosts store update event
  448. let store_sub = self.p2p().hosts().subscribe_store().await.unwrap();
  449. let result = timeout(
  450. Duration::from_secs(p2p.settings().outbound_peer_discovery_attempt_time),
  451. store_sub.receive(),
  452. )
  453. .await;
  454. match result {
  455. Ok(addrs_len) => {
  456. info!(
  457. target: "net::outbound_session::peer_discovery()",
  458. "[P2P] Discovered {} addrs", addrs_len
  459. );
  460. }
  461. Err(_) => {
  462. warn!(
  463. target: "net::outbound_session::peer_discovery()",
  464. "[P2P] Peer discovery waiting for addrs timed out."
  465. );
  466. // TODO: Just do seed next time
  467. }
  468. }
  469. // TODO: check every subscribe() call has a corresponding unsubscribe()
  470. store_sub.unsubscribe().await;
  471. } else {
  472. info!(
  473. target: "net::outbound_session::peer_discovery()",
  474. "[P2P] Seeding hosts. Attempt: {}",
  475. current_attempt
  476. );
  477. dnetev!(self, OutboundPeerDiscovery, {
  478. attempt: current_attempt,
  479. state: "seed",
  480. });
  481. match p2p.clone().seed().await {
  482. Ok(()) => {
  483. info!(
  484. target: "net::outbound_session::peer_discovery()",
  485. "[P2P] Seeding hosts successful."
  486. );
  487. }
  488. Err(err) => {
  489. error!(
  490. target: "net::outbound_session::peer_discovery()",
  491. "[P2P] Network reseed failed: {}", err,
  492. );
  493. }
  494. }
  495. }
  496. self.wakeup_self.reset();
  497. self.session().wakeup_slots().await;
  498. // Give some time for new connections to be established
  499. sleep(p2p.settings().outbound_peer_discovery_attempt_time).await;
  500. }
  501. }
  502. async fn wait(&self) -> bool {
  503. let wakeup_start = Instant::now();
  504. self.wakeup_self.wait().await;
  505. let wakeup_end = Instant::now();
  506. let epsilon = Duration::from_millis(200);
  507. wakeup_end - wakeup_start <= epsilon
  508. }
  509. fn notify(&self) {
  510. self.wakeup_self.notify()
  511. }
  512. fn session(&self) -> OutboundSessionPtr {
  513. self.session.upgrade()
  514. }
  515. fn p2p(&self) -> P2pPtr {
  516. self.session().p2p()
  517. }
  518. }