protocol_address.rs 12 KB

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