message.rs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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 darkfi_serial::{
  19. async_trait, AsyncDecodable, AsyncEncodable, Decodable, Encodable, SerialDecodable,
  20. SerialEncodable, VarInt,
  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, Copy, Clone, SerialEncodable, SerialDecodable)]
  53. pub struct GetAddrsMessage {
  54. /// Maximum number of addresses to receive
  55. pub max: u32,
  56. }
  57. impl_p2p_message!(GetAddrsMessage, "getaddr");
  58. /// Sends address information to inbound connection.
  59. /// Response to `GetAddrsMessage`.
  60. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  61. pub struct AddrsMessage {
  62. pub addrs: Vec<Url>,
  63. }
  64. impl_p2p_message!(AddrsMessage, "addr");
  65. /// Requests version information of outbound connection.
  66. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  67. pub struct VersionMessage {
  68. /// Only used for debugging. Compromises privacy when set.
  69. pub node_id: String,
  70. }
  71. impl_p2p_message!(VersionMessage, "version");
  72. /// Sends version information to inbound connection.
  73. /// Response to `VersionMessage`.
  74. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  75. pub struct VerackMessage {
  76. /// App version
  77. pub app_version: semver::Version,
  78. }
  79. impl_p2p_message!(VerackMessage, "verack");
  80. /// Packets are the base type read from the network.
  81. /// Converted to messages and passed to event loop.
  82. #[derive(Debug, SerialEncodable, SerialDecodable)]
  83. pub struct Packet {
  84. pub command: String,
  85. pub payload: Vec<u8>,
  86. }
  87. /// Reads and decodes an inbound payload from the given async stream.
  88. /// Returns decoded [`Packet`].
  89. pub async fn read_packet<R: AsyncRead + Unpin + Send + Sized>(stream: &mut R) -> Result<Packet> {
  90. // Packets should have a 4 byte header of magic digits.
  91. // This is used for network debugging.
  92. let mut magic = [0u8; 4];
  93. trace!(target: "net::message", "Reading magic...");
  94. stream.read_exact(&mut magic).await?;
  95. trace!(target: "net::message", "Read magic {:?}", magic);
  96. if magic != MAGIC_BYTES {
  97. trace!(target: "net::message", "Error: Magic bytes mismatch");
  98. return Err(Error::MalformedPacket)
  99. }
  100. // The type of the message.
  101. let command_len = VarInt::decode_async(stream).await?.0 as usize;
  102. let mut cmd = vec![0u8; command_len];
  103. stream.read_exact(&mut cmd).await?;
  104. let command = String::from_utf8(cmd)?;
  105. trace!(target: "net::message", "Read command: {}", command);
  106. // The message-dependent data (see message types)
  107. let payload_len = VarInt::decode_async(stream).await?.0 as usize;
  108. let mut payload = vec![0u8; payload_len];
  109. stream.read_exact(&mut payload).await?;
  110. trace!(target: "net::message", "Read payload {} bytes", payload_len);
  111. Ok(Packet { command, payload })
  112. }
  113. /// Sends an outbound packet by writing data to the given async stream.
  114. /// Returns the total written bytes.
  115. pub async fn send_packet<W: AsyncWrite + Unpin + Send + Sized>(
  116. stream: &mut W,
  117. packet: Packet,
  118. ) -> Result<usize> {
  119. assert!(!packet.command.is_empty());
  120. //assert!(!packet.payload.is_empty());
  121. assert!(std::mem::size_of::<usize>() <= std::mem::size_of::<u64>());
  122. let mut written: usize = 0;
  123. trace!(target: "net::message", "Sending magic...");
  124. stream.write_all(&MAGIC_BYTES).await?;
  125. written += MAGIC_BYTES.len();
  126. trace!(target: "net::message", "Sent magic");
  127. trace!(target: "net::message", "Sending command...");
  128. written += VarInt(packet.command.len() as u64).encode_async(stream).await?;
  129. let cmd_ref = packet.command.as_bytes();
  130. stream.write_all(cmd_ref).await?;
  131. written += cmd_ref.len();
  132. trace!(target: "net::message", "Sent command: {}", packet.command);
  133. trace!(target: "net::message", "Sending payload...");
  134. written += VarInt(packet.payload.len() as u64).encode_async(stream).await?;
  135. stream.write_all(&packet.payload).await?;
  136. written += packet.payload.len();
  137. trace!(target: "net::message", "Sent payload {} bytes", packet.payload.len() as u64);
  138. stream.flush().await?;
  139. Ok(written)
  140. }