mod.rs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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::sync::{Arc, Weak};
  19. use async_trait::async_trait;
  20. use log::debug;
  21. use smol::Executor;
  22. use super::{channel::ChannelPtr, p2p::P2pPtr, protocol::ProtocolVersion};
  23. use crate::Result;
  24. pub mod inbound_session;
  25. pub use inbound_session::{InboundSession, InboundSessionPtr};
  26. pub mod manual_session;
  27. pub use manual_session::{ManualSession, ManualSessionPtr};
  28. pub mod outbound_session;
  29. pub use outbound_session::{OutboundSession, OutboundSessionPtr};
  30. pub mod seedsync_session;
  31. pub use seedsync_session::{SeedSyncSession, SeedSyncSessionPtr};
  32. /// Bitwise selectors for the `protocol_registry`
  33. pub type SessionBitFlag = u32;
  34. pub const SESSION_INBOUND: SessionBitFlag = 0b0001;
  35. pub const SESSION_OUTBOUND: SessionBitFlag = 0b0010;
  36. pub const SESSION_MANUAL: SessionBitFlag = 0b0100;
  37. pub const SESSION_SEED: SessionBitFlag = 0b1000;
  38. pub const SESSION_ALL: SessionBitFlag = 0b1111;
  39. pub type SessionWeakPtr = Weak<dyn Session + Send + Sync + 'static>;
  40. /// Removes channel from the list of connected channels when a stop signal
  41. /// is received.
  42. pub async fn remove_sub_on_stop(p2p: P2pPtr, channel: ChannelPtr) {
  43. debug!(target: "net::session::remove_sub_on_stop()", "[START]");
  44. // Subscribe to stop events
  45. let stop_sub = channel.clone().subscribe_stop().await;
  46. if let Ok(stop_sub) = stop_sub {
  47. // Wait for a stop event
  48. stop_sub.receive().await;
  49. }
  50. debug!(
  51. target: "net::session::remove_sub_on_stop()",
  52. "Received stop event. Removing channel {}", channel.address(),
  53. );
  54. // Remove channel from p2p
  55. p2p.remove(channel).await;
  56. debug!(target: "net::session::remove_sub_on_stop()", "[END]");
  57. }
  58. /// Session trait. Defines methods that are used across sessions.
  59. /// Implements registering the channel and initializing the channel by
  60. /// performing a network handshake.
  61. #[async_trait]
  62. pub trait Session: Sync {
  63. /// Registers a new channel with the session.
  64. /// Performs a network handshake and starts the channel.
  65. /// If we need to pass `Self` as an `Arc` we can do so like this:
  66. /// ```
  67. /// pub trait MyTrait: Send + Sync {
  68. /// async fn foo(&self, self_: Arc<dyn MyTrait>) {}
  69. /// }
  70. /// ```
  71. async fn register_channel(
  72. &self,
  73. channel: ChannelPtr,
  74. executor: Arc<Executor<'_>>,
  75. ) -> Result<()> {
  76. debug!(target: "net::session::register_channel()", "[START]");
  77. // Protocols should all be initialized but not started.
  78. // We do this so that the protocols can begin receiving and buffering
  79. // messages while the handshake protocol is ongoing. They are currently
  80. // in sleep mode.
  81. let p2p = self.p2p();
  82. let protocols =
  83. p2p.protocol_registry().attach(self.type_id(), channel.clone(), p2p.clone()).await;
  84. // Perform the handshake protocol
  85. let protocol_version = ProtocolVersion::new(channel.clone(), p2p.settings().clone()).await;
  86. debug!(target: "net::session::register_channel()",
  87. "Performing handshake protocols {}", channel.clone().address());
  88. let handshake_task =
  89. self.perform_handshake_protocols(protocol_version, channel.clone(), executor.clone());
  90. // Switch on the channel
  91. channel.start(executor.clone());
  92. // Wait for handshake to finish.
  93. handshake_task.await?;
  94. // Now the channel is ready
  95. debug!(target: "net::session::register_channel()", "Session handshake complete");
  96. debug!(target: "net::session::register_channel()", "Activating remaining protocols");
  97. // Now start all the protocols. They are responsible for managing their own
  98. // lifetimes and correctly selfdestructing when the channel ends.
  99. for protocol in protocols {
  100. protocol.start(executor.clone()).await?;
  101. }
  102. debug!(target: "net::session::register_channel()", "[END]");
  103. Ok(())
  104. }
  105. /// Performs network handshake to initialize channel. Adds the channel to
  106. /// the list of connected channels, and prepares to remove the channel when
  107. /// a stop signal is received.
  108. async fn perform_handshake_protocols(
  109. &self,
  110. protocol_version: Arc<ProtocolVersion>,
  111. channel: ChannelPtr,
  112. executor: Arc<Executor<'_>>,
  113. ) -> Result<()> {
  114. // Perform handshake
  115. protocol_version.run(executor.clone()).await?;
  116. // Add channel to p2p
  117. self.p2p().store(channel.clone()).await;
  118. // Subscribe to stop, so we can remove from p2p
  119. executor.spawn(remove_sub_on_stop(self.p2p(), channel)).detach();
  120. // Channel is ready for use
  121. Ok(())
  122. }
  123. /// Returns a pointer to the p2p network interface
  124. fn p2p(&self) -> P2pPtr;
  125. /// Return the session bit flag for the session type
  126. fn type_id(&self) -> SessionBitFlag;
  127. }