channel.rs 11 KB

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