protocol_version.rs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2026 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 futures::{
  19. future::{join_all, select, Either},
  20. pin_mut,
  21. };
  22. use smol::{lock::RwLock as AsyncRwLock, Executor, Timer};
  23. use std::{
  24. sync::Arc,
  25. time::{Duration, UNIX_EPOCH},
  26. };
  27. use tracing::debug;
  28. use super::super::{
  29. channel::ChannelPtr,
  30. message::{VerackMessage, VersionMessage},
  31. message_publisher::MessageSubscription,
  32. settings::Settings,
  33. };
  34. use crate::{
  35. net::{session::SESSION_OUTBOUND, BanPolicy},
  36. util::logger::verbose,
  37. Error, Result,
  38. };
  39. /// Implements the protocol version handshake sent out by nodes at
  40. /// the beginning of a connection.
  41. pub struct ProtocolVersion {
  42. channel: ChannelPtr,
  43. version_sub: MessageSubscription<VersionMessage>,
  44. verack_sub: MessageSubscription<VerackMessage>,
  45. settings: Arc<AsyncRwLock<Settings>>,
  46. }
  47. impl ProtocolVersion {
  48. /// Create a new version protocol. Makes a version and version ack
  49. /// subscription, then adds them to a version protocol instance.
  50. // TODO: This function takes settings as a param, however, it is also reachable through Channel.
  51. // Maybe we want to navigate towards Settings through channel->session->p2p->settings
  52. pub async fn new(channel: ChannelPtr, settings: Arc<AsyncRwLock<Settings>>) -> Arc<Self> {
  53. // Creates a version subscription
  54. let version_sub =
  55. channel.subscribe_msg::<VersionMessage>().await.expect("Missing version dispatcher!");
  56. // Creates a version acknowledgement subscription
  57. let verack_sub =
  58. channel.subscribe_msg::<VerackMessage>().await.expect("Missing verack dispatcher!");
  59. Arc::new(Self { channel, version_sub, verack_sub, settings })
  60. }
  61. /// Start version information exchange. Start the timer. Send version
  62. /// info and wait for version ack. Wait for version info and send
  63. /// version ack.
  64. pub async fn run(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  65. debug!(target: "net::protocol_version::run", "START => address={}", self.channel.display_address());
  66. let channel_handshake_timeout =
  67. self.settings.read().await.channel_handshake_timeout(self.channel.address().scheme());
  68. let timeout = Timer::after(Duration::from_secs(channel_handshake_timeout));
  69. let version = self.clone().exchange_versions(executor);
  70. pin_mut!(timeout);
  71. pin_mut!(version);
  72. // Run timer and version exchange at the same time. Either deal
  73. // with the success or failure of the version exchange or
  74. // time out.
  75. match select(version, timeout).await {
  76. Either::Left((Ok(_), _)) => {
  77. debug!(target: "net::protocol_version::run", "END => address={}",
  78. self.channel.display_address());
  79. Ok(())
  80. }
  81. Either::Left((Err(e), _)) => {
  82. verbose!(
  83. target: "net::protocol_version::run",
  84. "[P2P] Version Exchange failed [{}]: {e}",
  85. self.channel.display_address()
  86. );
  87. self.channel.stop().await;
  88. Err(e)
  89. }
  90. Either::Right((_, _)) => {
  91. verbose!(
  92. target: "net::protocol_version::run",
  93. "[P2P] Version Exchange timed out [{}]",
  94. self.channel.display_address(),
  95. );
  96. self.channel.stop().await;
  97. Err(Error::ChannelTimeout)
  98. }
  99. }
  100. }
  101. /// Send and receive version information
  102. async fn exchange_versions(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
  103. debug!(
  104. target: "net::protocol_version::exchange_versions",
  105. "START => address={}", self.channel.display_address(),
  106. );
  107. let send = executor.spawn(self.clone().send_version());
  108. let recv = executor.spawn(self.clone().recv_version());
  109. let rets = join_all(vec![send, recv]).await;
  110. if let Err(e) = &rets[0] {
  111. verbose!(
  112. target: "net::protocol_version::exchange_versions",
  113. "send_version() failed: {e}"
  114. );
  115. return Err(e.clone())
  116. }
  117. if let Err(e) = &rets[1] {
  118. verbose!(
  119. target: "net::protocol_version::exchange_versions",
  120. "recv_version() failed: {e}"
  121. );
  122. return Err(e.clone())
  123. }
  124. debug!(
  125. target: "net::protocol_version::exchange_versions",
  126. "END => address={}", self.channel.display_address(),
  127. );
  128. Ok(())
  129. }
  130. /// Send version info and wait for version acknowledgement.
  131. /// Ensures that the app version is the same.
  132. async fn send_version(self: Arc<Self>) -> Result<()> {
  133. debug!(
  134. target: "net::protocol_version::send_version",
  135. "START => address={}", self.channel.display_address(),
  136. );
  137. let settings = self.settings.read().await;
  138. let node_id = settings.node_id.clone();
  139. let app_version = settings.app_version.clone();
  140. let app_name = settings.app_name.clone();
  141. drop(settings);
  142. let external_addrs = self.channel.hosts().external_addrs().await;
  143. let version = VersionMessage {
  144. node_id,
  145. app_name: app_name.clone(),
  146. version: app_version.clone(),
  147. timestamp: UNIX_EPOCH.elapsed().unwrap().as_secs(),
  148. connect_recv_addr: self.channel.connect_addr().clone(),
  149. resolve_recv_addr: self.channel.resolve_addr(),
  150. ext_send_addr: external_addrs,
  151. /* NOTE: `features` is a list of enabled features in the
  152. format Vec<(service, version)>. In the future, Protocols will
  153. add their own data to this field when they are attached.*/
  154. features: vec![],
  155. };
  156. self.channel.send(&version).await?;
  157. // Wait for verack
  158. let verack_msg = self.verack_sub.receive().await?;
  159. // Validate peer received version against our version.
  160. debug!(
  161. target: "net::protocol_version::send_version",
  162. "App version: {app_version}, Recv version: {}",
  163. verack_msg.app_version,
  164. );
  165. // MAJOR and MINOR should be the same, as well as the app identifier
  166. if app_version.major != verack_msg.app_version.major ||
  167. app_version.minor != verack_msg.app_version.minor ||
  168. app_name != verack_msg.app_name
  169. {
  170. verbose!(
  171. target: "net::protocol_version::send_version",
  172. "[P2P] Version mismatch from {}. Disconnecting...",
  173. self.channel.display_address(),
  174. );
  175. // If it is outbound, ban the host so we don't share it with other nodes
  176. if self.channel.session_type_id() & SESSION_OUTBOUND != 0 {
  177. if let BanPolicy::Strict = self.channel.p2p().settings().read().await.ban_policy {
  178. self.channel.ban().await;
  179. }
  180. }
  181. self.channel.stop().await;
  182. return Err(Error::ChannelStopped)
  183. }
  184. // Versions are compatible
  185. debug!(
  186. target: "net::protocol_version::send_version",
  187. "END => address={}", self.channel.display_address(),
  188. );
  189. Ok(())
  190. }
  191. /// Receive version info, check the message is okay and send verack
  192. /// with app version attached.
  193. async fn recv_version(self: Arc<Self>) -> Result<()> {
  194. debug!(
  195. target: "net::protocol_version::recv_version",
  196. "START => address={}", self.channel.display_address(),
  197. );
  198. // Receive version message
  199. let version = self.version_sub.receive().await?;
  200. if let Some(ipv6_addr) = version.get_ipv6_addr() {
  201. let hosts = self.channel.p2p().hosts();
  202. hosts.add_auto_addr(ipv6_addr);
  203. }
  204. self.channel.set_version(version).await;
  205. // Send verack
  206. let settings = self.settings.read().await;
  207. let app_version = settings.app_version.clone();
  208. let app_name = settings.app_name.clone();
  209. drop(settings);
  210. let verack = VerackMessage { app_version, app_name };
  211. self.channel.send(&verack).await?;
  212. debug!(
  213. target: "net::protocol_version::recv_version",
  214. "END => address={}", self.channel.display_address(),
  215. );
  216. Ok(())
  217. }
  218. }