message.rs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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 darkfi_serial::{
  19. async_trait, AsyncDecodable, AsyncEncodable, Decodable, Encodable, SerialDecodable,
  20. SerialEncodable,
  21. };
  22. use log::trace;
  23. use smol::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
  24. use url::Url;
  25. use crate::{Error, Result};
  26. const MAGIC_BYTES: [u8; 4] = [0xd9, 0xef, 0xb6, 0x7d];
  27. /// Generic message template.
  28. pub trait Message: 'static + Send + Sync + Encodable + Decodable {
  29. const NAME: &'static str;
  30. }
  31. #[macro_export]
  32. macro_rules! impl_p2p_message {
  33. ($st:ty, $nm:expr) => {
  34. impl Message for $st {
  35. const NAME: &'static str = $nm;
  36. }
  37. };
  38. }
  39. /// Outbound keepalive message.
  40. #[derive(Debug, Copy, Clone, SerialEncodable, SerialDecodable)]
  41. pub struct PingMessage {
  42. pub nonce: u16,
  43. }
  44. impl_p2p_message!(PingMessage, "ping");
  45. /// Inbound keepalive message.
  46. #[derive(Debug, Copy, Clone, SerialEncodable, SerialDecodable)]
  47. pub struct PongMessage {
  48. pub nonce: u16,
  49. }
  50. impl_p2p_message!(PongMessage, "pong");
  51. /// Requests address of outbound connecction.
  52. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  53. pub struct GetAddrsMessage {
  54. /// Maximum number of addresses with preferred
  55. /// transports to receive. Response vector will
  56. /// also containg addresses without the preferred
  57. /// transports, so its size will be 2 * max.
  58. pub max: u32,
  59. /// Preferred addresses transports
  60. pub transports: Vec<String>,
  61. }
  62. impl_p2p_message!(GetAddrsMessage, "getaddr");
  63. /// Sends address information to inbound connection.
  64. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  65. pub struct AddrsMessage {
  66. pub addrs: Vec<(Url, u64)>,
  67. }
  68. impl_p2p_message!(AddrsMessage, "addr");
  69. /// Requests version information of outbound connection.
  70. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  71. pub struct VersionMessage {
  72. /// Only used for debugging. Compromises privacy when set.
  73. pub node_id: String,
  74. /// Identifies protocol version being used by the node
  75. pub version: semver::Version,
  76. /// UNIX timestamp of when the VersionMessage was created.
  77. pub timestamp: u64,
  78. /// Network address of the node receiving this message (before
  79. /// resolving).
  80. pub connect_recv_addr: Url,
  81. /// Network address of the node receiving this message (after
  82. /// resolving). Optional because only used by outbound connections.
  83. pub resolve_recv_addr: Option<Url>,
  84. /// External address of the sender node, if it exists (empty
  85. /// otherwise).
  86. pub ext_send_addr: Vec<Url>,
  87. /// List of features consisting of a tuple of (services, version)
  88. /// to be enabled for this connection
  89. pub features: Vec<(String, u32)>,
  90. }
  91. impl_p2p_message!(VersionMessage, "version");
  92. /// Sends version information to inbound connection.
  93. /// Response to `VersionMessage`.
  94. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  95. pub struct VerackMessage {
  96. /// App version
  97. pub app_version: semver::Version,
  98. }
  99. impl_p2p_message!(VerackMessage, "verack");
  100. /// Packets are the base type read from the network.
  101. /// Converted to messages and passed to event loop.
  102. #[derive(Debug, SerialEncodable, SerialDecodable)]
  103. pub struct Packet {
  104. pub command: String,
  105. pub payload: Vec<u8>,
  106. }
  107. /// Reads and decodes an inbound payload from the given async stream.
  108. /// Returns decoded [`Packet`].
  109. pub async fn read_packet<R: AsyncRead + Unpin + Send + Sized>(stream: &mut R) -> Result<Packet> {
  110. // Packets should have a 4 byte header of magic digits.
  111. // This is used for network debugging.
  112. let mut magic = [0u8; 4];
  113. trace!(target: "net::message", "Reading magic...");
  114. stream.read_exact(&mut magic).await?;
  115. trace!(target: "net::message", "Read magic {:?}", magic);
  116. if magic != MAGIC_BYTES {
  117. trace!(target: "net::message", "Error: Magic bytes mismatch");
  118. return Err(Error::MalformedPacket)
  119. }
  120. // The type of the message.
  121. let command = String::decode_async(stream).await?;
  122. trace!(target: "net::message", "Read command: {}", command);
  123. // The message-dependent data (see message types)
  124. let payload = Vec::<u8>::decode_async(stream).await?;
  125. trace!(target: "net::message", "Read payload {} bytes", payload.len());
  126. Ok(Packet { command, payload })
  127. }
  128. /// Sends an outbound packet by writing data to the given async stream.
  129. /// Returns the total written bytes.
  130. pub async fn send_packet<W: AsyncWrite + Unpin + Send + Sized>(
  131. stream: &mut W,
  132. packet: Packet,
  133. ) -> Result<usize> {
  134. assert!(!packet.command.is_empty());
  135. assert!(std::mem::size_of::<usize>() <= std::mem::size_of::<u64>());
  136. let mut written: usize = 0;
  137. trace!(target: "net::message", "Sending magic...");
  138. written += MAGIC_BYTES.encode_async(stream).await?;
  139. trace!(target: "net::message", "Sent magic");
  140. written += packet.command.encode_async(stream).await?;
  141. trace!(target: "net::message", "Sent command: {}", packet.command);
  142. written += packet.payload.encode_async(stream).await?;
  143. trace!(target: "net::message", "Sent payload {} bytes", packet.payload.len() as u64);
  144. stream.flush().await?;
  145. Ok(written)
  146. }