protocol_address.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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;
  19. use async_trait::async_trait;
  20. use log::{debug, warn};
  21. use smol::Executor;
  22. use super::{
  23. super::{
  24. channel::ChannelPtr,
  25. hosts::store::{HostColor, HostsPtr},
  26. message::{AddrsMessage, GetAddrsMessage},
  27. message_subscriber::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::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, so we
  44. /// 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. p2p: P2pPtr,
  64. }
  65. const PROTO_NAME: &str = "ProtocolAddress";
  66. impl ProtocolAddress {
  67. /// Creates a new address protocol. Makes an address, an external address
  68. /// and a get-address subscription and adds them to the address protocol
  69. /// instance.
  70. pub async fn init(channel: ChannelPtr, p2p: P2pPtr) -> ProtocolBasePtr {
  71. let settings = p2p.settings();
  72. let hosts = p2p.hosts();
  73. // Creates a subscription to address message
  74. let addrs_sub =
  75. channel.subscribe_msg::<AddrsMessage>().await.expect("Missing addrs dispatcher!");
  76. // Creates a subscription to get-address message
  77. let get_addrs_sub =
  78. channel.subscribe_msg::<GetAddrsMessage>().await.expect("Missing getaddrs dispatcher!");
  79. Arc::new(Self {
  80. channel: channel.clone(),
  81. addrs_sub,
  82. get_addrs_sub,
  83. hosts,
  84. jobsman: ProtocolJobsManager::new(PROTO_NAME, channel),
  85. settings,
  86. p2p,
  87. })
  88. }
  89. /// Handles receiving the address message. Loops to continually receive
  90. /// address messages on the address subscription. Validates and adds the
  91. /// received addresses to the greylist.
  92. async fn handle_receive_addrs(self: Arc<Self>) -> Result<()> {
  93. debug!(
  94. target: "net::protocol_address::handle_receive_addrs()",
  95. "[START] address={}", self.channel.address(),
  96. );
  97. loop {
  98. let addrs_msg = self.addrs_sub.receive().await?;
  99. debug!(
  100. target: "net::protocol_address::handle_receive_addrs()",
  101. "Received {} addrs from {}", addrs_msg.addrs.len(), self.channel.address(),
  102. );
  103. debug!(
  104. target: "net::protocol_address::handle_receive_addrs()",
  105. "Appending to greylist...",
  106. );
  107. self.hosts.insert(HostColor::Grey, &addrs_msg.addrs).await;
  108. }
  109. }
  110. /// Handles receiving the get-address message. Continually receives
  111. /// get-address messages on the get-address subscription. Then replies
  112. /// with an address message.
  113. async fn handle_receive_get_addrs(self: Arc<Self>) -> Result<()> {
  114. debug!(
  115. target: "net::protocol_address::handle_receive_get_addrs()",
  116. "[START] address={}", self.channel.address(),
  117. );
  118. loop {
  119. let get_addrs_msg = self.get_addrs_sub.receive().await?;
  120. debug!(
  121. target: "net::protocol_address::handle_receive_get_addrs()",
  122. "Received GetAddrs({}) message from {}", get_addrs_msg.max, self.channel.address(),
  123. );
  124. // Validate transports length
  125. // TODO: Verify this limit. It should be the max number of all our allowed transports,
  126. // plus their mixing.
  127. if get_addrs_msg.transports.len() > 20 {
  128. warn!(target: "net::protocol_address::handle_receive_get_addrs()",
  129. "Sending empty Addrs message");
  130. // TODO: Should this error out, effectively ending the connection?
  131. let addrs_msg = AddrsMessage { addrs: vec![] };
  132. self.channel.send(&addrs_msg).await?;
  133. continue
  134. }
  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
  139. .hosts
  140. .container
  141. .fetch_n_random_with_schemes(
  142. HostColor::Gold,
  143. &get_addrs_msg.transports,
  144. get_addrs_msg.max,
  145. )
  146. .await;
  147. // Then we grab address with the requested transports from the whitelist
  148. debug!(target: "net::protocol_address::handle_receive_get_addrs()",
  149. "Fetching whitelist entries with schemes");
  150. addrs.append(
  151. &mut self
  152. .hosts
  153. .container
  154. .fetch_n_random_with_schemes(
  155. HostColor::White,
  156. &get_addrs_msg.transports,
  157. get_addrs_msg.max,
  158. )
  159. .await,
  160. );
  161. // Next we grab addresses without the requested transports
  162. // to fill a 2 * max length vector.
  163. // Then we grab address without the requested transports from the gold list
  164. debug!(target: "net::protocol_address::handle_receive_get_addrs()",
  165. "Fetching gold entries without schemes");
  166. let remain = 2 * get_addrs_msg.max - addrs.len() as u32;
  167. addrs.append(
  168. &mut self
  169. .hosts
  170. .container
  171. .fetch_n_random_excluding_schemes(
  172. HostColor::Gold,
  173. &get_addrs_msg.transports,
  174. remain,
  175. )
  176. .await,
  177. );
  178. // Then we grab address without the requested transports from the white list
  179. debug!(target: "net::protocol_address::handle_receive_get_addrs()",
  180. "Fetching white entries without schemes");
  181. let remain = 2 * get_addrs_msg.max - addrs.len() as u32;
  182. addrs.append(
  183. &mut self
  184. .hosts
  185. .container
  186. .fetch_n_random_excluding_schemes(
  187. HostColor::White,
  188. &get_addrs_msg.transports,
  189. remain,
  190. )
  191. .await,
  192. );
  193. // If there's still space available, take from the Dark list.
  194. /* NOTE: We share peers from our Dark list because to ensure
  195. that non-compatiable transports are shared with other nodes
  196. so that they propagate on the network even if they're not
  197. popular transports. */
  198. debug!(target: "net::protocol_address::handle_receive_get_addrs()",
  199. "Fetching dark entries");
  200. let remain = 2 * get_addrs_msg.max - addrs.len() as u32;
  201. addrs.append(&mut self.hosts.container.fetch_n_random(HostColor::Dark, remain).await);
  202. debug!(
  203. target: "net::protocol_address::handle_receive_get_addrs()",
  204. "Sending {} addresses to {}", addrs.len(), self.channel.address(),
  205. );
  206. let addrs_msg = AddrsMessage { addrs };
  207. self.channel.send(&addrs_msg).await?;
  208. }
  209. }
  210. /// Send our own external addresses over a channel. Get the latest
  211. /// last_seen field from InboundSession, and send it along with our
  212. /// external address.
  213. ///
  214. /// If our external address is misconfigured, send an empty vector.
  215. /// If we have reached our inbound connection limit, send our external
  216. /// address with a `last_seen` field that corresponds to the last time
  217. /// we could receive inbound connections.
  218. async fn send_my_addrs(self: Arc<Self>) -> Result<()> {
  219. debug!(
  220. target: "net::protocol_address::send_my_addrs()",
  221. "[START] channel address={}", self.channel.address(),
  222. );
  223. let type_id = self.channel.session_type_id();
  224. if type_id != SESSION_OUTBOUND {
  225. debug!(target: "net::protocol_address::send_my_addrs()",
  226. "Not an outbound session. Stopping");
  227. return Ok(())
  228. }
  229. if self.settings.external_addrs.is_empty() {
  230. debug!(target: "net::protocol_address::send_my_addrs()",
  231. "External addr not configured. Stopping");
  232. return Ok(())
  233. }
  234. let mut addrs = vec![];
  235. let inbound = self.p2p.session_inbound();
  236. for (addr, last_seen) in inbound.ping_self.addrs.lock().await.iter() {
  237. addrs.push((addr.clone(), *last_seen));
  238. }
  239. debug!(target: "net::protocol_address::send_my_addrs()",
  240. "Broadcasting {} addresses", addrs.len());
  241. let ext_addr_msg = AddrsMessage { addrs };
  242. self.channel.send(&ext_addr_msg).await?;
  243. debug!(target: "net::protocol_address::send_my_addrs()",
  244. "[END] channel address={}", self.channel.address());
  245. Ok(())
  246. }
  247. }
  248. #[async_trait]
  249. impl ProtocolBase for ProtocolAddress {
  250. /// Start the address protocol. If it's an outbound session and has an
  251. /// external address, send our external address. Run receive address
  252. /// and get address protocols on the protocol task manager. Then send
  253. /// get-address msg.
  254. async fn start(self: Arc<Self>, ex: Arc<Executor<'_>>) -> Result<()> {
  255. debug!(target: "net::protocol_address::start()",
  256. "START => address={}", self.channel.address());
  257. self.jobsman.clone().start(ex.clone());
  258. self.jobsman.clone().spawn(self.clone().send_my_addrs(), ex.clone()).await;
  259. self.jobsman.clone().spawn(self.clone().handle_receive_addrs(), ex.clone()).await;
  260. self.jobsman.spawn(self.clone().handle_receive_get_addrs(), ex).await;
  261. // Send get_address message.
  262. let get_addrs = GetAddrsMessage {
  263. max: self.settings.outbound_connections as u32,
  264. transports: self.settings.allowed_transports.clone(),
  265. };
  266. self.channel.send(&get_addrs).await?;
  267. debug!(target: "net::protocol_address::start()",
  268. "END => address={}", self.channel.address());
  269. Ok(())
  270. }
  271. fn name(&self) -> &'static str {
  272. PROTO_NAME
  273. }
  274. }