protocol_address.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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::{lock::RwLock as AsyncRwLock, 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::Settings,
  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: Arc<AsyncRwLock<Settings>>,
  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. // Creates a subscription to address message
  76. let addrs_sub =
  77. channel.subscribe_msg::<AddrsMessage>().await.expect("Missing addrs dispatcher!");
  78. // Creates a subscription to get-address message
  79. let get_addrs_sub =
  80. channel.subscribe_msg::<GetAddrsMessage>().await.expect("Missing getaddrs dispatcher!");
  81. Arc::new(Self {
  82. channel: channel.clone(),
  83. addrs_sub,
  84. get_addrs_sub,
  85. hosts: p2p.hosts(),
  86. jobsman: ProtocolJobsManager::new(PROTO_NAME, channel),
  87. settings: p2p.settings(),
  88. })
  89. }
  90. /// Handles receiving the address message. Loops to continually receive
  91. /// address messages on the address subscription. Validates and adds the
  92. /// received addresses to the greylist.
  93. async fn handle_receive_addrs(self: Arc<Self>) -> Result<()> {
  94. debug!(
  95. target: "net::protocol_address::handle_receive_addrs()",
  96. "[START] address={}", self.channel.address(),
  97. );
  98. loop {
  99. let addrs_msg = self.addrs_sub.receive().await?;
  100. debug!(
  101. target: "net::protocol_address::handle_receive_addrs()",
  102. "Received {} addrs from {}", addrs_msg.addrs.len(), self.channel.address(),
  103. );
  104. debug!(
  105. target: "net::protocol_address::handle_receive_addrs()",
  106. "Appending to greylist...",
  107. );
  108. self.hosts.insert(HostColor::Grey, &addrs_msg.addrs).await;
  109. }
  110. }
  111. /// Handles receiving the get-address message. Continually receives
  112. /// get-address messages on the get-address subscription. Then replies
  113. /// with an address message.
  114. async fn handle_receive_get_addrs(self: Arc<Self>) -> Result<()> {
  115. debug!(
  116. target: "net::protocol_address::handle_receive_get_addrs()",
  117. "[START] address={}", self.channel.address(),
  118. );
  119. loop {
  120. let get_addrs_msg = self.get_addrs_sub.receive().await?;
  121. debug!(
  122. target: "net::protocol_address::handle_receive_get_addrs()",
  123. "Received GetAddrs({}) message from {}", get_addrs_msg.max, self.channel.address(),
  124. );
  125. // Check that this peer isn't requesting more transports than we support
  126. // (the max number of all transports, plus mixing).
  127. if get_addrs_msg.transports.len() > TRANSPORT_COMBOS.len() {
  128. return Err(Error::InvalidTransportRequest);
  129. }
  130. // First we grab address with the requested transports from the gold list
  131. debug!(target: "net::protocol_address::handle_receive_get_addrs()",
  132. "Fetching gold entries with schemes");
  133. let mut addrs = self.hosts.container.fetch_n_random_with_schemes(
  134. HostColor::Gold,
  135. &get_addrs_msg.transports,
  136. get_addrs_msg.max,
  137. );
  138. // Then we grab address with the requested transports from the whitelist
  139. debug!(target: "net::protocol_address::handle_receive_get_addrs()",
  140. "Fetching whitelist entries with schemes");
  141. addrs.append(&mut self.hosts.container.fetch_n_random_with_schemes(
  142. HostColor::White,
  143. &get_addrs_msg.transports,
  144. get_addrs_msg.max,
  145. ));
  146. // Next we grab addresses without the requested transports
  147. // to fill a 2 * max length vector.
  148. // Then we grab address without the requested transports from the gold list
  149. debug!(target: "net::protocol_address::handle_receive_get_addrs()",
  150. "Fetching gold entries without schemes");
  151. let remain = 2 * get_addrs_msg.max - addrs.len() as u32;
  152. addrs.append(&mut self.hosts.container.fetch_n_random_excluding_schemes(
  153. HostColor::Gold,
  154. &get_addrs_msg.transports,
  155. remain,
  156. ));
  157. // Then we grab address without the requested transports from the white list
  158. debug!(target: "net::protocol_address::handle_receive_get_addrs()",
  159. "Fetching white entries without schemes");
  160. let remain = 2 * get_addrs_msg.max - addrs.len() as u32;
  161. addrs.append(&mut self.hosts.container.fetch_n_random_excluding_schemes(
  162. HostColor::White,
  163. &get_addrs_msg.transports,
  164. remain,
  165. ));
  166. // If there's still space available, take from the Dark list.
  167. /* NOTE: We share peers from our Dark list because to ensure
  168. that non-compatiable transports are shared with other nodes
  169. so that they propagate on the network even if they're not
  170. popular transports. */
  171. debug!(target: "net::protocol_address::handle_receive_get_addrs()",
  172. "Fetching dark entries");
  173. let remain = 2 * get_addrs_msg.max - addrs.len() as u32;
  174. addrs.append(&mut self.hosts.container.fetch_n_random(HostColor::Dark, remain));
  175. debug!(
  176. target: "net::protocol_address::handle_receive_get_addrs()",
  177. "Sending {} addresses to {}", addrs.len(), self.channel.address(),
  178. );
  179. let addrs_msg = AddrsMessage { addrs };
  180. self.channel.send(&addrs_msg).await?;
  181. }
  182. }
  183. /// Send our own external addresses over a channel. Set the
  184. /// last_seen field to now.
  185. async fn send_my_addrs(self: Arc<Self>) -> Result<()> {
  186. debug!(
  187. target: "net::protocol_address::send_my_addrs",
  188. "[START] channel address={}", self.channel.address(),
  189. );
  190. let type_id = self.channel.session_type_id();
  191. if type_id != SESSION_OUTBOUND {
  192. debug!(
  193. target: "net::protocol_address::send_my_addrs",
  194. "Not an outbound session. Stopping",
  195. );
  196. return Ok(())
  197. }
  198. let external_addrs = self.settings.read().await.external_addrs.clone();
  199. if external_addrs.is_empty() {
  200. debug!(
  201. target: "net::protocol_address::send_my_addrs",
  202. "External addr not configured. Stopping",
  203. );
  204. return Ok(())
  205. }
  206. let mut addrs = vec![];
  207. for addr in external_addrs {
  208. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  209. addrs.push((addr, last_seen));
  210. }
  211. debug!(
  212. target: "net::protocol_address::send_my_addrs",
  213. "Broadcasting {} addresses", addrs.len(),
  214. );
  215. let ext_addr_msg = AddrsMessage { addrs };
  216. self.channel.send(&ext_addr_msg).await?;
  217. debug!(
  218. target: "net::protocol_address::send_my_addrs",
  219. "[END] channel address={}", self.channel.address(),
  220. );
  221. Ok(())
  222. }
  223. }
  224. #[async_trait]
  225. impl ProtocolBase for ProtocolAddress {
  226. /// Start the address protocol. If it's an outbound session and has an
  227. /// external address, send our external address. Run receive address
  228. /// and get address protocols on the protocol task manager. Then send
  229. /// get-address msg.
  230. async fn start(self: Arc<Self>, ex: Arc<Executor<'_>>) -> Result<()> {
  231. debug!(
  232. target: "net::protocol_address::start()",
  233. "START => address={}", self.channel.address(),
  234. );
  235. let settings = self.settings.read().await;
  236. let outbound_connections = settings.outbound_connections;
  237. let allowed_transports = settings.allowed_transports.clone();
  238. drop(settings);
  239. self.jobsman.clone().start(ex.clone());
  240. self.jobsman.clone().spawn(self.clone().send_my_addrs(), ex.clone()).await;
  241. self.jobsman.clone().spawn(self.clone().handle_receive_addrs(), ex.clone()).await;
  242. self.jobsman.spawn(self.clone().handle_receive_get_addrs(), ex).await;
  243. // Send get_address message.
  244. let get_addrs =
  245. GetAddrsMessage { max: outbound_connections as u32, transports: allowed_transports };
  246. self.channel.send(&get_addrs).await?;
  247. debug!(
  248. target: "net::protocol_address::start()",
  249. "END => address={}", self.channel.address(),
  250. );
  251. Ok(())
  252. }
  253. fn name(&self) -> &'static str {
  254. PROTO_NAME
  255. }
  256. }