mod.rs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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. use std::{
  19. sync::{Arc, Weak},
  20. time::UNIX_EPOCH,
  21. };
  22. use async_trait::async_trait;
  23. use log::debug;
  24. use smol::Executor;
  25. use super::{channel::ChannelPtr, hosts::HostColor, p2p::P2pPtr, protocol::ProtocolVersion};
  26. use crate::Result;
  27. pub mod inbound_session;
  28. pub use inbound_session::{InboundSession, InboundSessionPtr};
  29. pub mod manual_session;
  30. pub use manual_session::{ManualSession, ManualSessionPtr};
  31. pub mod outbound_session;
  32. pub use outbound_session::{OutboundSession, OutboundSessionPtr};
  33. pub mod seedsync_session;
  34. pub use seedsync_session::{SeedSyncSession, SeedSyncSessionPtr};
  35. pub mod refine_session;
  36. pub use refine_session::{RefineSession, RefineSessionPtr};
  37. /// Bitwise selectors for the `protocol_registry`
  38. pub type SessionBitFlag = u32;
  39. pub const SESSION_INBOUND: SessionBitFlag = 0b00001;
  40. pub const SESSION_OUTBOUND: SessionBitFlag = 0b00010;
  41. pub const SESSION_MANUAL: SessionBitFlag = 0b00100;
  42. pub const SESSION_SEED: SessionBitFlag = 0b01000;
  43. pub const SESSION_REFINE: SessionBitFlag = 0b10000;
  44. pub const SESSION_DEFAULT: SessionBitFlag = 0b00111;
  45. pub const SESSION_ALL: SessionBitFlag = 0b11111;
  46. pub type SessionWeakPtr = Weak<dyn Session + Send + Sync + 'static>;
  47. /// Removes channel from the list of connected channels when a stop signal
  48. /// is received.
  49. pub async fn remove_sub_on_stop(p2p: P2pPtr, channel: ChannelPtr, type_id: SessionBitFlag) {
  50. debug!(target: "net::session::remove_sub_on_stop()", "[START]");
  51. let addr = channel.address();
  52. // Subscribe to stop events
  53. let stop_sub = channel.clone().subscribe_stop().await;
  54. if let Ok(stop_sub) = stop_sub {
  55. // Wait for a stop event
  56. stop_sub.receive().await;
  57. }
  58. debug!(
  59. target: "net::session::remove_sub_on_stop()",
  60. "Received stop event. Removing channel {}", addr,
  61. );
  62. // Downgrade to greylist this is a outbound or manual session.
  63. if type_id & (SESSION_MANUAL | SESSION_OUTBOUND) != 0 {
  64. debug!(
  65. target: "net::session::remove_sub_on_stop()",
  66. "Downgrading {}", addr,
  67. );
  68. let last_seen = p2p.hosts().fetch_last_seen(addr).await.unwrap();
  69. p2p.hosts().move_host(addr, last_seen, HostColor::Grey).await.unwrap();
  70. }
  71. // Remove channel from the HostRegistry. Free up this addr for any future operation.
  72. p2p.hosts().unregister(channel.address()).await;
  73. debug!(target: "net::session::remove_sub_on_stop()", "[END]");
  74. }
  75. /// Session trait. Defines methods that are used across sessions.
  76. /// Implements registering the channel and initializing the channel by
  77. /// performing a network handshake.
  78. #[async_trait]
  79. pub trait Session: Sync {
  80. /// Registers a new channel with the session.
  81. /// Performs a network handshake and starts the channel.
  82. /// If we need to pass `Self` as an `Arc` we can do so like this:
  83. /// ```
  84. /// pub trait MyTrait: Send + Sync {
  85. /// async fn foo(&self, self_: Arc<dyn MyTrait>) {}
  86. /// }
  87. /// ```
  88. async fn register_channel(
  89. &self,
  90. channel: ChannelPtr,
  91. executor: Arc<Executor<'_>>,
  92. ) -> Result<()> {
  93. debug!(target: "net::session::register_channel()", "[START]");
  94. // Protocols should all be initialized but not started.
  95. // We do this so that the protocols can begin receiving and buffering
  96. // messages while the handshake protocol is ongoing. They are currently
  97. // in sleep mode.
  98. let p2p = self.p2p();
  99. let protocols =
  100. p2p.protocol_registry().attach(self.type_id(), channel.clone(), p2p.clone()).await;
  101. // Perform the handshake protocol
  102. let protocol_version = ProtocolVersion::new(channel.clone(), p2p.settings().clone()).await;
  103. debug!(target: "net::session::register_channel()",
  104. "Performing handshake protocols {}", channel.clone().address());
  105. let handshake_task =
  106. self.perform_handshake_protocols(protocol_version, channel.clone(), executor.clone());
  107. // Switch on the channel
  108. channel.clone().start(executor.clone());
  109. // Wait for handshake to finish.
  110. // If the handshake returns an error, remove this host from all hostlists.
  111. match handshake_task.await {
  112. Ok(()) => {
  113. debug!(target: "net::session::register_channel()",
  114. "Handshake successful {}", channel.clone().address());
  115. }
  116. Err(e) => {
  117. debug!(target: "net::session::register_channel()",
  118. "Handshake error {} {}", e, channel.clone().address());
  119. }
  120. }
  121. // Now the channel is ready
  122. debug!(target: "net::session::register_channel()", "Session handshake complete");
  123. debug!(target: "net::session::register_channel()", "Activating remaining protocols");
  124. // Now start all the protocols. They are responsible for managing their own
  125. // lifetimes and correctly selfdestructing when the channel ends.
  126. for protocol in protocols {
  127. protocol.start(executor.clone()).await?;
  128. }
  129. debug!(target: "net::session::register_channel()", "[END]");
  130. Ok(())
  131. }
  132. /// Performs network handshake to initialize channel. Adds the channel to
  133. /// the list of connected channels, and prepares to remove the channel when
  134. /// a stop signal is received.
  135. async fn perform_handshake_protocols(
  136. &self,
  137. protocol_version: Arc<ProtocolVersion>,
  138. channel: ChannelPtr,
  139. executor: Arc<Executor<'_>>,
  140. ) -> Result<()> {
  141. // Perform handshake
  142. protocol_version.run(executor.clone()).await?;
  143. // Upgrade to goldlist if this is a outbound or manual session.
  144. if self.type_id() & (SESSION_MANUAL | SESSION_OUTBOUND) != 0 {
  145. debug!(
  146. target: "net::session::perform_handshake_protocols()",
  147. "Upgrading {}", channel.address(),
  148. );
  149. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  150. self.p2p()
  151. .hosts()
  152. .move_host(channel.address(), last_seen, HostColor::Gold)
  153. .await
  154. .unwrap();
  155. }
  156. // Attempt to add channel to registry
  157. self.p2p().hosts().register_channel(channel.clone()).await;
  158. // Subscribe to stop, so we can remove from registry
  159. executor.spawn(remove_sub_on_stop(self.p2p(), channel, self.type_id())).detach();
  160. // Channel is ready for use
  161. Ok(())
  162. }
  163. /// Returns a pointer to the p2p network interface
  164. fn p2p(&self) -> P2pPtr;
  165. /// Return the session bit flag for the session type
  166. fn type_id(&self) -> SessionBitFlag;
  167. }