message.rs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. use futures::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
  2. use log::debug;
  3. use std::{io, net::SocketAddr};
  4. use crate::{
  5. util::serial::{Decodable, Encodable, VarInt},
  6. Error, Result,
  7. };
  8. const MAGIC_BYTES: [u8; 4] = [0xd9, 0xef, 0xb6, 0x7d];
  9. /// Generic message template.
  10. pub trait Message: 'static + Encodable + Decodable + Send + Sync {
  11. fn name() -> &'static str;
  12. }
  13. /// Outbound keep-alive message.
  14. pub struct PingMessage {
  15. pub nonce: u32,
  16. }
  17. /// Inbound keep-alive message.
  18. pub struct PongMessage {
  19. pub nonce: u32,
  20. }
  21. /// Requests address of outbound connection.
  22. pub struct GetAddrsMessage {}
  23. /// Sends address information to inbound connection. Response to GetAddrs
  24. /// message.
  25. pub struct AddrsMessage {
  26. pub addrs: Vec<SocketAddr>,
  27. }
  28. /// Requests version information of outbound connection.
  29. pub struct VersionMessage {}
  30. /// Sends version information to inbound connection. Response to VersionMessage.
  31. pub struct VerackMessage {}
  32. impl Message for PingMessage {
  33. fn name() -> &'static str {
  34. "ping"
  35. }
  36. }
  37. impl Message for PongMessage {
  38. fn name() -> &'static str {
  39. "pong"
  40. }
  41. }
  42. impl Message for GetAddrsMessage {
  43. fn name() -> &'static str {
  44. "getaddr"
  45. }
  46. }
  47. impl Message for AddrsMessage {
  48. fn name() -> &'static str {
  49. "addr"
  50. }
  51. }
  52. impl Message for VersionMessage {
  53. fn name() -> &'static str {
  54. "version"
  55. }
  56. }
  57. impl Message for VerackMessage {
  58. fn name() -> &'static str {
  59. "verack"
  60. }
  61. }
  62. impl Encodable for PingMessage {
  63. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  64. let mut len = 0;
  65. len += self.nonce.encode(&mut s)?;
  66. Ok(len)
  67. }
  68. }
  69. impl Decodable for PingMessage {
  70. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  71. Ok(Self { nonce: Decodable::decode(&mut d)? })
  72. }
  73. }
  74. impl Encodable for PongMessage {
  75. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  76. let mut len = 0;
  77. len += self.nonce.encode(&mut s)?;
  78. Ok(len)
  79. }
  80. }
  81. impl Decodable for PongMessage {
  82. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  83. Ok(Self { nonce: Decodable::decode(&mut d)? })
  84. }
  85. }
  86. impl Encodable for GetAddrsMessage {
  87. fn encode<S: io::Write>(&self, mut _s: S) -> Result<usize> {
  88. let len = 0;
  89. Ok(len)
  90. }
  91. }
  92. impl Decodable for GetAddrsMessage {
  93. fn decode<D: io::Read>(mut _d: D) -> Result<Self> {
  94. Ok(Self {})
  95. }
  96. }
  97. impl Encodable for AddrsMessage {
  98. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  99. let mut len = 0;
  100. len += self.addrs.encode(&mut s)?;
  101. Ok(len)
  102. }
  103. }
  104. impl Decodable for AddrsMessage {
  105. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  106. Ok(Self { addrs: Decodable::decode(&mut d)? })
  107. }
  108. }
  109. impl Encodable for VersionMessage {
  110. fn encode<S: io::Write>(&self, _s: S) -> Result<usize> {
  111. Ok(0)
  112. }
  113. }
  114. impl Decodable for VersionMessage {
  115. fn decode<D: io::Read>(_d: D) -> Result<Self> {
  116. Ok(Self {})
  117. }
  118. }
  119. impl Encodable for VerackMessage {
  120. fn encode<S: io::Write>(&self, _s: S) -> Result<usize> {
  121. Ok(0)
  122. }
  123. }
  124. impl Decodable for VerackMessage {
  125. fn decode<D: io::Read>(_d: D) -> Result<Self> {
  126. Ok(Self {})
  127. }
  128. }
  129. /// Packets are the base type read from the network. Converted to messages and
  130. /// passed to event loop.
  131. pub struct Packet {
  132. pub command: String,
  133. pub payload: Vec<u8>,
  134. }
  135. /// Reads and decodes an inbound payload.
  136. pub async fn read_packet<R: AsyncRead + Unpin>(stream: &mut R) -> Result<Packet> {
  137. // Packets have a 4 byte header of magic digits
  138. // This is used for network debugging
  139. let mut magic = [0u8; 4];
  140. debug!(target: "net", "reading magic...");
  141. stream.read_exact(&mut magic).await?;
  142. debug!(target: "net", "read magic {:?}", magic);
  143. if magic != MAGIC_BYTES {
  144. return Err(Error::MalformedPacket)
  145. }
  146. // The type of the message
  147. let command_len = VarInt::decode_async(stream).await?.0 as usize;
  148. let mut cmd = vec![0u8; command_len];
  149. if command_len > 0 {
  150. stream.read_exact(&mut cmd).await?;
  151. }
  152. let cmd = String::from_utf8(cmd)?;
  153. debug!(target: "net", "read command: {}", cmd);
  154. let payload_len = VarInt::decode_async(stream).await?.0 as usize;
  155. // The message-dependent data (see message types)
  156. let mut payload = vec![0u8; payload_len];
  157. if payload_len > 0 {
  158. stream.read_exact(&mut payload).await?;
  159. }
  160. debug!(target: "net", "read payload {} bytes", payload_len);
  161. Ok(Packet { command: cmd, payload })
  162. }
  163. /// Sends an outbound packet by writing data to TCP stream.
  164. pub async fn send_packet<W: AsyncWrite + Unpin>(stream: &mut W, packet: Packet) -> Result<()> {
  165. debug!(target: "net", "sending magic...");
  166. stream.write_all(&MAGIC_BYTES).await?;
  167. debug!(target: "net", "sent magic...");
  168. VarInt(packet.command.len() as u64).encode_async(stream).await?;
  169. assert!(!packet.command.is_empty());
  170. stream.write_all(packet.command.as_bytes()).await?;
  171. debug!(target: "net", "sent command: {}", packet.command);
  172. assert_eq!(std::mem::size_of::<usize>(), std::mem::size_of::<u64>());
  173. VarInt(packet.payload.len() as u64).encode_async(stream).await?;
  174. if !packet.payload.is_empty() {
  175. stream.write_all(&packet.payload).await?;
  176. }
  177. debug!(target: "net", "sent payload {} bytes", packet.payload.len() as u64);
  178. Ok(())
  179. }