channel.rs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. use async_std::sync::Mutex;
  2. use futures::io::{ReadHalf, WriteHalf};
  3. use futures::AsyncReadExt;
  4. use log::*;
  5. use smol::{Async, Executor};
  6. use std::net::{SocketAddr, TcpStream};
  7. use std::sync::atomic::{AtomicBool, Ordering};
  8. use std::sync::Arc;
  9. use crate::error::{Error, Result};
  10. use crate::net::message_subscriber::{MessageSubscription, MessageSubsystem};
  11. use crate::net::messages;
  12. use crate::system::{StoppableTask, StoppableTaskPtr, Subscriber, SubscriberPtr, Subscription};
  13. /// Atomic pointer to async channel.
  14. pub type ChannelPtr = Arc<Channel>;
  15. /// Async channel for communication between nodes.
  16. pub struct Channel {
  17. reader: Mutex<ReadHalf<Async<TcpStream>>>,
  18. writer: Mutex<WriteHalf<Async<TcpStream>>>,
  19. address: SocketAddr,
  20. message_subsystem: MessageSubsystem,
  21. stop_subscriber: SubscriberPtr<Error>,
  22. receive_task: StoppableTaskPtr,
  23. stopped: AtomicBool,
  24. }
  25. impl Channel {
  26. /// Sets up a new channel. Creates a reader and writer TCP stream and
  27. /// summons the message subscriber subsystem. Performs a network
  28. /// handshake on the subsystem dispatchers.
  29. pub async fn new(stream: Async<TcpStream>, address: SocketAddr) -> Arc<Self> {
  30. let (reader, writer) = stream.split();
  31. let reader = Mutex::new(reader);
  32. let writer = Mutex::new(writer);
  33. let message_subsystem = MessageSubsystem::new();
  34. Self::setup_dispatchers(&message_subsystem).await;
  35. Arc::new(Self {
  36. reader,
  37. writer,
  38. address,
  39. message_subsystem,
  40. stop_subscriber: Subscriber::new(),
  41. receive_task: StoppableTask::new(),
  42. stopped: AtomicBool::new(false),
  43. })
  44. }
  45. /// Starts the channel. Runs a receive loop to start receiving messages or
  46. /// handles a network failure.
  47. pub fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) {
  48. debug!(target: "net", "Channel::start() [START, address={}]", self.address());
  49. let self2 = self.clone();
  50. self.receive_task.clone().start(
  51. self.clone().main_receive_loop(),
  52. // Ignore stop handler
  53. |result| self2.handle_stop(result),
  54. Error::ServiceStopped,
  55. executor,
  56. );
  57. debug!(target: "net", "Channel::start() [END, address={}]", self.address());
  58. }
  59. /// Stops the channel. Steps through each component of the channel
  60. /// connection and sends a stop signal. Notifies all subscribers that
  61. /// the channel has been closed.
  62. pub async fn stop(&self) {
  63. debug!(target: "net", "Channel::stop() [START, address={}]", self.address());
  64. assert_eq!(self.stopped.load(Ordering::Relaxed), false);
  65. // Changes memory ordering to relaxed. We don't need strict thread locking here.
  66. self.stopped.store(false, Ordering::Relaxed);
  67. self.stop_subscriber.notify(Error::ChannelStopped).await;
  68. self.receive_task.stop().await;
  69. self.message_subsystem
  70. .trigger_error(Error::ChannelStopped)
  71. .await;
  72. debug!(target: "net", "Channel::stop() [END, address={}]", self.address());
  73. }
  74. /// Creates a subscription to a stopped signal.
  75. pub async fn subscribe_stop(&self) -> Subscription<Error> {
  76. debug!(target: "net",
  77. "Channel::subscribe_stop() [START, address={}]",
  78. self.address()
  79. );
  80. // TODO: this should check the stopped status
  81. // Call to receive should return ChannelStopped on newly created sub
  82. let sub = self.stop_subscriber.clone().subscribe().await;
  83. debug!(target: "net",
  84. "Channel::subscribe_stop() [END, address={}]",
  85. self.address()
  86. );
  87. sub
  88. }
  89. /// Sends a message across a channel. Calls function 'send_message' that
  90. /// creates a new payload and sends it over the TCP connection as a
  91. /// packet. Returns an error if something goes wrong.
  92. pub async fn send<M: messages::Message>(&self, message: M) -> Result<()> {
  93. debug!(target: "net",
  94. "Channel::send() [START, command={:?}, address={}]",
  95. M::name(),
  96. self.address()
  97. );
  98. if self.stopped.load(Ordering::Relaxed) {
  99. return Err(Error::ChannelStopped);
  100. }
  101. // Catch failure and stop channel, return a net error
  102. let result = match self.send_message(message).await {
  103. Ok(()) => Ok(()),
  104. Err(err) => {
  105. error!("Channel send error for [{}]: {}", self.address(), err);
  106. self.stop().await;
  107. Err(Error::ChannelStopped)
  108. }
  109. };
  110. debug!(target: "net",
  111. "Channel::send() [END, command={:?}, address={}]",
  112. M::name(),
  113. self.address()
  114. );
  115. result
  116. }
  117. /// Implements send message functionality. Creates a new payload and encodes
  118. /// it. Then creates a message packet- the base type of the network- and
  119. /// copies the payload into it. Then we send the packet over the TCP
  120. /// stream.
  121. async fn send_message<M: messages::Message>(&self, message: M) -> Result<()> {
  122. let mut payload = Vec::new();
  123. message.encode(&mut payload)?;
  124. let packet = messages::Packet {
  125. command: String::from(M::name()),
  126. payload,
  127. };
  128. let stream = &mut *self.writer.lock().await;
  129. messages::send_packet(stream, packet).await
  130. }
  131. /// Subscribe to a messages on the message subsystem.
  132. pub async fn subscribe_msg<M: messages::Message>(&self) -> Result<MessageSubscription<M>> {
  133. debug!(target: "net",
  134. "Channel::subscribe_msg() [START, command={:?}, address={}]",
  135. M::name(),
  136. self.address()
  137. );
  138. let sub = self.message_subsystem.subscribe::<M>().await;
  139. debug!(target: "net",
  140. "Channel::subscribe_msg() [END, command={:?}, address={}]",
  141. M::name(),
  142. self.address()
  143. );
  144. sub
  145. }
  146. /// Return the local socket address.
  147. pub fn address(&self) -> SocketAddr {
  148. self.address
  149. }
  150. /// End of file error. Triggered when unexpected end of file occurs.
  151. fn is_eof_error(err: Error) -> bool {
  152. match err {
  153. Error::Io(io_err) => io_err.clone() == std::io::ErrorKind::UnexpectedEof,
  154. _ => false,
  155. }
  156. }
  157. /// Perform network handshake for message subsystem dispatchers.
  158. async fn setup_dispatchers(message_subsystem: &MessageSubsystem) {
  159. message_subsystem
  160. .add_dispatch::<messages::VersionMessage>()
  161. .await;
  162. message_subsystem
  163. .add_dispatch::<messages::VerackMessage>()
  164. .await;
  165. message_subsystem
  166. .add_dispatch::<messages::PingMessage>()
  167. .await;
  168. message_subsystem
  169. .add_dispatch::<messages::PongMessage>()
  170. .await;
  171. message_subsystem
  172. .add_dispatch::<messages::GetAddrsMessage>()
  173. .await;
  174. message_subsystem
  175. .add_dispatch::<messages::AddrsMessage>()
  176. .await;
  177. }
  178. /// Convenience function that returns the Message Subsystem.
  179. pub fn get_message_subsystem(&self) -> &MessageSubsystem {
  180. &self.message_subsystem
  181. }
  182. /// Run the receive loop. Start receiving messages or handle network
  183. /// failure.
  184. async fn main_receive_loop(self: Arc<Self>) -> Result<()> {
  185. debug!(target: "net",
  186. "Channel::receive_loop() [START, address={}]",
  187. self.address()
  188. );
  189. let reader = &mut *self.reader.lock().await;
  190. loop {
  191. let packet = match messages::read_packet(reader).await {
  192. Ok(packet) => packet,
  193. Err(err) => {
  194. if Self::is_eof_error(err.clone()) {
  195. info!("Channel {} disconnected", self.address());
  196. } else {
  197. error!("Read error on channel: {}", err);
  198. }
  199. debug!(target: "net",
  200. "Channel::receive_loop() stopping channel {}",
  201. self.address()
  202. );
  203. self.stop().await;
  204. return Err(Error::ChannelStopped);
  205. }
  206. };
  207. // Send result to our subscribers
  208. self.message_subsystem
  209. .notify(&packet.command, packet.payload)
  210. .await;
  211. }
  212. }
  213. /// Handle network errors. Panic if error passes silently, otherwise
  214. /// broadcast the error.
  215. async fn handle_stop(self: Arc<Self>, result: Result<()>) {
  216. debug!(target: "net", "Channel::handle_stop() [START, address={}]", self.address());
  217. match result {
  218. Ok(()) => panic!("Channel task should never complete without error status"),
  219. Err(err) => {
  220. // Send this error to all channel subscribers
  221. self.message_subsystem.trigger_error(err).await;
  222. }
  223. }
  224. debug!(target: "net", "Channel::handle_stop() [END, address={}]", self.address());
  225. }
  226. }