channel.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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. hosts::HostColor,
  38. message,
  39. message::{Packet, VersionMessage},
  40. message_subscriber::{MessageSubscription, MessageSubsystem},
  41. p2p::P2pPtr,
  42. session::{Session, SessionBitFlag, SessionWeakPtr, SESSION_ALL, SESSION_REFINE},
  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 resolve_addr: Option<Url>,
  56. pub connect_addr: Url,
  57. pub start_time: u64,
  58. pub id: u32,
  59. }
  60. impl ChannelInfo {
  61. fn new(resolve_addr: Option<Url>, connect_addr: Url, start_time: u64) -> Self {
  62. Self { resolve_addr, connect_addr, start_time, id: OsRng.gen() }
  63. }
  64. }
  65. /// Async channel for communication between nodes.
  66. pub struct Channel {
  67. /// The reading half of the transport stream
  68. reader: Mutex<ReadHalf<Box<dyn PtStream>>>,
  69. /// The writing half of the transport stream
  70. writer: Mutex<WriteHalf<Box<dyn PtStream>>>,
  71. /// The message subsystem instance for this channel
  72. message_subsystem: MessageSubsystem,
  73. /// Subscriber listening for stop signal for closing this channel
  74. stop_subscriber: SubscriberPtr<Error>,
  75. /// Task that is listening for the stop signal
  76. receive_task: StoppableTaskPtr,
  77. /// A boolean marking if this channel is stopped
  78. stopped: AtomicBool,
  79. /// Weak pointer to respective session
  80. session: SessionWeakPtr,
  81. /// The version message of the node we are connected to.
  82. /// Some if the version exchange has already occurred, None
  83. /// otherwise.
  84. version: Mutex<Option<Arc<VersionMessage>>>,
  85. /// Channel debug info
  86. pub info: ChannelInfo,
  87. }
  88. impl Channel {
  89. /// Sets up a new channel. Creates a reader and writer [`PtStream`] and
  90. /// the message subscriber subsystem. Performs a network handshake on the
  91. /// subsystem dispatchers.
  92. pub async fn new(
  93. stream: Box<dyn PtStream>,
  94. resolve_addr: Option<Url>,
  95. connect_addr: Url,
  96. session: SessionWeakPtr,
  97. ) -> Arc<Self> {
  98. let (reader, writer) = io::split(stream);
  99. let reader = Mutex::new(reader);
  100. let writer = Mutex::new(writer);
  101. let message_subsystem = MessageSubsystem::new();
  102. Self::setup_dispatchers(&message_subsystem).await;
  103. let version = Mutex::new(None);
  104. let start_time = UNIX_EPOCH.elapsed().unwrap().as_secs();
  105. let info = ChannelInfo::new(resolve_addr, connect_addr.clone(), start_time);
  106. Arc::new(Self {
  107. reader,
  108. writer,
  109. message_subsystem,
  110. stop_subscriber: Subscriber::new(),
  111. receive_task: StoppableTask::new(),
  112. stopped: AtomicBool::new(false),
  113. session,
  114. version,
  115. info,
  116. })
  117. }
  118. /// Perform network handshake for message subsystem dispatchers.
  119. async fn setup_dispatchers(subsystem: &MessageSubsystem) {
  120. subsystem.add_dispatch::<message::VersionMessage>().await;
  121. subsystem.add_dispatch::<message::VerackMessage>().await;
  122. subsystem.add_dispatch::<message::PingMessage>().await;
  123. subsystem.add_dispatch::<message::PongMessage>().await;
  124. subsystem.add_dispatch::<message::GetAddrsMessage>().await;
  125. subsystem.add_dispatch::<message::AddrsMessage>().await;
  126. }
  127. /// Starts the channel. Runs a receive loop to start receiving messages
  128. /// or handles a network failure.
  129. pub fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) {
  130. debug!(target: "net::channel::start()", "START {:?}", self);
  131. let self_ = self.clone();
  132. self.receive_task.clone().start(
  133. self.clone().main_receive_loop(),
  134. |result| self_.handle_stop(result),
  135. Error::ChannelStopped,
  136. executor,
  137. );
  138. debug!(target: "net::channel::start()", "END {:?}", self);
  139. }
  140. /// Stops the channel.
  141. /// Notifies all subscribers that the channel has been closed in `handle_stop()`.
  142. pub async fn stop(&self) {
  143. debug!(target: "net::channel::stop()", "START {:?}", self);
  144. self.receive_task.stop().await;
  145. debug!(target: "net::channel::stop()", "END {:?}", self);
  146. }
  147. /// Creates a subscription to a stopped signal.
  148. /// If the channel is stopped then this will return a ChannelStopped error.
  149. pub async fn subscribe_stop(&self) -> Result<Subscription<Error>> {
  150. debug!(target: "net::channel::subscribe_stop()", "START {:?}", self);
  151. if self.is_stopped() {
  152. return Err(Error::ChannelStopped)
  153. }
  154. let sub = self.stop_subscriber.clone().subscribe().await;
  155. debug!(target: "net::channel::subscribe_stop()", "END {:?}", self);
  156. Ok(sub)
  157. }
  158. pub fn is_stopped(&self) -> bool {
  159. self.stopped.load(SeqCst)
  160. }
  161. /// Sends a message across a channel. Calls `send_message` that creates
  162. /// a new payload and sends it over the network transport as a packet.
  163. /// Returns an error if something goes wrong.
  164. pub async fn send<M: message::Message>(&self, message: &M) -> Result<()> {
  165. debug!(
  166. target: "net::channel::send()", "[START] command={} {:?}",
  167. M::NAME, self,
  168. );
  169. if self.is_stopped() {
  170. return Err(Error::ChannelStopped)
  171. }
  172. // Catch failure and stop channel, return a net error
  173. if let Err(e) = self.send_message(message).await {
  174. if self.session.upgrade().unwrap().type_id() & (SESSION_ALL & !SESSION_REFINE) != 0 {
  175. error!(
  176. target: "net::channel::send()", "[P2P] Channel send error for [{:?}]: {}",
  177. self, e
  178. );
  179. }
  180. self.stop().await;
  181. return Err(Error::ChannelStopped)
  182. }
  183. debug!(
  184. target: "net::channel::send()", "[END] command={} {:?}",
  185. M::NAME, self
  186. );
  187. Ok(())
  188. }
  189. /// Implements send message functionality. Creates a new payload and
  190. /// encodes it. Then creates a message packet (the base type of the
  191. /// network) and copies the payload into it. Then we send the packet
  192. /// over the network stream.
  193. async fn send_message<M: message::Message>(&self, message: &M) -> Result<()> {
  194. let packet = Packet { command: M::NAME.to_string(), payload: serialize(message) };
  195. dnetev!(self, SendMessage, {
  196. chan: self.info.clone(),
  197. cmd: packet.command.clone(),
  198. time: NanoTimestamp::current_time(),
  199. });
  200. let stream = &mut *self.writer.lock().await;
  201. let _ = message::send_packet(stream, packet).await?;
  202. Ok(())
  203. }
  204. /// Subscribe to a message on the message subsystem.
  205. pub async fn subscribe_msg<M: message::Message>(&self) -> Result<MessageSubscription<M>> {
  206. debug!(
  207. target: "net::channel::subscribe_msg()", "[START] command={} {:?}",
  208. M::NAME, self
  209. );
  210. let sub = self.message_subsystem.subscribe::<M>().await;
  211. debug!(
  212. target: "net::channel::subscribe_msg()", "[END] command={} {:?}",
  213. M::NAME, self
  214. );
  215. sub
  216. }
  217. /// Handle network errors. Panic if error passes silently, otherwise
  218. /// broadcast the error.
  219. async fn handle_stop(self: Arc<Self>, result: Result<()>) {
  220. debug!(target: "net::channel::handle_stop()", "[START] {:?}", self);
  221. self.stopped.store(true, SeqCst);
  222. match result {
  223. Ok(()) => panic!("Channel task should never complete without error status"),
  224. // Send this error to all channel subscribers
  225. Err(e) => {
  226. self.stop_subscriber.notify(Error::ChannelStopped).await;
  227. self.message_subsystem.trigger_error(e).await;
  228. }
  229. }
  230. debug!(target: "net::channel::handle_stop()", "[END] {:?}", self);
  231. }
  232. /// Run the receive loop. Start receiving messages or handle network failure.
  233. async fn main_receive_loop(self: Arc<Self>) -> Result<()> {
  234. debug!(target: "net::channel::main_receive_loop()", "[START] {:?}", self);
  235. // Acquire reader lock
  236. let reader = &mut *self.reader.lock().await;
  237. // Run loop
  238. loop {
  239. let packet = match message::read_packet(reader).await {
  240. Ok(packet) => packet,
  241. Err(err) => {
  242. if Self::is_eof_error(&err) {
  243. info!(
  244. target: "net::channel::main_receive_loop()",
  245. "[P2P] Channel inbound connection {} disconnected",
  246. self.address(),
  247. );
  248. } else if self.session.upgrade().unwrap().type_id() &
  249. (SESSION_ALL & !SESSION_REFINE) !=
  250. 0
  251. {
  252. error!(
  253. target: "net::channel::main_receive_loop()",
  254. "[P2P] Read error on channel {}: {}",
  255. self.address(), err,
  256. );
  257. }
  258. debug!(
  259. target: "net::channel::main_receive_loop()",
  260. "Stopping channel {:?}", self
  261. );
  262. return Err(Error::ChannelStopped)
  263. }
  264. };
  265. dnetev!(self, RecvMessage, {
  266. chan: self.info.clone(),
  267. cmd: packet.command.clone(),
  268. time: NanoTimestamp::current_time(),
  269. });
  270. // Send result to our subscribers
  271. match self.message_subsystem.notify(&packet.command, &packet.payload).await {
  272. Ok(()) => {}
  273. // If we're getting messages without dispatchers, it's spam.
  274. Err(Error::MissingDispatcher) => {
  275. debug!(target: "net::channel::main_receive_loop()", "Stopping channel {:?}", self);
  276. // We will reject further connections from this peer
  277. self.ban(self.address()).await;
  278. return Err(Error::ChannelStopped)
  279. }
  280. Err(_) => unreachable!("You added a new error in notify()"),
  281. }
  282. }
  283. }
  284. /// Ban a malicious peer and stop the channel.
  285. pub async fn ban(&self, peer: &Url) {
  286. debug!(target: "net::channel::ban()", "START {:?}", self);
  287. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  288. self.p2p().hosts().move_host(peer, last_seen, HostColor::Black).await.unwrap();
  289. self.stop().await;
  290. debug!(target: "net::channel::ban()", "STOP {:?}", self);
  291. }
  292. /// Returns the relevant socket address for this connection. If this is
  293. /// an outbound connection, the transport-processed resolve_addr will
  294. /// be returned. Otherwise for inbound connections it will default
  295. /// to connect_addr.
  296. pub fn address(&self) -> &Url {
  297. if self.info.resolve_addr.is_some() {
  298. self.info.resolve_addr.as_ref().unwrap()
  299. } else {
  300. &self.info.connect_addr
  301. }
  302. }
  303. /// Returns the socket address that has undergone transport
  304. /// processing, if it exists. Returns None otherwise.
  305. pub fn resolve_addr(&self) -> Option<Url> {
  306. self.info.resolve_addr.clone()
  307. }
  308. /// Return the socket address without transport processing.
  309. pub fn connect_addr(&self) -> &Url {
  310. &self.info.connect_addr
  311. }
  312. /// Set the VersionMessage of the node this channel is connected
  313. /// to. Called on receiving a version message in `ProtocolVersion`.
  314. pub(crate) async fn set_version(&self, version: Arc<VersionMessage>) {
  315. *self.version.lock().await = Some(version);
  316. }
  317. /// Returns the inner [`MessageSubsystem`] reference
  318. pub fn message_subsystem(&self) -> &MessageSubsystem {
  319. &self.message_subsystem
  320. }
  321. fn session(&self) -> Arc<dyn Session> {
  322. self.session.upgrade().unwrap()
  323. }
  324. pub fn session_type_id(&self) -> SessionBitFlag {
  325. let session = self.session();
  326. session.type_id()
  327. }
  328. fn p2p(&self) -> P2pPtr {
  329. self.session().p2p()
  330. }
  331. fn is_eof_error(err: &Error) -> bool {
  332. match err {
  333. Error::Io(ioerr) => ioerr == &std::io::ErrorKind::UnexpectedEof,
  334. _ => false,
  335. }
  336. }
  337. }
  338. impl fmt::Debug for Channel {
  339. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  340. write!(f, "<Channel addr='{}' id={}>", self.address(), self.info.id)
  341. }
  342. }