channel.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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 async_std::sync::{Arc, Mutex};
  19. use futures::{
  20. io::{ReadHalf, WriteHalf},
  21. AsyncReadExt,
  22. };
  23. use log::{debug, error, info};
  24. use rand::Rng;
  25. use serde_json::json;
  26. use smol::Executor;
  27. use url::Url;
  28. use super::{
  29. message,
  30. message_subscriber::{MessageSubscription, MessageSubsystem},
  31. transport::TransportStream,
  32. Session, SessionBitflag, SessionWeakPtr,
  33. };
  34. use crate::{
  35. system::{StoppableTask, StoppableTaskPtr, Subscriber, SubscriberPtr, Subscription},
  36. util::{ringbuffer::RingBuffer, time::NanoTimestamp},
  37. Error, Result,
  38. };
  39. /// Atomic pointer to async channel.
  40. pub type ChannelPtr = Arc<Channel>;
  41. const SIZE_OF_BUFFER: usize = 65536;
  42. struct ChannelInfo {
  43. random_id: u32,
  44. remote_node_id: String,
  45. last_msg: String,
  46. last_status: String,
  47. // Message log which is cleared on querying get_info
  48. log: Option<Mutex<RingBuffer<(NanoTimestamp, String, String)>>>,
  49. }
  50. impl ChannelInfo {
  51. fn new(channel_log: bool) -> Self {
  52. let log = match channel_log {
  53. true => Some(Mutex::new(RingBuffer::new(SIZE_OF_BUFFER))),
  54. false => None,
  55. };
  56. Self {
  57. random_id: rand::thread_rng().gen(),
  58. remote_node_id: String::new(),
  59. last_msg: String::new(),
  60. last_status: String::new(),
  61. log,
  62. }
  63. }
  64. // ANCHOR: get_info
  65. async fn get_info(&self) -> serde_json::Value {
  66. let log = match &self.log {
  67. Some(l) => {
  68. let mut lock = l.lock().await;
  69. let ret = lock.clone();
  70. *lock = RingBuffer::new(SIZE_OF_BUFFER);
  71. ret
  72. }
  73. None => RingBuffer::new(0),
  74. };
  75. json!({
  76. "random_id": self.random_id,
  77. "remote_node_id": self.remote_node_id,
  78. "last_msg": self.last_msg,
  79. "last_status": self.last_status,
  80. "log": log,
  81. })
  82. }
  83. // ANCHOR_END: get_info
  84. }
  85. /// Async channel for communication between nodes.
  86. pub struct Channel {
  87. reader: Mutex<ReadHalf<Box<dyn TransportStream>>>,
  88. writer: Mutex<WriteHalf<Box<dyn TransportStream>>>,
  89. address: Url,
  90. message_subsystem: MessageSubsystem,
  91. stop_subscriber: SubscriberPtr<Error>,
  92. receive_task: StoppableTaskPtr,
  93. stopped: Mutex<bool>,
  94. info: Mutex<ChannelInfo>,
  95. session: SessionWeakPtr,
  96. }
  97. impl Channel {
  98. /// Sets up a new channel. Creates a reader and writer TCP stream and
  99. /// summons the message subscriber subsystem. Performs a network
  100. /// handshake on the subsystem dispatchers.
  101. pub async fn new(
  102. stream: Box<dyn TransportStream>,
  103. address: Url,
  104. session: SessionWeakPtr,
  105. ) -> Arc<Self> {
  106. let (reader, writer) = stream.split();
  107. let reader = Mutex::new(reader);
  108. let writer = Mutex::new(writer);
  109. let message_subsystem = MessageSubsystem::new();
  110. Self::setup_dispatchers(&message_subsystem).await;
  111. let channel_log = session.upgrade().unwrap().p2p().settings().channel_log;
  112. Arc::new(Self {
  113. reader,
  114. writer,
  115. address,
  116. message_subsystem,
  117. stop_subscriber: Subscriber::new(),
  118. receive_task: StoppableTask::new(),
  119. stopped: Mutex::new(false),
  120. info: Mutex::new(ChannelInfo::new(channel_log)),
  121. session,
  122. })
  123. }
  124. pub async fn get_info(&self) -> serde_json::Value {
  125. self.info.lock().await.get_info().await
  126. }
  127. /// Starts the channel. Runs a receive loop to start receiving messages or
  128. /// handles a network failure.
  129. pub fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) {
  130. debug!(target: "net::channel::start()", "START, address={}", self.address());
  131. let self2 = self.clone();
  132. self.receive_task.clone().start(
  133. self.clone().main_receive_loop(),
  134. |result| self2.handle_stop(result),
  135. Error::NetworkServiceStopped,
  136. executor,
  137. );
  138. debug!(target: "net::channel::start()", "END, address={}", self.address());
  139. }
  140. /// Stops the channel. Steps through each component of the channel
  141. /// connection and sends a stop signal. Notifies all subscribers that
  142. /// the channel has been closed.
  143. pub async fn stop(&self) {
  144. debug!(target: "net::channel::stop()", "START, address={}", self.address());
  145. if !(*self.stopped.lock().await) {
  146. *self.stopped.lock().await = true;
  147. self.stop_subscriber.notify(Error::ChannelStopped).await;
  148. self.receive_task.stop().await;
  149. self.message_subsystem.trigger_error(Error::ChannelStopped).await;
  150. debug!(target: "net::channel::stop()", "END, address={}", self.address());
  151. }
  152. }
  153. /// Creates a subscription to a stopped signal.
  154. /// If the channel is stopped then this will return a ChannelStopped error.
  155. pub async fn subscribe_stop(&self) -> Result<Subscription<Error>> {
  156. debug!(target: "net::channel::subscribe_stop()", "START, address={}", self.address());
  157. {
  158. let stopped = *self.stopped.lock().await;
  159. if stopped {
  160. return Err(Error::ChannelStopped)
  161. }
  162. }
  163. let sub = self.stop_subscriber.clone().subscribe().await;
  164. debug!(target: "net::channel::subscribe_stop()", "END, address={}", self.address());
  165. Ok(sub)
  166. }
  167. /// Sends a message across a channel. Calls function 'send_message' that
  168. /// creates a new payload and sends it over the TCP connection as a
  169. /// packet. Returns an error if something goes wrong.
  170. pub async fn send<M: message::Message>(&self, message: M) -> Result<()> {
  171. debug!(
  172. target: "net::channel::send()",
  173. "START, command={:?}, address={}",
  174. M::name(),
  175. self.address()
  176. );
  177. {
  178. let stopped = *self.stopped.lock().await;
  179. if stopped {
  180. return Err(Error::ChannelStopped)
  181. }
  182. }
  183. // Catch failure and stop channel, return a net error
  184. let result = match self.send_message(message).await {
  185. Ok(()) => Ok(()),
  186. Err(err) => {
  187. error!(target: "net::channel::send()", "Channel send error for [{}]: {}", self.address(), err);
  188. self.stop().await;
  189. Err(Error::ChannelStopped)
  190. }
  191. };
  192. debug!(
  193. target: "net::channel::send()",
  194. "END, command={:?}, address={}",
  195. M::name(),
  196. self.address()
  197. );
  198. {
  199. let info = &mut *self.info.lock().await;
  200. info.last_msg = M::name().to_string();
  201. info.last_status = "sent".to_string();
  202. }
  203. result
  204. }
  205. /// Implements send message functionality. Creates a new payload and encodes
  206. /// it. Then creates a message packet- the base type of the network- and
  207. /// copies the payload into it. Then we send the packet over the TCP
  208. /// stream.
  209. async fn send_message<M: message::Message>(&self, message: M) -> Result<()> {
  210. let mut payload = Vec::new();
  211. message.encode(&mut payload)?;
  212. let packet = message::Packet { command: String::from(M::name()), payload };
  213. let time = NanoTimestamp::current_time();
  214. //let time = time::unix_timestamp()?;
  215. {
  216. let info = &mut *self.info.lock().await;
  217. if let Some(l) = &info.log {
  218. l.lock().await.push((time, "send".to_string(), packet.command.clone()));
  219. };
  220. }
  221. let stream = &mut *self.writer.lock().await;
  222. message::send_packet(stream, packet).await
  223. }
  224. /// Subscribe to a messages on the message subsystem.
  225. pub async fn subscribe_msg<M: message::Message>(&self) -> Result<MessageSubscription<M>> {
  226. debug!(
  227. target: "net::channel::subscribe_msg()",
  228. "START, command={:?}, address={}",
  229. M::name(),
  230. self.address()
  231. );
  232. let sub = self.message_subsystem.subscribe::<M>().await;
  233. debug!(
  234. target: "net::channel::subscribe_msg()",
  235. "END, command={:?}, address={}",
  236. M::name(),
  237. self.address()
  238. );
  239. sub
  240. }
  241. /// Return the local socket address.
  242. pub fn address(&self) -> Url {
  243. self.address.clone()
  244. }
  245. pub async fn remote_node_id(&self) -> String {
  246. self.info.lock().await.remote_node_id.clone()
  247. }
  248. pub async fn set_remote_node_id(&self, remote_node_id: String) {
  249. self.info.lock().await.remote_node_id = remote_node_id;
  250. }
  251. /// End of file error. Triggered when unexpected end of file occurs.
  252. fn is_eof_error(err: Error) -> bool {
  253. match err {
  254. Error::Io(io_err) => io_err == std::io::ErrorKind::UnexpectedEof,
  255. _ => false,
  256. }
  257. }
  258. /// Perform network handshake for message subsystem dispatchers.
  259. async fn setup_dispatchers(message_subsystem: &MessageSubsystem) {
  260. message_subsystem.add_dispatch::<message::VersionMessage>().await;
  261. message_subsystem.add_dispatch::<message::VerackMessage>().await;
  262. message_subsystem.add_dispatch::<message::PingMessage>().await;
  263. message_subsystem.add_dispatch::<message::PongMessage>().await;
  264. message_subsystem.add_dispatch::<message::GetAddrsMessage>().await;
  265. message_subsystem.add_dispatch::<message::AddrsMessage>().await;
  266. message_subsystem.add_dispatch::<message::ExtAddrsMessage>().await;
  267. }
  268. /// Convenience function that returns the Message Subsystem.
  269. pub fn get_message_subsystem(&self) -> &MessageSubsystem {
  270. &self.message_subsystem
  271. }
  272. /// Run the receive loop. Start receiving messages or handle network
  273. /// failure.
  274. async fn main_receive_loop(self: Arc<Self>) -> Result<()> {
  275. debug!(target: "net::channel::main_receive_loop()", "START, address={}", self.address());
  276. let reader = &mut *self.reader.lock().await;
  277. loop {
  278. let packet = match message::read_packet(reader).await {
  279. Ok(packet) => packet,
  280. Err(err) => {
  281. if Self::is_eof_error(err.clone()) {
  282. info!(
  283. target: "net::channel::main_receive_loop()",
  284. "Inbound connection {} disconnected",
  285. self.address()
  286. );
  287. } else {
  288. error!(
  289. target: "net::channel::main_receive_loop()",
  290. "Read error on channel {}: {}",
  291. self.address(),
  292. err
  293. );
  294. }
  295. debug!(
  296. target: "net::channel::main_receive_loop()",
  297. "Channel::receive_loop() stopping channel {}",
  298. self.address()
  299. );
  300. self.stop().await;
  301. return Err(Error::ChannelStopped)
  302. }
  303. };
  304. {
  305. let info = &mut *self.info.lock().await;
  306. info.last_msg = packet.command.clone();
  307. info.last_status = "recv".to_string();
  308. let time = NanoTimestamp::current_time();
  309. //let time = time::unix_timestamp()?;
  310. if let Some(l) = &info.log {
  311. l.lock().await.push((time, "recv".to_string(), packet.command.clone()));
  312. };
  313. }
  314. // Send result to our subscribers
  315. self.message_subsystem.notify(&packet.command, packet.payload).await;
  316. }
  317. }
  318. /// Handle network errors. Panic if error passes silently, otherwise
  319. /// broadcast the error.
  320. async fn handle_stop(self: Arc<Self>, result: Result<()>) {
  321. debug!(
  322. target: "net::channel::handle_stop()",
  323. "START, address={}",
  324. self.address()
  325. );
  326. match result {
  327. Ok(()) => panic!("Channel task should never complete without error status"),
  328. Err(err) => {
  329. // Send this error to all channel subscribers
  330. self.message_subsystem.trigger_error(err).await;
  331. }
  332. }
  333. debug!(
  334. target: "net::channel::handle_stop()",
  335. "END, address={}",
  336. self.address()
  337. );
  338. }
  339. fn session(&self) -> Arc<dyn Session> {
  340. self.session.upgrade().unwrap()
  341. }
  342. pub fn session_type_id(&self) -> SessionBitflag {
  343. let session = self.session();
  344. session.type_id()
  345. }
  346. }