seedsync_session.rs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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 discoonnects, 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 async_std::sync::{Arc, Weak};
  39. use async_trait::async_trait;
  40. use futures::future::join_all;
  41. use log::{debug, info, warn};
  42. use smol::Executor;
  43. use url::Url;
  44. use super::{
  45. super::{
  46. connector::Connector,
  47. p2p::{DnetInfo, P2p, P2pPtr},
  48. },
  49. Session, SessionBitFlag, SESSION_SEED,
  50. };
  51. use crate::Result;
  52. pub type SeedSyncSessionPtr = Arc<SeedSyncSession>;
  53. /// Defines seed connections session
  54. pub struct SeedSyncSession {
  55. p2p: Weak<P2p>,
  56. }
  57. impl SeedSyncSession {
  58. /// Create a new seed sync session instance
  59. pub fn new(p2p: Weak<P2p>) -> SeedSyncSessionPtr {
  60. Arc::new(Self { p2p })
  61. }
  62. /// Start the seed sync session. Creates a new task for every seed
  63. /// connection and starts the seed on each task.
  64. pub async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  65. debug!(target: "net::session::seedsync_session", "SeedSyncSession::start() [START]");
  66. let settings = self.p2p().settings();
  67. if settings.seeds.is_empty() {
  68. warn!(
  69. target: "net::session::seedsync_session",
  70. "[P2P] Skipping seed sync process since no seeds are configured.",
  71. );
  72. return Ok(())
  73. }
  74. // Gather tasks so we can execute concurrently
  75. let mut tasks = Vec::with_capacity(settings.seeds.len());
  76. for (i, seed) in settings.seeds.iter().enumerate() {
  77. let ex_ = executor.clone();
  78. let self_ = self.clone();
  79. tasks.push(async move {
  80. if let Err(e) = self_.clone().start_seed(i, seed.clone(), ex_.clone()).await {
  81. warn!(
  82. target: "net::session::seedsync_session",
  83. "[P2P] Seed #{} connection failed: {}", i, e,
  84. );
  85. }
  86. });
  87. }
  88. // Poll concurrently
  89. join_all(tasks).await;
  90. // Seed process complete
  91. if self.p2p().hosts().is_empty().await {
  92. warn!(target: "net::session::seedsync_session", "[P2P] Hosts pool empty after seeding");
  93. }
  94. debug!(target: "net::session::seedsync_session", "SeedSyncSession::start() [END]");
  95. Ok(())
  96. }
  97. /// Connects to a seed socket address
  98. async fn start_seed(
  99. self: Arc<Self>,
  100. seed_index: usize,
  101. seed: Url,
  102. ex: Arc<Executor<'_>>,
  103. ) -> Result<()> {
  104. debug!(
  105. target: "net::session::seedsync_session", "SeedSyncSession::start_seed(i={}) [START]",
  106. seed_index
  107. );
  108. let settings = self.p2p.upgrade().unwrap().settings();
  109. let parent = Arc::downgrade(&self);
  110. let connector = Connector::new(settings.clone(), Arc::new(parent));
  111. match connector.connect(&seed).await {
  112. Ok((url, ch)) => {
  113. info!(
  114. target: "net::session::seedsync_session",
  115. "[P2P] Connected seed #{} [{}]", seed_index, url,
  116. );
  117. if let Err(e) = self.clone().register_channel(ch.clone(), ex.clone()).await {
  118. warn!(
  119. target: "net::session::seedsync_session",
  120. "[P2P] Failure during sync seed session #{} [{}]: {}",
  121. seed_index, url, e,
  122. );
  123. }
  124. info!(
  125. target: "net::session::seedsync_session",
  126. "[P2P] Disconnecting from seed #{} [{}]",
  127. seed_index, url,
  128. );
  129. ch.stop().await;
  130. }
  131. Err(e) => {
  132. warn!(
  133. target: "net::session:seedsync_session",
  134. "[P2P] Failure contacting seed #{} [{}]: {}",
  135. seed_index, seed, e
  136. );
  137. return Err(e)
  138. }
  139. }
  140. debug!(
  141. target: "net::session::seedsync_session",
  142. "SeedSyncSession::start_seed(i={}) [END]",
  143. seed_index
  144. );
  145. Ok(())
  146. }
  147. }
  148. #[async_trait]
  149. impl Session for SeedSyncSession {
  150. fn p2p(&self) -> P2pPtr {
  151. self.p2p.upgrade().unwrap()
  152. }
  153. fn type_id(&self) -> SessionBitFlag {
  154. SESSION_SEED
  155. }
  156. async fn dnet_info(&self) -> DnetInfo {
  157. todo!()
  158. }
  159. }