seedsync_session.rs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. //! Seed sync session creates a connection to the seed nodes specified in settings.
  19. //! A new seed sync session is created every time we call [`P2p::start()`]. The
  20. //! seed sync session loops through all the configured seeds and tries to connect
  21. //! to them using a [`Connector`]. Seed sync either connects successfully, fails
  22. //! with an error, or times out.
  23. //!
  24. //! If a seed node connects successfully, it runs a version exchange protocol,
  25. //! stores the channel in the p2p list of channels, and disconnects, removing
  26. //! the channel from the channel list.
  27. //!
  28. //! The channel is registered using the [`Session::register_channel()`] trait
  29. //! method. This invokes the Protocol Registry method `attach()`. Usually this
  30. //! returns a list of protocols that we loop through and start. In this case,
  31. //! `attach()` uses the bitflag selector to identify seed sessions and exclude
  32. //! them.
  33. //!
  34. //! The version exchange occurs inside `register_channel()`. We create a handshake
  35. //! task that runs the version exchange with the `perform_handshake_protocols()`
  36. //! function. This runs the version exchange protocol, stores the channel in the
  37. //! p2p list of channels, and subscribes to a stop signal.
  38. use std::sync::{
  39. atomic::{AtomicUsize, Ordering},
  40. Arc, Weak,
  41. };
  42. use async_trait::async_trait;
  43. use futures::future::join_all;
  44. use log::{debug, info, warn};
  45. use smol::Executor;
  46. use url::Url;
  47. use super::{
  48. super::{
  49. connector::Connector,
  50. p2p::{P2p, P2pPtr},
  51. },
  52. Session, SessionBitFlag, SESSION_SEED,
  53. };
  54. use crate::{Error, Result};
  55. pub type SeedSyncSessionPtr = Arc<SeedSyncSession>;
  56. /// Defines seed connections session
  57. pub struct SeedSyncSession {
  58. p2p: Weak<P2p>,
  59. }
  60. impl SeedSyncSession {
  61. /// Create a new seed sync session instance
  62. pub fn new(p2p: Weak<P2p>) -> SeedSyncSessionPtr {
  63. Arc::new(Self { p2p })
  64. }
  65. /// Start the seed sync session. Creates a new task for every seed
  66. /// connection and starts the seed on each task.
  67. pub async fn start(self: Arc<Self>) -> Result<()> {
  68. debug!(target: "net::session::seedsync_session", "SeedSyncSession::start() [START]");
  69. let settings = self.p2p().settings();
  70. if settings.seeds.is_empty() {
  71. warn!(
  72. target: "net::session::seedsync_session",
  73. "[P2P] Skipping seed sync process since no seeds are configured.",
  74. );
  75. return Ok(())
  76. }
  77. // Gather tasks so we can execute concurrently
  78. let executor = self.p2p().executor();
  79. let mut tasks = Vec::with_capacity(settings.seeds.len());
  80. let failed = Arc::new(AtomicUsize::new(0));
  81. for (i, seed) in settings.seeds.iter().enumerate() {
  82. let ex_ = executor.clone();
  83. let self_ = self.clone();
  84. let failed_ = failed.clone();
  85. tasks.push(async move {
  86. if let Err(e) = self_.clone().start_seed(i, seed.clone(), ex_.clone()).await {
  87. warn!(
  88. target: "net::session::seedsync_session",
  89. "[P2P] Seed #{} connection failed: {}", i, e,
  90. );
  91. failed_.fetch_add(1, Ordering::SeqCst);
  92. }
  93. });
  94. }
  95. // Poll concurrently
  96. join_all(tasks).await;
  97. if failed.load(Ordering::SeqCst) == settings.seeds.len() {
  98. return Err(Error::SeedFailed)
  99. }
  100. // Seed process complete
  101. if self.p2p().hosts().is_empty().await {
  102. warn!(target: "net::session::seedsync_session", "[P2P] Hosts pool empty after seeding");
  103. }
  104. debug!(target: "net::session::seedsync_session", "SeedSyncSession::start() [END]");
  105. Ok(())
  106. }
  107. /// Connects to a seed socket address
  108. async fn start_seed(
  109. self: Arc<Self>,
  110. seed_index: usize,
  111. seed: Url,
  112. ex: Arc<Executor<'_>>,
  113. ) -> Result<()> {
  114. debug!(
  115. target: "net::session::seedsync_session", "SeedSyncSession::start_seed(i={}) [START]",
  116. seed_index
  117. );
  118. let settings = self.p2p.upgrade().unwrap().settings();
  119. let parent = Arc::downgrade(&self);
  120. let connector = Connector::new(settings.clone(), parent);
  121. match connector.connect(&seed).await {
  122. Ok((url, ch)) => {
  123. info!(
  124. target: "net::session::seedsync_session",
  125. "[P2P] Connected seed #{} [{}]", seed_index, url,
  126. );
  127. if let Err(e) = self.clone().register_channel(ch.clone(), ex.clone()).await {
  128. warn!(
  129. target: "net::session::seedsync_session",
  130. "[P2P] Failure during sync seed session #{} [{}]: {}",
  131. seed_index, url, e,
  132. );
  133. }
  134. info!(
  135. target: "net::session::seedsync_session",
  136. "[P2P] Disconnecting from seed #{} [{}]",
  137. seed_index, url,
  138. );
  139. ch.stop().await;
  140. }
  141. Err(e) => {
  142. warn!(
  143. target: "net::session:seedsync_session",
  144. "[P2P] Failure contacting seed #{} [{}]: {}",
  145. seed_index, seed, e
  146. );
  147. return Err(e)
  148. }
  149. }
  150. debug!(
  151. target: "net::session::seedsync_session",
  152. "SeedSyncSession::start_seed(i={}) [END]",
  153. seed_index
  154. );
  155. Ok(())
  156. }
  157. }
  158. #[async_trait]
  159. impl Session for SeedSyncSession {
  160. fn p2p(&self) -> P2pPtr {
  161. self.p2p.upgrade().unwrap()
  162. }
  163. fn type_id(&self) -> SessionBitFlag {
  164. SESSION_SEED
  165. }
  166. }