message.rs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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::{Decodable, Encodable, SerialDecodable, SerialEncodable, VarInt};
  19. use futures::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
  20. use log::debug;
  21. use url::Url;
  22. use crate::{Error, Result};
  23. const MAGIC_BYTES: [u8; 4] = [0xd9, 0xef, 0xb6, 0x7d];
  24. /// Generic message template.
  25. pub trait Message: 'static + Encodable + Decodable + Send + Sync {
  26. fn name() -> &'static str;
  27. }
  28. /// Outbound keep-alive message.
  29. #[derive(SerialEncodable, SerialDecodable)]
  30. pub struct PingMessage {
  31. pub nonce: u32,
  32. }
  33. /// Inbound keep-alive message.
  34. #[derive(SerialEncodable, SerialDecodable)]
  35. pub struct PongMessage {
  36. pub nonce: u32,
  37. }
  38. /// Requests address of outbound connection.
  39. #[derive(SerialEncodable, SerialDecodable)]
  40. pub struct GetAddrsMessage {}
  41. /// Sends address information to inbound connection. Response to GetAddrs
  42. /// message.
  43. #[derive(SerialEncodable, SerialDecodable)]
  44. pub struct AddrsMessage {
  45. pub addrs: Vec<Url>,
  46. }
  47. /// Sends external address information to inbound connection.
  48. #[derive(SerialEncodable, SerialDecodable)]
  49. pub struct ExtAddrsMessage {
  50. pub ext_addrs: Vec<Url>,
  51. }
  52. /// Requests version information of outbound connection.
  53. #[derive(SerialEncodable, SerialDecodable)]
  54. pub struct VersionMessage {
  55. pub node_id: String,
  56. }
  57. /// Sends version information to inbound connection. Response to VersionMessage.
  58. #[derive(SerialEncodable, SerialDecodable)]
  59. pub struct VerackMessage {
  60. // app version
  61. pub app: String,
  62. }
  63. impl Message for PingMessage {
  64. fn name() -> &'static str {
  65. "ping"
  66. }
  67. }
  68. impl Message for PongMessage {
  69. fn name() -> &'static str {
  70. "pong"
  71. }
  72. }
  73. impl Message for GetAddrsMessage {
  74. fn name() -> &'static str {
  75. "getaddr"
  76. }
  77. }
  78. impl Message for AddrsMessage {
  79. fn name() -> &'static str {
  80. "addr"
  81. }
  82. }
  83. impl Message for ExtAddrsMessage {
  84. fn name() -> &'static str {
  85. "extaddr"
  86. }
  87. }
  88. impl Message for VersionMessage {
  89. fn name() -> &'static str {
  90. "version"
  91. }
  92. }
  93. impl Message for VerackMessage {
  94. fn name() -> &'static str {
  95. "verack"
  96. }
  97. }
  98. /// Packets are the base type read from the network. Converted to messages and
  99. /// passed to event loop.
  100. pub struct Packet {
  101. pub command: String,
  102. pub payload: Vec<u8>,
  103. }
  104. /// Reads and decodes an inbound payload.
  105. pub async fn read_packet<R: AsyncRead + Unpin + Sized>(stream: &mut R) -> Result<Packet> {
  106. // Packets have a 4 byte header of magic digits
  107. // This is used for network debugging
  108. let mut magic = [0u8; 4];
  109. debug!(target: "net::message", "reading magic...");
  110. stream.read_exact(&mut magic).await?;
  111. debug!(target: "net::message", "read magic {:?}", magic);
  112. if magic != MAGIC_BYTES {
  113. return Err(Error::MalformedPacket)
  114. }
  115. // The type of the message
  116. let command_len = VarInt::decode_async(stream).await?.0 as usize;
  117. let mut cmd = vec![0u8; command_len];
  118. if command_len > 0 {
  119. stream.read_exact(&mut cmd).await?;
  120. }
  121. let cmd = String::from_utf8(cmd)?;
  122. debug!(target: "net::message", "read command: {}", cmd);
  123. let payload_len = VarInt::decode_async(stream).await?.0 as usize;
  124. // The message-dependent data (see message types)
  125. let mut payload = vec![0u8; payload_len];
  126. if payload_len > 0 {
  127. stream.read_exact(&mut payload).await?;
  128. }
  129. debug!(target: "net::message", "read payload {} bytes", payload_len);
  130. Ok(Packet { command: cmd, payload })
  131. }
  132. /// Sends an outbound packet by writing data to TCP stream.
  133. pub async fn send_packet<W: AsyncWrite + Unpin + Sized>(
  134. stream: &mut W,
  135. packet: Packet,
  136. ) -> Result<()> {
  137. debug!(target: "net::message", "sending magic...");
  138. stream.write_all(&MAGIC_BYTES).await?;
  139. debug!(target: "net::message", "sent magic...");
  140. VarInt(packet.command.len() as u64).encode_async(stream).await?;
  141. assert!(!packet.command.is_empty());
  142. stream.write_all(packet.command.as_bytes()).await?;
  143. debug!(target: "net::message", "sent command: {}", packet.command);
  144. assert_eq!(std::mem::size_of::<usize>(), std::mem::size_of::<u64>());
  145. VarInt(packet.payload.len() as u64).encode_async(stream).await?;
  146. if !packet.payload.is_empty() {
  147. stream.write_all(&packet.payload).await?;
  148. }
  149. debug!(target: "net::message", "sent payload {} bytes", packet.payload.len() as u64);
  150. Ok(())
  151. }