protocol_address.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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 async_trait::async_trait;
  19. use log::debug;
  20. use smol::{lock::RwLock as AsyncRwLock, Executor};
  21. use std::{sync::Arc, time::UNIX_EPOCH};
  22. use super::{
  23. super::{
  24. channel::ChannelPtr,
  25. hosts::{HostColor, HostsPtr},
  26. message::{AddrsMessage, GetAddrsMessage},
  27. message_publisher::MessageSubscription,
  28. p2p::P2pPtr,
  29. session::SESSION_OUTBOUND,
  30. settings::Settings,
  31. },
  32. protocol_base::{ProtocolBase, ProtocolBasePtr},
  33. protocol_jobs_manager::{ProtocolJobsManager, ProtocolJobsManagerPtr},
  34. };
  35. use crate::Result;
  36. /// Defines address and get-address messages.
  37. ///
  38. /// On receiving GetAddr, nodes reply an AddrMessage containing nodes from
  39. /// their hostlist. On receiving an AddrMessage, nodes enter the info into
  40. /// their greylists.
  41. ///
  42. /// The node selection logic for creating an AddrMessage is as follows:
  43. ///
  44. /// 1. First select nodes matching the requested transports from the
  45. /// anchorlist. These nodes have the highest guarantee of being reachable,
  46. /// so we prioritize them first.
  47. ///
  48. /// 2. Then select nodes matching the requested transports from the
  49. /// whitelist.
  50. ///
  51. /// 3. Next select whitelist nodes that don't match our transports. We do
  52. /// this so that nodes share and propagate nodes of different transports,
  53. /// even if they can't connect to them themselves.
  54. ///
  55. /// 4. Finally, if there's still space available, fill the remaining vector
  56. /// space with darklist entries. This is necessary to propagate transports
  57. /// that neither this node nor the receiving node support.
  58. pub struct ProtocolAddress {
  59. channel: ChannelPtr,
  60. addrs_sub: MessageSubscription<AddrsMessage>,
  61. get_addrs_sub: MessageSubscription<GetAddrsMessage>,
  62. hosts: HostsPtr,
  63. settings: Arc<AsyncRwLock<Settings>>,
  64. jobsman: ProtocolJobsManagerPtr,
  65. }
  66. const PROTO_NAME: &str = "ProtocolAddress";
  67. /// A vector of all currently accepted transports and valid transport
  68. /// combinations. Should be updated if and when new transports are
  69. /// added. Creates a upper bound on the number of transports a given peer
  70. /// can request.
  71. const TRANSPORT_COMBOS: [&str; 9] =
  72. ["tor", "tls", "tcp", "nym", "i2p", "tor+tls", "nym+tls", "tcp+tls", "i2p+tls"];
  73. impl ProtocolAddress {
  74. /// Creates a new address protocol. Makes an address, an external address
  75. /// and a get-address subscription and adds them to the address protocol
  76. /// instance.
  77. pub async fn init(channel: ChannelPtr, p2p: P2pPtr) -> ProtocolBasePtr {
  78. // Creates a subscription to address message
  79. let addrs_sub =
  80. channel.subscribe_msg::<AddrsMessage>().await.expect("Missing addrs dispatcher!");
  81. // Creates a subscription to get-address message
  82. let get_addrs_sub =
  83. channel.subscribe_msg::<GetAddrsMessage>().await.expect("Missing getaddrs dispatcher!");
  84. Arc::new(Self {
  85. channel: channel.clone(),
  86. addrs_sub,
  87. get_addrs_sub,
  88. hosts: p2p.hosts(),
  89. jobsman: ProtocolJobsManager::new(PROTO_NAME, channel),
  90. settings: p2p.settings(),
  91. })
  92. }
  93. /// Handles receiving the address message. Loops to continually receive
  94. /// address messages on the address subscription. Validates and adds the
  95. /// received addresses to the greylist.
  96. async fn handle_receive_addrs(self: Arc<Self>) -> Result<()> {
  97. debug!(
  98. target: "net::protocol_address::handle_receive_addrs()",
  99. "[START] address={}", self.channel.display_address(),
  100. );
  101. loop {
  102. let addrs_msg = self.addrs_sub.receive().await?;
  103. debug!(
  104. target: "net::protocol_address::handle_receive_addrs()",
  105. "Received {} addrs from {}", addrs_msg.addrs.len(), self.channel.display_address(),
  106. );
  107. debug!(
  108. target: "net::protocol_address::handle_receive_addrs()",
  109. "Appending to greylist...",
  110. );
  111. self.hosts.insert(HostColor::Grey, &addrs_msg.addrs).await;
  112. }
  113. }
  114. /// Handles receiving the get-address message. Continually receives
  115. /// get-address messages on the get-address subscription. Then replies
  116. /// with an address message.
  117. async fn handle_receive_get_addrs(self: Arc<Self>) -> Result<()> {
  118. debug!(
  119. target: "net::protocol_address::handle_receive_get_addrs()",
  120. "[START] address={}", self.channel.display_address(),
  121. );
  122. loop {
  123. let get_addrs_msg = self.get_addrs_sub.receive().await?;
  124. debug!(
  125. target: "net::protocol_address::handle_receive_get_addrs()",
  126. "Received GetAddrs({}) message from {}", get_addrs_msg.max, self.channel.display_address(),
  127. );
  128. // Filter out transports not meant to be shared like Socks5 and Socks5+tls
  129. let requested_transports: Vec<String> = get_addrs_msg
  130. .transports
  131. .iter()
  132. .filter(|tp| TRANSPORT_COMBOS.contains(&tp.as_str()))
  133. .cloned()
  134. .collect();
  135. // First we grab address with the requested transports from the gold list
  136. debug!(target: "net::protocol_address::handle_receive_get_addrs()",
  137. "Fetching gold entries with schemes");
  138. let mut addrs = self.hosts.container.fetch_n_random_with_schemes(
  139. HostColor::Gold,
  140. &requested_transports,
  141. get_addrs_msg.max,
  142. );
  143. // Then we grab address with the requested transports from the whitelist
  144. debug!(target: "net::protocol_address::handle_receive_get_addrs()",
  145. "Fetching whitelist entries with schemes");
  146. addrs.append(&mut self.hosts.container.fetch_n_random_with_schemes(
  147. HostColor::White,
  148. &requested_transports,
  149. get_addrs_msg.max,
  150. ));
  151. // Next we grab addresses without the requested transports
  152. // to fill a 2 * max length vector.
  153. // Then we grab address without the requested transports from the gold list
  154. debug!(target: "net::protocol_address::handle_receive_get_addrs()",
  155. "Fetching gold entries without schemes");
  156. let remain = 2 * get_addrs_msg.max - addrs.len() as u32;
  157. addrs.append(&mut self.hosts.container.fetch_n_random_excluding_schemes(
  158. HostColor::Gold,
  159. &requested_transports,
  160. remain,
  161. ));
  162. // Then we grab address without the requested transports from the white list
  163. debug!(target: "net::protocol_address::handle_receive_get_addrs()",
  164. "Fetching white entries without schemes");
  165. let remain = 2 * get_addrs_msg.max - addrs.len() as u32;
  166. addrs.append(&mut self.hosts.container.fetch_n_random_excluding_schemes(
  167. HostColor::White,
  168. &requested_transports,
  169. remain,
  170. ));
  171. // If there's still space available, take from the Dark list.
  172. /* NOTE: We share peers from our Dark list because to ensure
  173. that non-compatiable transports are shared with other nodes
  174. so that they propagate on the network even if they're not
  175. popular transports. */
  176. debug!(target: "net::protocol_address::handle_receive_get_addrs()",
  177. "Fetching dark entries");
  178. let remain = 2 * get_addrs_msg.max - addrs.len() as u32;
  179. addrs.append(&mut self.hosts.container.fetch_n_random(HostColor::Dark, remain));
  180. // Filter out transports not meant to be shared like Socks5 and Socks5+tls
  181. addrs.retain(|addr| TRANSPORT_COMBOS.contains(&addr.0.scheme()));
  182. debug!(
  183. target: "net::protocol_address::handle_receive_get_addrs()",
  184. "Sending {} addresses to {}", addrs.len(), self.channel.display_address(),
  185. );
  186. let addrs_msg = AddrsMessage { addrs };
  187. self.channel.send(&addrs_msg).await?;
  188. }
  189. }
  190. /// Send our own external addresses over a channel. Set the
  191. /// last_seen field to now.
  192. async fn send_my_addrs(self: Arc<Self>) -> Result<()> {
  193. debug!(
  194. target: "net::protocol_address::send_my_addrs",
  195. "[START] channel address={}", self.channel.display_address(),
  196. );
  197. if self.channel.session_type_id() != SESSION_OUTBOUND {
  198. debug!(
  199. target: "net::protocol_address::send_my_addrs",
  200. "Not an outbound session. Stopping",
  201. );
  202. return Ok(())
  203. }
  204. let external_addrs = self.channel.hosts().external_addrs().await;
  205. if external_addrs.is_empty() {
  206. debug!(
  207. target: "net::protocol_address::send_my_addrs",
  208. "External addr not configured. Stopping",
  209. );
  210. return Ok(())
  211. }
  212. let mut addrs = vec![];
  213. for addr in external_addrs {
  214. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  215. addrs.push((addr, last_seen));
  216. }
  217. debug!(
  218. target: "net::protocol_address::send_my_addrs",
  219. "Broadcasting {} addresses", addrs.len(),
  220. );
  221. let ext_addr_msg = AddrsMessage { addrs };
  222. self.channel.send(&ext_addr_msg).await?;
  223. debug!(
  224. target: "net::protocol_address::send_my_addrs",
  225. "[END] channel address={}", self.channel.display_address(),
  226. );
  227. Ok(())
  228. }
  229. }
  230. #[async_trait]
  231. impl ProtocolBase for ProtocolAddress {
  232. /// Start the address protocol. If it's an outbound session and has an
  233. /// external address, send our external address. Run receive address
  234. /// and get address protocols on the protocol task manager. Then send
  235. /// get-address msg.
  236. async fn start(self: Arc<Self>, ex: Arc<Executor<'_>>) -> Result<()> {
  237. debug!(
  238. target: "net::protocol_address::start()",
  239. "START => address={}", self.channel.display_address(),
  240. );
  241. let settings = self.settings.read().await;
  242. let outbound_connections = settings.outbound_connections;
  243. let getaddrs_max = settings.getaddrs_max;
  244. let allowed_transports = settings.allowed_transports.clone();
  245. drop(settings);
  246. self.jobsman.clone().start(ex.clone());
  247. self.jobsman.clone().spawn(self.clone().send_my_addrs(), ex.clone()).await;
  248. self.jobsman.clone().spawn(self.clone().handle_receive_addrs(), ex.clone()).await;
  249. self.jobsman.spawn(self.clone().handle_receive_get_addrs(), ex).await;
  250. // Send get_address message.
  251. // We ask for a maximum of u8::MAX addresses from a single node
  252. let get_addrs = GetAddrsMessage {
  253. max: getaddrs_max.unwrap_or(outbound_connections.min(u32::MAX as usize) as u32),
  254. transports: allowed_transports,
  255. };
  256. self.channel.send(&get_addrs).await?;
  257. debug!(
  258. target: "net::protocol_address::start()",
  259. "END => address={}", self.channel.display_address(),
  260. );
  261. Ok(())
  262. }
  263. fn name(&self) -> &'static str {
  264. PROTO_NAME
  265. }
  266. }
  267. #[cfg(test)]
  268. mod tests {
  269. use darkfi_serial::serialize;
  270. use crate::net::message::GET_ADDRS_MAX_BYTES;
  271. use super::{GetAddrsMessage, TRANSPORT_COMBOS};
  272. // Helps to check if the MAX_BYTES for GetAddrs message is valid as new transports are added
  273. #[test]
  274. fn test_get_addrs_msg_size() {
  275. let message = GetAddrsMessage {
  276. max: u8::MAX as u32,
  277. transports: TRANSPORT_COMBOS.iter().map(|x| x.to_string()).collect(),
  278. };
  279. assert_eq!(serialize(&message).len() as u64, GET_ADDRS_MAX_BYTES);
  280. }
  281. }