channel.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. use std::sync::Arc;
  19. use darkfi_serial::{serialize, SerialDecodable, SerialEncodable};
  20. use log::{debug, error, info};
  21. use rand::{rngs::OsRng, Rng};
  22. use smol::{
  23. io::{self, ReadHalf, WriteHalf},
  24. lock::Mutex,
  25. Executor,
  26. };
  27. use url::Url;
  28. use super::{
  29. dnet::{self, dnetev, DnetEvent},
  30. message,
  31. message::Packet,
  32. message_subscriber::{MessageSubscription, MessageSubsystem},
  33. p2p::P2pPtr,
  34. session::{Session, SessionBitFlag, SessionWeakPtr},
  35. transport::PtStream,
  36. };
  37. use crate::{
  38. system::{StoppableTask, StoppableTaskPtr, Subscriber, SubscriberPtr, Subscription},
  39. util::time::NanoTimestamp,
  40. Error, Result,
  41. };
  42. /// Atomic pointer to async channel
  43. pub type ChannelPtr = Arc<Channel>;
  44. /// Channel debug info
  45. #[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
  46. pub struct ChannelInfo {
  47. pub addr: Url,
  48. pub id: u32,
  49. }
  50. impl ChannelInfo {
  51. fn new(addr: Url) -> Self {
  52. Self { addr, id: OsRng.gen() }
  53. }
  54. }
  55. /// Async channel for communication between nodes.
  56. pub struct Channel {
  57. /// The reading half of the transport stream
  58. reader: Mutex<ReadHalf<Box<dyn PtStream>>>,
  59. /// The writing half of the transport stream
  60. writer: Mutex<WriteHalf<Box<dyn PtStream>>>,
  61. /// The message subsystem instance for this channel
  62. message_subsystem: MessageSubsystem,
  63. /// Subscriber listening for stop signal for closing this channel
  64. stop_subscriber: SubscriberPtr<Error>,
  65. /// Task that is listening for the stop signal
  66. receive_task: StoppableTaskPtr,
  67. /// A boolean marking if this channel is stopped
  68. stopped: Mutex<bool>,
  69. /// Weak pointer to respective session
  70. session: SessionWeakPtr,
  71. /// Channel debug info
  72. pub info: ChannelInfo,
  73. }
  74. impl std::fmt::Debug for Channel {
  75. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  76. write!(f, "{}", self.address())
  77. }
  78. }
  79. impl Channel {
  80. /// Sets up a new channel. Creates a reader and writer [`PtStream`] and
  81. /// summons the message subscriber subsystem. Performs a network handshake
  82. /// on the subsystem dispatchers.
  83. pub async fn new(stream: Box<dyn PtStream>, addr: Url, session: SessionWeakPtr) -> Arc<Self> {
  84. let (reader, writer) = io::split(stream);
  85. let reader = Mutex::new(reader);
  86. let writer = Mutex::new(writer);
  87. let message_subsystem = MessageSubsystem::new();
  88. Self::setup_dispatchers(&message_subsystem).await;
  89. let info = ChannelInfo::new(addr.clone());
  90. Arc::new(Self {
  91. reader,
  92. writer,
  93. message_subsystem,
  94. stop_subscriber: Subscriber::new(),
  95. receive_task: StoppableTask::new(),
  96. stopped: Mutex::new(false),
  97. session,
  98. info,
  99. })
  100. }
  101. /// Perform network handshake for message subsystem dispatchers.
  102. async fn setup_dispatchers(subsystem: &MessageSubsystem) {
  103. subsystem.add_dispatch::<message::VersionMessage>().await;
  104. subsystem.add_dispatch::<message::VerackMessage>().await;
  105. subsystem.add_dispatch::<message::PingMessage>().await;
  106. subsystem.add_dispatch::<message::PongMessage>().await;
  107. subsystem.add_dispatch::<message::GetAddrsMessage>().await;
  108. subsystem.add_dispatch::<message::AddrsMessage>().await;
  109. }
  110. /// Starts the channel. Runs a receive loop to start receiving messages
  111. /// or handles a network failure.
  112. pub fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) {
  113. debug!(target: "net::channel::start()", "START => address={}", self.address());
  114. let self_ = self.clone();
  115. self.receive_task.clone().start(
  116. self.clone().main_receive_loop(),
  117. |result| self_.handle_stop(result),
  118. Error::NetworkServiceStopped,
  119. executor,
  120. );
  121. debug!(target: "net::channel::start()", "END => address={}", self.address());
  122. }
  123. /// Stops the channel. Steps through each component of the channel connection
  124. /// and sends a stop signal. Notifies all subscribers that the channel has
  125. /// been closed.
  126. pub async fn stop(&self) {
  127. debug!(target: "net::channel::stop()", "START => address={}", self.address());
  128. if !*self.stopped.lock().await {
  129. *self.stopped.lock().await = true;
  130. self.stop_subscriber.notify(Error::ChannelStopped).await;
  131. self.receive_task.stop().await;
  132. self.message_subsystem.trigger_error(Error::ChannelStopped).await;
  133. }
  134. debug!(target: "net::channel::stop()", "END => address={}", self.address());
  135. }
  136. /// Creates a subscription to a stopped signal.
  137. /// If the channel is stopped then this will return a ChannelStopped error.
  138. pub async fn subscribe_stop(&self) -> Result<Subscription<Error>> {
  139. debug!(target: "net::channel::subscribe_stop()", "START => address={}", self.address());
  140. if *self.stopped.lock().await {
  141. return Err(Error::ChannelStopped)
  142. }
  143. let sub = self.stop_subscriber.clone().subscribe().await;
  144. debug!(target: "net::channel::subscribe_stop()", "END => address={}", self.address());
  145. Ok(sub)
  146. }
  147. /// Sends a message across a channel. Calls `send_message` that creates
  148. /// a new payload and sends it over the network transport as a packet.
  149. /// Returns an error if something goes wrong.
  150. pub async fn send<M: message::Message>(&self, message: &M) -> Result<()> {
  151. debug!(
  152. target: "net::channel::send()", "[START] command={} => address={}",
  153. M::NAME, self.address(),
  154. );
  155. if *self.stopped.lock().await {
  156. return Err(Error::ChannelStopped)
  157. }
  158. // Catch failure and stop channel, return a net error
  159. if let Err(e) = self.send_message(message).await {
  160. error!(
  161. target: "net::channel::send()", "[P2P] Channel send error for [{}]: {}",
  162. self.address(), e
  163. );
  164. self.stop().await;
  165. return Err(Error::ChannelStopped)
  166. }
  167. debug!(
  168. target: "net::channel::send()", "[END] command={} => address={}",
  169. M::NAME,self.address(),
  170. );
  171. Ok(())
  172. }
  173. /// Implements send message functionality. Creates a new payload and
  174. /// encodes it. Then creates a message packet (the base type of the
  175. /// network) and copies the payload into it. Then we send the packet
  176. /// over the network stream.
  177. async fn send_message<M: message::Message>(&self, message: &M) -> Result<()> {
  178. let packet = Packet { command: M::NAME.to_string(), payload: serialize(message) };
  179. dnetev!(self, SendMessage, {
  180. chan: self.info.clone(),
  181. cmd: packet.command.clone(),
  182. time: NanoTimestamp::current_time(),
  183. });
  184. let stream = &mut *self.writer.lock().await;
  185. let _ = message::send_packet(stream, packet).await?;
  186. Ok(())
  187. }
  188. /// Subscribe to a message on the message subsystem.
  189. pub async fn subscribe_msg<M: message::Message>(&self) -> Result<MessageSubscription<M>> {
  190. debug!(
  191. target: "net::channel::subscribe_msg()", "[START] command={} => address={}",
  192. M::NAME, self.address(),
  193. );
  194. let sub = self.message_subsystem.subscribe::<M>().await;
  195. debug!(
  196. target: "net::channel::subscribe_msg()", "[END] command={} => address={}",
  197. M::NAME, self.address(),
  198. );
  199. sub
  200. }
  201. /// Handle network errors. Panic if error passes silently, otherwise
  202. /// broadcast the error.
  203. async fn handle_stop(self: Arc<Self>, result: Result<()>) {
  204. debug!(target: "net::channel::handle_stop()", "[START] address={}", self.address());
  205. match result {
  206. Ok(()) => panic!("Channel task should never complete without error status"),
  207. // Send this error to all channel subscribers
  208. Err(e) => self.message_subsystem.trigger_error(e).await,
  209. }
  210. debug!(target: "net::channel::handle_stop()", "[END] address={}", self.address());
  211. }
  212. /// Run the receive loop. Start receiving messages or handle network failure.
  213. async fn main_receive_loop(self: Arc<Self>) -> Result<()> {
  214. debug!(target: "net::channel::main_receive_loop()", "[START] address={}", self.address());
  215. // Acquire reader lock
  216. let reader = &mut *self.reader.lock().await;
  217. // Run loop
  218. loop {
  219. let packet = match message::read_packet(reader).await {
  220. Ok(packet) => packet,
  221. Err(err) => {
  222. if Self::is_eof_error(&err) {
  223. info!(
  224. target: "net::channel::main_receive_loop()",
  225. "[P2P] Channel inbound connection {} disconnected",
  226. self.address(),
  227. );
  228. } else {
  229. error!(
  230. target: "net::channel::main_receive_loop()",
  231. "[P2P] Read error on channel {}: {}",
  232. self.address(), err,
  233. );
  234. }
  235. debug!(
  236. target: "net::channel::main_receive_loop()",
  237. "Stopping channel {}", self.address(),
  238. );
  239. self.stop().await;
  240. return Err(Error::ChannelStopped)
  241. }
  242. };
  243. dnetev!(self, RecvMessage, {
  244. chan: self.info.clone(),
  245. cmd: packet.command.clone(),
  246. time: NanoTimestamp::current_time(),
  247. });
  248. // Send result to our subscribers
  249. self.message_subsystem.notify(&packet.command, &packet.payload).await;
  250. }
  251. }
  252. /// Returns the local socket address
  253. pub fn address(&self) -> &Url {
  254. &self.info.addr
  255. }
  256. /// Returns the inner [`MessageSubsystem`] reference
  257. pub fn message_subsystem(&self) -> &MessageSubsystem {
  258. &self.message_subsystem
  259. }
  260. fn session(&self) -> Arc<dyn Session> {
  261. self.session.upgrade().unwrap()
  262. }
  263. pub fn session_type_id(&self) -> SessionBitFlag {
  264. let session = self.session();
  265. session.type_id()
  266. }
  267. fn p2p(&self) -> P2pPtr {
  268. self.session().p2p()
  269. }
  270. fn is_eof_error(err: &Error) -> bool {
  271. match err {
  272. Error::Io(ioerr) => ioerr == &std::io::ErrorKind::UnexpectedEof,
  273. _ => false,
  274. }
  275. }
  276. }