channel.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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.
  125. /// Notifies all subscribers that the channel has been closed in `handle_stop()`.
  126. pub async fn stop(&self) {
  127. debug!(target: "net::channel::stop()", "START {:?}", self);
  128. self.receive_task.stop().await;
  129. debug!(target: "net::channel::stop()", "END {:?}", self);
  130. }
  131. /// Creates a subscription to a stopped signal.
  132. /// If the channel is stopped then this will return a ChannelStopped error.
  133. pub async fn subscribe_stop(&self) -> Result<Subscription<Error>> {
  134. debug!(target: "net::channel::subscribe_stop()", "START {:?}", self);
  135. if self.stopped.load(SeqCst) {
  136. return Err(Error::ChannelStopped)
  137. }
  138. let sub = self.stop_subscriber.clone().subscribe().await;
  139. debug!(target: "net::channel::subscribe_stop()", "END {:?}", self);
  140. Ok(sub)
  141. }
  142. pub fn is_stopped(&self) -> bool {
  143. self.stopped.load(SeqCst)
  144. }
  145. /// Sends a message across a channel. Calls `send_message` that creates
  146. /// a new payload and sends it over the network transport as a packet.
  147. /// Returns an error if something goes wrong.
  148. pub async fn send<M: message::Message>(&self, message: &M) -> Result<()> {
  149. debug!(
  150. target: "net::channel::send()", "[START] command={} {:?}",
  151. M::NAME, self,
  152. );
  153. if self.stopped.load(SeqCst) {
  154. return Err(Error::ChannelStopped)
  155. }
  156. // Catch failure and stop channel, return a net error
  157. if let Err(e) = self.send_message(message).await {
  158. error!(
  159. target: "net::channel::send()", "[P2P] Channel send error for [{:?}]: {}",
  160. self, e
  161. );
  162. self.stop().await;
  163. return Err(Error::ChannelStopped)
  164. }
  165. debug!(
  166. target: "net::channel::send()", "[END] command={} {:?}",
  167. M::NAME, self
  168. );
  169. Ok(())
  170. }
  171. /// Implements send message functionality. Creates a new payload and
  172. /// encodes it. Then creates a message packet (the base type of the
  173. /// network) and copies the payload into it. Then we send the packet
  174. /// over the network stream.
  175. async fn send_message<M: message::Message>(&self, message: &M) -> Result<()> {
  176. let packet = Packet { command: M::NAME.to_string(), payload: serialize(message) };
  177. dnetev!(self, SendMessage, {
  178. chan: self.info.clone(),
  179. cmd: packet.command.clone(),
  180. time: NanoTimestamp::current_time(),
  181. });
  182. let stream = &mut *self.writer.lock().await;
  183. let _ = message::send_packet(stream, packet).await?;
  184. Ok(())
  185. }
  186. /// Subscribe to a message on the message subsystem.
  187. pub async fn subscribe_msg<M: message::Message>(&self) -> Result<MessageSubscription<M>> {
  188. debug!(
  189. target: "net::channel::subscribe_msg()", "[START] command={} {:?}",
  190. M::NAME, self
  191. );
  192. let sub = self.message_subsystem.subscribe::<M>().await;
  193. debug!(
  194. target: "net::channel::subscribe_msg()", "[END] command={} {:?}",
  195. M::NAME, self
  196. );
  197. sub
  198. }
  199. /// Handle network errors. Panic if error passes silently, otherwise
  200. /// broadcast the error.
  201. async fn handle_stop(self: Arc<Self>, result: Result<()>) {
  202. debug!(target: "net::channel::handle_stop()", "[START] {:?}", self);
  203. self.stopped.store(true, SeqCst);
  204. match result {
  205. Ok(()) => panic!("Channel task should never complete without error status"),
  206. // Send this error to all channel subscribers
  207. Err(e) => {
  208. self.stop_subscriber.notify(Error::ChannelStopped).await;
  209. self.message_subsystem.trigger_error(e).await;
  210. }
  211. }
  212. debug!(target: "net::channel::handle_stop()", "[END] {:?}", self);
  213. }
  214. /// Run the receive loop. Start receiving messages or handle network failure.
  215. async fn main_receive_loop(self: Arc<Self>) -> Result<()> {
  216. debug!(target: "net::channel::main_receive_loop()", "[START] {:?}", self);
  217. // Acquire reader lock
  218. let reader = &mut *self.reader.lock().await;
  219. // Run loop
  220. loop {
  221. let packet = match message::read_packet(reader).await {
  222. Ok(packet) => packet,
  223. Err(err) => {
  224. if Self::is_eof_error(&err) {
  225. info!(
  226. target: "net::channel::main_receive_loop()",
  227. "[P2P] Channel inbound connection {} disconnected",
  228. self.address(),
  229. );
  230. } else {
  231. error!(
  232. target: "net::channel::main_receive_loop()",
  233. "[P2P] Read error on channel {}: {}",
  234. self.address(), err,
  235. );
  236. }
  237. debug!(
  238. target: "net::channel::main_receive_loop()",
  239. "Stopping channel {:?}", self
  240. );
  241. return Err(Error::ChannelStopped)
  242. }
  243. };
  244. dnetev!(self, RecvMessage, {
  245. chan: self.info.clone(),
  246. cmd: packet.command.clone(),
  247. time: NanoTimestamp::current_time(),
  248. });
  249. // Send result to our subscribers
  250. match self.message_subsystem.notify(&packet.command, &packet.payload).await {
  251. Ok(()) => {}
  252. // If we're getting messages without dispatchers, it's spam.
  253. Err(Error::MissingDispatcher) => {
  254. debug!(target: "net::channel::main_receive_loop()", "Stopping channel {:?}", self);
  255. // We will reject further connections from this peer
  256. self.session
  257. .upgrade()
  258. .unwrap()
  259. .p2p()
  260. .hosts()
  261. .mark_rejected(self.address())
  262. .await;
  263. return Err(Error::ChannelStopped)
  264. }
  265. Err(_) => unreachable!("You added a new error in notify()"),
  266. }
  267. }
  268. }
  269. /// Returns the local socket address
  270. pub fn address(&self) -> &Url {
  271. &self.info.addr
  272. }
  273. /// Returns the inner [`MessageSubsystem`] reference
  274. pub fn message_subsystem(&self) -> &MessageSubsystem {
  275. &self.message_subsystem
  276. }
  277. fn session(&self) -> Arc<dyn Session> {
  278. self.session.upgrade().unwrap()
  279. }
  280. pub fn session_type_id(&self) -> SessionBitFlag {
  281. let session = self.session();
  282. session.type_id()
  283. }
  284. fn p2p(&self) -> P2pPtr {
  285. self.session().p2p()
  286. }
  287. fn is_eof_error(err: &Error) -> bool {
  288. match err {
  289. Error::Io(ioerr) => ioerr == &std::io::ErrorKind::UnexpectedEof,
  290. _ => false,
  291. }
  292. }
  293. }
  294. impl fmt::Debug for Channel {
  295. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  296. write!(f, "<Channel addr='{}' id={}>", self.info.addr, self.info.id)
  297. }
  298. }