channel.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. fmt,
  20. sync::{
  21. atomic::{AtomicBool, Ordering::SeqCst},
  22. Arc,
  23. },
  24. time::UNIX_EPOCH,
  25. };
  26. use darkfi_serial::{async_trait, serialize, SerialDecodable, SerialEncodable};
  27. use log::{debug, error, info};
  28. use rand::{rngs::OsRng, Rng};
  29. use smol::{
  30. io::{self, ReadHalf, WriteHalf},
  31. lock::Mutex,
  32. Executor,
  33. };
  34. use url::Url;
  35. use super::{
  36. dnet::{self, dnetev, DnetEvent},
  37. message,
  38. message::Packet,
  39. message_subscriber::{MessageSubscription, MessageSubsystem},
  40. p2p::P2pPtr,
  41. hosts::store::HostColor,
  42. session::{Session, SessionBitFlag, SessionWeakPtr},
  43. transport::PtStream,
  44. };
  45. use crate::{
  46. system::{StoppableTask, StoppableTaskPtr, Subscriber, SubscriberPtr, Subscription},
  47. util::time::NanoTimestamp,
  48. Error, Result,
  49. };
  50. /// Atomic pointer to async channel
  51. pub type ChannelPtr = Arc<Channel>;
  52. /// Channel debug info
  53. #[derive(Clone, Debug, SerialEncodable, SerialDecodable)]
  54. pub struct ChannelInfo {
  55. pub addr: Url,
  56. pub id: u32,
  57. }
  58. impl ChannelInfo {
  59. fn new(addr: Url) -> Self {
  60. Self { addr, id: OsRng.gen() }
  61. }
  62. }
  63. /// Async channel for communication between nodes.
  64. pub struct Channel {
  65. /// The reading half of the transport stream
  66. reader: Mutex<ReadHalf<Box<dyn PtStream>>>,
  67. /// The writing half of the transport stream
  68. writer: Mutex<WriteHalf<Box<dyn PtStream>>>,
  69. /// The message subsystem instance for this channel
  70. message_subsystem: MessageSubsystem,
  71. /// Subscriber listening for stop signal for closing this channel
  72. stop_subscriber: SubscriberPtr<Error>,
  73. /// Task that is listening for the stop signal
  74. receive_task: StoppableTaskPtr,
  75. /// A boolean marking if this channel is stopped
  76. stopped: AtomicBool,
  77. /// Weak pointer to respective session
  78. session: SessionWeakPtr,
  79. /// Channel debug info
  80. pub info: ChannelInfo,
  81. }
  82. impl Channel {
  83. /// Sets up a new channel. Creates a reader and writer [`PtStream`] and
  84. /// the message subscriber subsystem. Performs a network handshake on the
  85. /// subsystem dispatchers.
  86. pub async fn new(stream: Box<dyn PtStream>, addr: Url, session: SessionWeakPtr) -> Arc<Self> {
  87. let (reader, writer) = io::split(stream);
  88. let reader = Mutex::new(reader);
  89. let writer = Mutex::new(writer);
  90. let message_subsystem = MessageSubsystem::new();
  91. Self::setup_dispatchers(&message_subsystem).await;
  92. let info = ChannelInfo::new(addr.clone());
  93. Arc::new(Self {
  94. reader,
  95. writer,
  96. message_subsystem,
  97. stop_subscriber: Subscriber::new(),
  98. receive_task: StoppableTask::new(),
  99. stopped: AtomicBool::new(false),
  100. session,
  101. info,
  102. })
  103. }
  104. /// Perform network handshake for message subsystem dispatchers.
  105. async fn setup_dispatchers(subsystem: &MessageSubsystem) {
  106. subsystem.add_dispatch::<message::VersionMessage>().await;
  107. subsystem.add_dispatch::<message::VerackMessage>().await;
  108. subsystem.add_dispatch::<message::PingMessage>().await;
  109. subsystem.add_dispatch::<message::PongMessage>().await;
  110. subsystem.add_dispatch::<message::GetAddrsMessage>().await;
  111. subsystem.add_dispatch::<message::AddrsMessage>().await;
  112. }
  113. /// Starts the channel. Runs a receive loop to start receiving messages
  114. /// or handles a network failure.
  115. pub fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) {
  116. debug!(target: "net::channel::start()", "START {:?}", self);
  117. let self_ = self.clone();
  118. self.receive_task.clone().start(
  119. self.clone().main_receive_loop(),
  120. |result| self_.handle_stop(result),
  121. Error::ChannelStopped,
  122. executor,
  123. );
  124. debug!(target: "net::channel::start()", "END {:?}", self);
  125. }
  126. /// Stops the channel.
  127. /// Notifies all subscribers that the channel has been closed in `handle_stop()`.
  128. pub async fn stop(&self) {
  129. debug!(target: "net::channel::stop()", "START {:?}", self);
  130. self.receive_task.stop().await;
  131. debug!(target: "net::channel::stop()", "END {:?}", self);
  132. }
  133. /// Creates a subscription to a stopped signal.
  134. /// If the channel is stopped then this will return a ChannelStopped error.
  135. pub async fn subscribe_stop(&self) -> Result<Subscription<Error>> {
  136. debug!(target: "net::channel::subscribe_stop()", "START {:?}", self);
  137. if self.is_stopped() {
  138. return Err(Error::ChannelStopped)
  139. }
  140. let sub = self.stop_subscriber.clone().subscribe().await;
  141. debug!(target: "net::channel::subscribe_stop()", "END {:?}", self);
  142. Ok(sub)
  143. }
  144. pub fn is_stopped(&self) -> bool {
  145. self.stopped.load(SeqCst)
  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={} {:?}",
  153. M::NAME, self,
  154. );
  155. if self.is_stopped() {
  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, e
  163. );
  164. self.stop().await;
  165. return Err(Error::ChannelStopped)
  166. }
  167. debug!(
  168. target: "net::channel::send()", "[END] command={} {:?}",
  169. M::NAME, self
  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={} {:?}",
  192. M::NAME, self
  193. );
  194. let sub = self.message_subsystem.subscribe::<M>().await;
  195. debug!(
  196. target: "net::channel::subscribe_msg()", "[END] command={} {:?}",
  197. M::NAME, self
  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] {:?}", self);
  205. self.stopped.store(true, SeqCst);
  206. match result {
  207. Ok(()) => panic!("Channel task should never complete without error status"),
  208. // Send this error to all channel subscribers
  209. Err(e) => {
  210. self.stop_subscriber.notify(Error::ChannelStopped).await;
  211. self.message_subsystem.trigger_error(e).await;
  212. }
  213. }
  214. debug!(target: "net::channel::handle_stop()", "[END] {:?}", self);
  215. }
  216. /// Run the receive loop. Start receiving messages or handle network failure.
  217. async fn main_receive_loop(self: Arc<Self>) -> Result<()> {
  218. debug!(target: "net::channel::main_receive_loop()", "[START] {:?}", self);
  219. // Acquire reader lock
  220. let reader = &mut *self.reader.lock().await;
  221. // Run loop
  222. loop {
  223. let packet = match message::read_packet(reader).await {
  224. Ok(packet) => packet,
  225. Err(err) => {
  226. if Self::is_eof_error(&err) {
  227. info!(
  228. target: "net::channel::main_receive_loop()",
  229. "[P2P] Channel inbound connection {} disconnected",
  230. self.address(),
  231. );
  232. } else {
  233. error!(
  234. target: "net::channel::main_receive_loop()",
  235. "[P2P] Read error on channel {}: {}",
  236. self.address(), err,
  237. );
  238. }
  239. debug!(
  240. target: "net::channel::main_receive_loop()",
  241. "Stopping channel {:?}", self
  242. );
  243. return Err(Error::ChannelStopped)
  244. }
  245. };
  246. dnetev!(self, RecvMessage, {
  247. chan: self.info.clone(),
  248. cmd: packet.command.clone(),
  249. time: NanoTimestamp::current_time(),
  250. });
  251. // Send result to our subscribers
  252. match self.message_subsystem.notify(&packet.command, &packet.payload).await {
  253. Ok(()) => {}
  254. // If we're getting messages without dispatchers, it's spam.
  255. Err(Error::MissingDispatcher) => {
  256. debug!(target: "net::channel::main_receive_loop()", "Stopping channel {:?}", self);
  257. // We will reject further connections from this peer
  258. self.ban(self.address()).await;
  259. return Err(Error::ChannelStopped)
  260. }
  261. Err(_) => unreachable!("You added a new error in notify()"),
  262. }
  263. }
  264. }
  265. /// Ban a malicious peer and stop the channel.
  266. pub async fn ban(&self, peer: &Url) {
  267. debug!(target: "net::channel::ban()", "START {:?}", self);
  268. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  269. self.p2p().hosts().move_host(&peer, last_seen, HostColor::Black).await;
  270. self.stop().await;
  271. debug!(target: "net::channel::ban()", "STOP {:?}", self);
  272. }
  273. /// Returns the local socket address
  274. pub fn address(&self) -> &Url {
  275. &self.info.addr
  276. }
  277. /// Returns the inner [`MessageSubsystem`] reference
  278. pub fn message_subsystem(&self) -> &MessageSubsystem {
  279. &self.message_subsystem
  280. }
  281. fn session(&self) -> Arc<dyn Session> {
  282. self.session.upgrade().unwrap()
  283. }
  284. pub fn session_type_id(&self) -> SessionBitFlag {
  285. let session = self.session();
  286. session.type_id()
  287. }
  288. fn p2p(&self) -> P2pPtr {
  289. self.session().p2p()
  290. }
  291. fn is_eof_error(err: &Error) -> bool {
  292. match err {
  293. Error::Io(ioerr) => ioerr == &std::io::ErrorKind::UnexpectedEof,
  294. _ => false,
  295. }
  296. }
  297. }
  298. impl fmt::Debug for Channel {
  299. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  300. write!(f, "<Channel addr='{}' id={}>", self.info.addr, self.info.id)
  301. }
  302. }