store.rs 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555
  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::{
  19. collections::{HashMap, HashSet},
  20. fs,
  21. fs::File,
  22. sync::Arc,
  23. time::UNIX_EPOCH,
  24. };
  25. use log::{debug, error, info, trace, warn};
  26. use rand::{prelude::IteratorRandom, rngs::OsRng, Rng};
  27. use smol::lock::RwLock;
  28. use url::Url;
  29. use super::super::{p2p::P2pPtr, settings::SettingsPtr};
  30. use crate::{
  31. system::{Subscriber, SubscriberPtr, Subscription},
  32. util::{
  33. file::{load_file, save_file},
  34. path::expand_path,
  35. },
  36. Result,
  37. };
  38. /// Atomic pointer to hosts object
  39. pub type HostsPtr = Arc<Hosts>;
  40. // An array containing all possible local host strings
  41. // TODO: This could perhaps be more exhaustive?
  42. pub const LOCAL_HOST_STRS: [&str; 2] = ["localhost", "localhost.localdomain"];
  43. const WHITELIST_MAX_LEN: usize = 5000;
  44. const GREYLIST_MAX_LEN: usize = 2000;
  45. /// Manages a store of network addresses
  46. // TODO: Test the performance overhead of using vectors for white/grey/anchor lists.
  47. // TODO: Check whether anchorlist has a max size in Monero.
  48. // TODO: we can probably clean up a lot of the repetitive code in this module.
  49. pub struct Hosts {
  50. /// Intermediary node list that is periodically probed and updated to whitelist.
  51. pub greylist: RwLock<Vec<(Url, u64)>>,
  52. /// Recently seen hosts. Shared with other nodes.
  53. pub whitelist: RwLock<Vec<(Url, u64)>>,
  54. /// Nodes to which we have already been able to establish a connection.
  55. pub anchorlist: RwLock<Vec<(Url, u64)>>,
  56. /// Peers we reject from connecting to
  57. rejected: RwLock<HashSet<String>>,
  58. /// Peers that are currently being removed from the hostlist
  59. migrating: RwLock<HashSet<Url>>,
  60. /// Subscriber listening for store updates
  61. store_subscriber: SubscriberPtr<usize>,
  62. /// Pointer to configured P2P settings
  63. settings: SettingsPtr,
  64. }
  65. impl Hosts {
  66. /// Create a new hosts list>
  67. pub fn new(settings: SettingsPtr) -> HostsPtr {
  68. Arc::new(Self {
  69. greylist: RwLock::new(Vec::new()),
  70. whitelist: RwLock::new(Vec::new()),
  71. anchorlist: RwLock::new(Vec::new()),
  72. rejected: RwLock::new(HashSet::new()),
  73. migrating: RwLock::new(HashSet::new()),
  74. store_subscriber: Subscriber::new(),
  75. settings,
  76. })
  77. }
  78. /// Loops through greylist addresses to find an outbound address that we can
  79. /// connect to. Check whether the address is valid by making sure it isn't
  80. /// our own inbound address, then checks whether it is already connected
  81. /// (exists) or connecting (pending).
  82. /// Lastly adds matching address to the pending list.
  83. pub async fn greylist_fetch_address(&self, transports: &[String]) -> Vec<(Url, u64)> {
  84. trace!(target: "store", "greylist_fetch_address() [START]");
  85. // Collect hosts
  86. let mut hosts = vec![];
  87. // If transport mixing is enabled, then for example we're allowed to
  88. // use tor:// to connect to tcp:// and tor+tls:// to connect to tcp+tls://.
  89. // However, **do not** mix tor:// and tcp+tls://, nor tor+tls:// and tcp://.
  90. let transport_mixing = self.settings.transport_mixing;
  91. macro_rules! mix_transport {
  92. ($a:expr, $b:expr) => {
  93. if transports.contains(&$a.to_string()) && transport_mixing {
  94. let mut a_to_b =
  95. self.greylist_fetch_with_schemes(&[$b.to_string()], None).await;
  96. for (addr, last_seen) in a_to_b.iter_mut() {
  97. addr.set_scheme($a).unwrap();
  98. hosts.push((addr.clone(), last_seen.clone()));
  99. }
  100. }
  101. };
  102. }
  103. mix_transport!("tor", "tcp");
  104. mix_transport!("tor+tls", "tcp+tls");
  105. mix_transport!("nym", "tcp");
  106. mix_transport!("nym+tls", "tcp+tls");
  107. // And now the actual requested transports
  108. for (addr, last_seen) in self.greylist_fetch_with_schemes(transports, None).await {
  109. hosts.push((addr, last_seen));
  110. }
  111. hosts
  112. }
  113. /// Loops through whitelist addresses to find an outbound address that we can
  114. /// connect to. Check whether the address is valid by making sure it isn't
  115. /// our own inbound address, then checks whether it is already connected
  116. /// (exists) or connecting (pending).
  117. /// Lastly adds matching address to the pending list.
  118. pub async fn whitelist_fetch_address(&self, transports: &[String]) -> Vec<(Url, u64)> {
  119. trace!(target: "store", "whitelist_fetch_address() [START]");
  120. // Collect hosts
  121. let mut hosts = vec![];
  122. // If transport mixing is enabled, then for example we're allowed to
  123. // use tor:// to connect to tcp:// and tor+tls:// to connect to tcp+tls://.
  124. // However, **do not** mix tor:// and tcp+tls://, nor tor+tls:// and tcp://.
  125. let transport_mixing = self.settings.transport_mixing;
  126. macro_rules! mix_transport {
  127. ($a:expr, $b:expr) => {
  128. if transports.contains(&$a.to_string()) && transport_mixing {
  129. let mut a_to_b =
  130. self.whitelist_fetch_with_schemes(&[$b.to_string()], None).await;
  131. for (addr, last_seen) in a_to_b.iter_mut() {
  132. addr.set_scheme($a).unwrap();
  133. hosts.push((addr.clone(), last_seen.clone()));
  134. }
  135. }
  136. };
  137. }
  138. mix_transport!("tor", "tcp");
  139. mix_transport!("tor+tls", "tcp+tls");
  140. mix_transport!("nym", "tcp");
  141. mix_transport!("nym+tls", "tcp+tls");
  142. // And now the actual requested transports
  143. for (addr, last_seen) in self.whitelist_fetch_with_schemes(transports, None).await {
  144. hosts.push((addr, last_seen));
  145. }
  146. trace!(target: "store::whitelist_fetch_address()",
  147. "Grabbed hosts, length: {}", hosts.len());
  148. hosts
  149. }
  150. /// Loops through anchorlist addresses to find an outbound address that we can
  151. /// connect to. Check whether the address is valid by making sure it isn't
  152. /// our own inbound address, then checks whether it is already connected
  153. /// (exists) or connecting (pending).
  154. /// Lastly adds matching address to the pending list.
  155. pub async fn anchorlist_fetch_address(&self, transports: &[String]) -> Vec<(Url, u64)> {
  156. trace!(target: "store", "anchorlist_fetch_address() [START]");
  157. // Collect hosts
  158. let mut hosts = vec![];
  159. // If transport mixing is enabled, then for example we're allowed to
  160. // use tor:// to connect to tcp:// and tor+tls:// to connect to tcp+tls://.
  161. // However, **do not** mix tor:// and tcp+tls://, nor tor+tls:// and tcp://.
  162. let transport_mixing = self.settings.transport_mixing;
  163. macro_rules! mix_transport {
  164. ($a:expr, $b:expr) => {
  165. if transports.contains(&$a.to_string()) && transport_mixing {
  166. let mut a_to_b =
  167. self.anchorlist_fetch_with_schemes(&[$b.to_string()], None).await;
  168. for (addr, last_seen) in a_to_b.iter_mut() {
  169. addr.set_scheme($a).unwrap();
  170. hosts.push((addr.clone(), last_seen.clone()));
  171. }
  172. }
  173. };
  174. }
  175. mix_transport!("tor", "tcp");
  176. mix_transport!("tor+tls", "tcp+tls");
  177. mix_transport!("nym", "tcp");
  178. mix_transport!("nym+tls", "tcp+tls");
  179. // And now the actual requested transports
  180. for (addr, last_seen) in self.anchorlist_fetch_with_schemes(transports, None).await {
  181. hosts.push((addr, last_seen));
  182. }
  183. trace!(target: "store::anchorlist_fetch_address()",
  184. "Grabbed hosts, length: {}", hosts.len());
  185. hosts
  186. }
  187. /// Check whether:
  188. /// * We already have this connection established
  189. /// * We already have this configured as a manual peer
  190. /// * This address is already pending a connection
  191. pub async fn check_address_with_lock(
  192. &self,
  193. p2p: P2pPtr,
  194. hosts: Vec<(Url, u64)>,
  195. ) -> Option<(Url, u64)> {
  196. // Try to find an unused host in the set.
  197. for (host, last_seen) in hosts {
  198. debug!(target: "store::check_address_with_lock()",
  199. "Starting checks");
  200. // Check if we already have this connection established
  201. if p2p.exists(&host).await {
  202. debug!(
  203. target: "store::check_address_with_lock()",
  204. "Host '{}' exists so skipping",
  205. host
  206. );
  207. continue
  208. }
  209. // Check if we already have this configured as a manual peer
  210. if self.settings.peers.contains(&host) {
  211. debug!(
  212. target: "store::check_address_with_lock()",
  213. "Host '{}' configured as manual peer so skipping",
  214. host
  215. );
  216. continue
  217. }
  218. // Obtain a lock on this address to prevent duplicate connection
  219. if !p2p.add_pending(&host).await {
  220. debug!(
  221. target: "store::check_address_with_lock()",
  222. "Host '{}' pending so skipping",
  223. host
  224. );
  225. continue
  226. }
  227. debug!(
  228. target: "store::check_address_with_lock()",
  229. "Found valid host {}",
  230. host
  231. );
  232. return Some((host.clone(), last_seen))
  233. }
  234. None
  235. }
  236. /// Upgrade a connection to the anchorlist. Called after a connection has been successfully
  237. /// established in Outbound and Manual sessions.
  238. pub async fn upgrade_host(&self, addr: &Url) {
  239. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  240. self.anchorlist_store_or_update(&[(addr.clone(), last_seen)]).await;
  241. }
  242. /// Remove an entry from the hostlist. Called when we cannot establish a connection to a host or
  243. /// when a pre-existing connection disconnects.
  244. pub async fn remove_host(&self, addr: &Url) {
  245. debug!(target: "store::remove_host", "Removing host {}", addr);
  246. self.mark_migrating(addr).await;
  247. // Remove channel from anchorlist
  248. if self.anchorlist_contains(addr).await {
  249. debug!(target: "store::remove_host", "Removing from anchorlist {}", addr);
  250. let index = self
  251. .get_anchorlist_index_at_addr(addr.clone())
  252. .await
  253. .expect("Expected anchorlist index to exist");
  254. self.anchorlist_remove(addr, index).await;
  255. }
  256. // Remove channel from whitelist
  257. if self.whitelist_contains(addr).await {
  258. debug!(target: "store::remove_host", "Removing from whitelist {}", addr);
  259. let index = self
  260. .get_whitelist_index_at_addr(addr.clone())
  261. .await
  262. .expect("Expected whitelist index to exist");
  263. self.whitelist_remove(addr, index).await;
  264. }
  265. // Remove channel the greylist
  266. if self.greylist_contains(addr).await {
  267. debug!(target: "store::remove_host", "Removing from greylist {}", addr);
  268. let index = self
  269. .get_greylist_index_at_addr(addr.clone())
  270. .await
  271. .expect("Expected greylist index to exist");
  272. self.greylist_remove(addr, index).await;
  273. }
  274. self.unmark_migrating(addr).await;
  275. }
  276. /// Stores an address on the greylist or updates its last_seen field if we already
  277. /// have the address.
  278. pub async fn greylist_store_or_update(&self, addrs: &[(Url, u64)]) {
  279. trace!(target: "store::greylist_store_or_update()", "[START]");
  280. // Filter addresses before writing to the greylist.
  281. let filtered_addrs = self.filter_addresses(addrs).await;
  282. let filtered_addrs_len = filtered_addrs.len();
  283. if filtered_addrs.is_empty() {
  284. debug!(target: "store::greylist_store_or_update()", "Filtered out all received addresses");
  285. }
  286. for (addr, last_seen) in filtered_addrs {
  287. if !self.greylist_contains(&addr).await {
  288. debug!(target: "store::greylist_store_or_update()",
  289. "We do not have this entry in the hostlist. Adding to store...");
  290. self.greylist_store(addr.clone(), last_seen).await;
  291. } else {
  292. debug!(target: "store::greylist_store_or_update()",
  293. "We have this entry in the greylist. Updating last seen...");
  294. let index = self
  295. .get_greylist_index_at_addr(addr.clone())
  296. .await
  297. .expect("Expected greylist entry to exist");
  298. self.greylist_update_last_seen(&addr, last_seen, index).await;
  299. self.store_subscriber.notify(filtered_addrs_len).await;
  300. }
  301. }
  302. }
  303. /// Stores an address on the whitelist or updates its last_seen field if we already
  304. /// have the address.
  305. pub async fn whitelist_store_or_update(&self, addrs: &[(Url, u64)]) {
  306. trace!(target: "store::whitelist_store_or_update()", "[START]");
  307. // No address filtering for whitelist (whitelist is created from greylist)
  308. for (addr, last_seen) in addrs {
  309. if !self.whitelist_contains(addr).await {
  310. debug!(target: "store::whitelist_store_or_update()",
  311. "We do not have this entry in the whitelist. Adding to store...");
  312. self.whitelist_store(addr.clone(), *last_seen).await;
  313. } else {
  314. debug!(target: "store::whitelist_store_or_update()",
  315. "We have this entry in the whitelist. Updating last seen...");
  316. let index = self
  317. .get_whitelist_index_at_addr(addr.clone())
  318. .await
  319. .expect("Expected whitelist entry to exist");
  320. self.whitelist_update_last_seen(addr, *last_seen, index).await;
  321. }
  322. }
  323. }
  324. /// Stores an address on the anchorlist or updates its last_seen field if we already
  325. /// have the address.
  326. pub async fn anchorlist_store_or_update(&self, addrs: &[(Url, u64)]) {
  327. trace!(target: "store::anchor_store_or_update()", "[START]");
  328. // No address filtering for anchorlist (contains addresses we have already connected to)
  329. for (addr, last_seen) in addrs {
  330. if !self.anchorlist_contains(addr).await {
  331. debug!(target: "store::anchorlist_store_or_update()",
  332. "We do not have this entry in the whitelist. Adding to store...");
  333. self.anchorlist_store(addr.clone(), *last_seen).await;
  334. } else {
  335. debug!(target: "store::anchorlist_store_or_update()",
  336. "We have this entry in the anchorlist. Updating last seen...");
  337. let index = self
  338. .get_anchorlist_index_at_addr(addr.clone())
  339. .await
  340. .expect("Expected anchorlist entry to exist");
  341. self.anchorlist_update_last_seen(addr, *last_seen, index).await;
  342. }
  343. }
  344. }
  345. /// Append host to the greylist. Called on learning of a new peer.
  346. pub async fn greylist_store(&self, addr: Url, last_seen: u64) {
  347. trace!(target: "store::greylist_store()", "hosts::greylist_store() [START]");
  348. let mut greylist = self.greylist.write().await;
  349. // Remove oldest element if the greylist reaches max size.
  350. if greylist.len() == GREYLIST_MAX_LEN {
  351. let last_entry = greylist.pop().unwrap();
  352. debug!(target: "store::greylist_store()", "Greylist reached max size. Removed {:?}", last_entry);
  353. }
  354. debug!(target: "store::greylist_store()", "Inserting {}", addr);
  355. greylist.push((addr, last_seen));
  356. // Sort the list by last_seen.
  357. greylist.sort_by_key(|entry| entry.1);
  358. greylist.reverse();
  359. trace!(target: "store::greylist_store()", "[END]");
  360. }
  361. /// Append host to the whitelist. Called after a successful interaction with an online peer.
  362. pub async fn whitelist_store(&self, addr: Url, last_seen: u64) {
  363. trace!(target: "store::whitelist_store()", "[START]");
  364. let mut whitelist = self.whitelist.write().await;
  365. // Remove oldest element if the whitelist reaches max size.
  366. if whitelist.len() == WHITELIST_MAX_LEN {
  367. let last_entry = whitelist.pop().unwrap();
  368. debug!(target: "store::whitelist_store()", "Whitelist reached max size. Removed {:?}", last_entry);
  369. }
  370. trace!(target: "store::whitelist_store()", "Inserting {}. Last seen {:?}", addr, last_seen);
  371. whitelist.push((addr, last_seen));
  372. // Sort the list by last_seen.
  373. whitelist.sort_by_key(|entry| entry.1);
  374. whitelist.reverse();
  375. trace!(target: "store::whitelist_store()", "[END]");
  376. }
  377. /// Append host to the anchorlist. Called after we have successfully established a connection
  378. /// to a peer.
  379. pub async fn anchorlist_store(&self, addr: Url, last_seen: u64) {
  380. trace!(target: "store::anchorlist_store()", "[START]");
  381. let mut anchorlist = self.anchorlist.write().await;
  382. trace!(target: "store::anchorlist_store()", "Inserting {}", addr);
  383. anchorlist.push((addr, last_seen));
  384. // Sort the list by last_seen.
  385. anchorlist.sort_by_key(|entry| entry.1);
  386. anchorlist.reverse();
  387. trace!(target: "store::anchorlist_store()", "[END]");
  388. }
  389. /// Update the last_seen field of a peer on the greylist.
  390. pub async fn greylist_update_last_seen(&self, addr: &Url, last_seen: u64, index: usize) {
  391. trace!(target: "store::greylist_update_last_seen()", "[START]");
  392. let mut greylist = self.greylist.write().await;
  393. greylist[index] = (addr.clone(), last_seen);
  394. // Sort the list by last_seen.
  395. greylist.sort_by_key(|entry| entry.1);
  396. greylist.reverse();
  397. trace!(target: "store::greylist_update_last_seen()", "[END]");
  398. }
  399. /// Update the last_seen field of a peer on the whitelist.
  400. pub async fn whitelist_update_last_seen(&self, addr: &Url, last_seen: u64, index: usize) {
  401. trace!(target: "store::whitelist_update_last_seen()", "[START]");
  402. let mut whitelist = self.whitelist.write().await;
  403. whitelist[index] = (addr.clone(), last_seen);
  404. // Sort the list by last_seen.
  405. whitelist.sort_by_key(|entry| entry.1);
  406. whitelist.reverse();
  407. trace!(target: "store::whitelist_update_last_seen()", "[END]");
  408. }
  409. /// Update the last_seen field of a peer on the anchorlist.
  410. pub async fn anchorlist_update_last_seen(&self, addr: &Url, last_seen: u64, index: usize) {
  411. trace!(target: "store::anchorlist_update_last_seen()", "[START]");
  412. let mut anchorlist = self.anchorlist.write().await;
  413. anchorlist[index] = (addr.clone(), last_seen);
  414. // Sort the list by last_seen.
  415. anchorlist.sort_by_key(|entry| entry.1);
  416. anchorlist.reverse();
  417. trace!(target: "store::anchorlist_update_last_seen()", "[END]");
  418. }
  419. /// Remove an entry from the greylist.
  420. pub async fn greylist_remove(&self, addr: &Url, index: usize) {
  421. debug!(target: "store::greylist_remove", "Removing peer {} from greylist", addr);
  422. self.greylist.write().await.remove(index);
  423. }
  424. /// Remove an entry from the whitelist.
  425. pub async fn whitelist_remove(&self, addr: &Url, index: usize) {
  426. debug!(target: "store::whitelist_remove", "Removing peer {} from whitelist", addr);
  427. self.whitelist.write().await.remove(index);
  428. }
  429. /// Remove an entry from the anchorlist.
  430. pub async fn anchorlist_remove(&self, addr: &Url, index: usize) {
  431. debug!(target: "store::anchorlist_remove", "Removing peer {} from anchorlist", addr);
  432. self.anchorlist.write().await.remove(index);
  433. }
  434. pub async fn subscribe_store(&self) -> Result<Subscription<usize>> {
  435. let sub = self.store_subscriber.clone().subscribe().await;
  436. Ok(sub)
  437. }
  438. // Verify whether a URL is local.
  439. // NOTE: This function is stateless and not specific to
  440. // `Hosts`. For this reason, it might make more sense
  441. // to move this function to a more appropriate location
  442. // in the codebase.
  443. /// Check whether a URL is local host
  444. pub async fn is_local_host(&self, url: Url) -> bool {
  445. // Reject Urls without host strings.
  446. if url.host_str().is_none() {
  447. return false
  448. }
  449. // We do this hack in order to parse IPs properly.
  450. // https://github.com/whatwg/url/issues/749
  451. let addr = Url::parse(&url.as_str().replace(url.scheme(), "http")).unwrap();
  452. // Filter private IP ranges
  453. match addr.host().unwrap() {
  454. url::Host::Ipv4(ip) => {
  455. if !ip.is_global() {
  456. return true
  457. }
  458. }
  459. url::Host::Ipv6(ip) => {
  460. if !ip.is_global() {
  461. return true
  462. }
  463. }
  464. url::Host::Domain(d) => {
  465. if LOCAL_HOST_STRS.contains(&d) {
  466. return true
  467. }
  468. }
  469. }
  470. false
  471. }
  472. /// Filter given addresses based on certain rulesets and validity.
  473. async fn filter_addresses(&self, addrs: &[(Url, u64)]) -> Vec<(Url, u64)> {
  474. trace!(target: "store::filter_addresses()", "Filtering addrs: {:?}", addrs);
  475. let mut ret = vec![];
  476. let localnet = self.settings.localnet;
  477. 'addr_loop: for (addr_, last_seen) in addrs {
  478. // Validate that the format is `scheme://host_str:port`
  479. if addr_.host_str().is_none() ||
  480. addr_.port().is_none() ||
  481. addr_.cannot_be_a_base() ||
  482. addr_.path_segments().is_some()
  483. {
  484. continue
  485. }
  486. if self.is_rejected(addr_).await {
  487. debug!(target: "store::filter_addresses()", "Peer {} is rejected", addr_);
  488. continue
  489. }
  490. let host_str = addr_.host_str().unwrap();
  491. if !localnet {
  492. // Our own external addresses should never enter the hosts set.
  493. for ext in &self.settings.external_addrs {
  494. if host_str == ext.host_str().unwrap() {
  495. continue 'addr_loop
  496. }
  497. }
  498. }
  499. // On localnet, make sure ours ports don't enter the host set.
  500. for ext in &self.settings.external_addrs {
  501. if addr_.port() == ext.port() {
  502. continue 'addr_loop
  503. }
  504. }
  505. // We do this hack in order to parse IPs properly.
  506. // https://github.com/whatwg/url/issues/749
  507. let addr = Url::parse(&addr_.as_str().replace(addr_.scheme(), "http")).unwrap();
  508. // Filter non-global ranges if we're not allowing localnet.
  509. // Should never be allowed in production, so we don't really care
  510. // about some of them (e.g. 0.0.0.0, or broadcast, etc.).
  511. if !localnet && self.is_local_host(addr).await {
  512. continue
  513. }
  514. match addr_.scheme() {
  515. // Validate that the address is an actual onion.
  516. #[cfg(feature = "p2p-tor")]
  517. "tor" | "tor+tls" => {
  518. use std::str::FromStr;
  519. if tor_hscrypto::pk::HsId::from_str(host_str).is_err() {
  520. continue
  521. }
  522. trace!(target: "store::filter_addresses()", "[Tor] Valid: {}", host_str);
  523. }
  524. #[cfg(feature = "p2p-nym")]
  525. "nym" | "nym+tls" => continue, // <-- Temp skip
  526. #[cfg(feature = "p2p-tcp")]
  527. "tcp" | "tcp+tls" => {
  528. trace!(target: "store::filter_addresses()", "[TCP] Valid: {}", host_str);
  529. }
  530. _ => continue,
  531. }
  532. ret.push((addr_.clone(), *last_seen));
  533. }
  534. ret
  535. }
  536. /// Check if a given peer (URL) is in the set of rejected hosts
  537. pub async fn is_rejected(&self, peer: &Url) -> bool {
  538. // Skip lookup for UNIX sockets and localhost connections
  539. // as they should never belong to the list of rejected URLs.
  540. let Some(hostname) = peer.host_str() else { return false };
  541. if self.is_local_host(peer.clone()).await {
  542. return false
  543. }
  544. self.rejected.read().await.contains(hostname)
  545. }
  546. /// Mark a peer as rejected by adding it to the set of rejected URLs.
  547. pub async fn mark_rejected(&self, peer: &Url) {
  548. // We ignore UNIX sockets here so we will just work
  549. // with stuff that has host_str().
  550. if let Some(hostname) = peer.host_str() {
  551. // Localhost connections should not be rejected
  552. // This however allows any Tor and Nym connections.
  553. if self.is_local_host(peer.clone()).await {
  554. return
  555. }
  556. self.rejected.write().await.insert(hostname.to_string());
  557. }
  558. }
  559. /// Unmark a rejected peer
  560. pub async fn unmark_rejected(&self, peer: &Url) {
  561. if let Some(hostname) = peer.host_str() {
  562. self.rejected.write().await.remove(hostname);
  563. }
  564. }
  565. /// Peer that is currently being removed from hostlists.
  566. pub async fn is_migrating(&self, peer: &Url) -> bool {
  567. self.migrating.read().await.contains(peer)
  568. }
  569. /// Mark a peer as currently migrating.
  570. pub async fn mark_migrating(&self, peer: &Url) {
  571. self.migrating.write().await.insert(peer.clone());
  572. }
  573. /// Unmark a migrating peer.
  574. pub async fn unmark_migrating(&self, peer: &Url) {
  575. self.migrating.write().await.remove(peer);
  576. }
  577. /// Check if the greylist is empty.
  578. pub async fn is_empty_greylist(&self) -> bool {
  579. self.greylist.read().await.is_empty()
  580. }
  581. /// Check if the whitelist is empty.
  582. pub async fn is_empty_whitelist(&self) -> bool {
  583. self.whitelist.read().await.is_empty()
  584. }
  585. /// Check if the anchorlist is empty.
  586. pub async fn is_empty_anchorlist(&self) -> bool {
  587. self.anchorlist.read().await.is_empty()
  588. }
  589. /// Check if the hostlist is empty.
  590. pub async fn is_empty_hostlist(&self) -> bool {
  591. self.is_empty_greylist().await &&
  592. self.is_empty_whitelist().await &&
  593. self.is_empty_anchorlist().await
  594. }
  595. /// Check if host is in the greylist
  596. pub async fn greylist_contains(&self, addr: &Url) -> bool {
  597. self.greylist.read().await.iter().any(|(u, _t)| u == addr)
  598. }
  599. /// Check if host is in the whitelist
  600. pub async fn whitelist_contains(&self, addr: &Url) -> bool {
  601. self.whitelist.read().await.iter().any(|(u, _t)| u == addr)
  602. }
  603. /// Check if host is in the anchorlist
  604. pub async fn anchorlist_contains(&self, addr: &Url) -> bool {
  605. self.anchorlist.read().await.iter().any(|(u, _t)| u == addr)
  606. }
  607. /// Get the index for a given addr on the greylist.
  608. pub async fn get_greylist_index_at_addr(&self, addr: Url) -> Option<usize> {
  609. self.greylist.read().await.iter().position(|a| a.0 == addr)
  610. }
  611. /// Get the index for a given addr on the whitelist.
  612. pub async fn get_whitelist_index_at_addr(&self, addr: Url) -> Option<usize> {
  613. self.whitelist.read().await.iter().position(|a| a.0 == addr)
  614. }
  615. /// Get the index for a given addr on the anchorlist.
  616. pub async fn get_anchorlist_index_at_addr(&self, addr: Url) -> Option<usize> {
  617. self.anchorlist.read().await.iter().position(|a| a.0 == addr)
  618. }
  619. /// Get the entry for a given addr on the whitelist.
  620. pub async fn get_whitelist_entry_at_addr(&self, addr: &Url) -> Option<(Url, u64)> {
  621. self.whitelist
  622. .read()
  623. .await
  624. .iter()
  625. .find(|(url, _)| url == addr)
  626. .map(|(url, time)| (url.clone(), *time))
  627. }
  628. /// Get the entry for a given addr on the anchorlist.
  629. pub async fn get_anchorlist_entry_at_addr(&self, addr: &Url) -> Option<(Url, u64)> {
  630. self.anchorlist
  631. .read()
  632. .await
  633. .iter()
  634. .find(|(url, _)| url == addr)
  635. .map(|(url, time)| (url.clone(), *time))
  636. }
  637. /// Return all known whitelisted hosts
  638. pub async fn whitelist_fetch_all(&self) -> Vec<(Url, u64)> {
  639. self.whitelist.read().await.iter().cloned().collect()
  640. }
  641. /// Return all greylist and anchorlist hosts. Called on stop().
  642. /// Note: we do not return whitelist entries here since whitelist entries must go via the
  643. /// greylist refinery in the lifetime of the p2p network.
  644. pub async fn hostlist_fetch_safe(&self) -> HashMap<String, Vec<(Url, u64)>> {
  645. let mut hostlist = HashMap::new();
  646. hostlist.insert(
  647. "anchorlist".to_string(),
  648. self.anchorlist.read().await.iter().cloned().collect(),
  649. );
  650. hostlist
  651. .insert("greylist".to_string(), self.greylist.read().await.iter().cloned().collect());
  652. hostlist
  653. }
  654. /// Get up to n random peers from the whitelist.
  655. pub async fn whitelist_fetch_n_random(&self, n: u32) -> Vec<(Url, u64)> {
  656. let n = n as usize;
  657. if n == 0 {
  658. return vec![]
  659. }
  660. let addrs = self.whitelist.read().await;
  661. let urls = addrs.iter().choose_multiple(&mut OsRng, n.min(addrs.len()));
  662. urls.iter().map(|&url| url.clone()).collect()
  663. }
  664. /// Get a random peer from the greylist.
  665. pub async fn greylist_fetch_random(&self) -> ((Url, u64), usize) {
  666. let greylist = self.greylist.read().await;
  667. let position = rand::thread_rng().gen_range(0..greylist.len());
  668. let entry = &greylist[position];
  669. (entry.clone(), position)
  670. }
  671. /// Get a random peer from the whitelist.
  672. pub async fn whitelist_fetch_random(&self) -> ((Url, u64), usize) {
  673. let whitelist = self.whitelist.read().await;
  674. let position = rand::thread_rng().gen_range(0..whitelist.len());
  675. let entry = &whitelist[position];
  676. (entry.clone(), position)
  677. }
  678. /// Get the oldest entry from the whitelist.
  679. pub async fn whitelist_fetch_last(&self) -> ((Url, u64), usize) {
  680. let whitelist = self.whitelist.read().await;
  681. let position = whitelist.len() - 1;
  682. let entry = &whitelist[position];
  683. (entry.clone(), position)
  684. }
  685. /// Get a random greylist peer that matches the given transport schemes.
  686. pub async fn greylist_fetch_random_with_schemes(&self) -> Option<((Url, u64), usize)> {
  687. trace!(target: "store::greylist_fetch_random_with_schemes", "[START]");
  688. // Retrieve all peers corresponding to that transport schemes
  689. let schemes = &self.settings.allowed_transports;
  690. let greylist = self.greylist_fetch_with_schemes(schemes, None).await;
  691. if greylist.is_empty() {
  692. return None
  693. }
  694. let position = rand::thread_rng().gen_range(0..greylist.len());
  695. let entry = &greylist[position];
  696. Some((entry.clone(), position))
  697. }
  698. /// Get up to n random greylist peers. Schemes are not taken into account.
  699. pub async fn greylist_fetch_n_random(&self, n: u32) -> Vec<(Url, u64)> {
  700. trace!(target: "store::greylist_fetch_n_random", "[START]");
  701. let n = n as usize;
  702. if n == 0 {
  703. return vec![]
  704. }
  705. let mut hosts = vec![];
  706. let greylist = self.greylist.read().await;
  707. for (addr, last_seen) in greylist.iter() {
  708. hosts.push((addr.clone(), *last_seen));
  709. }
  710. if hosts.is_empty() {
  711. debug!(target: "store::greylist_fetch_n_random", "No greylist entries found!");
  712. return hosts
  713. }
  714. // Grab random ones
  715. let urls = hosts.iter().choose_multiple(&mut OsRng, n.min(hosts.len()));
  716. urls.iter().map(|&url| url.clone()).collect()
  717. }
  718. /// Get up to n random greylist peers that match the given transport schemes.
  719. pub async fn greylist_fetch_n_random_with_schemes(
  720. &self,
  721. schemes: &[String],
  722. n: u32,
  723. ) -> Vec<(Url, u64)> {
  724. let n = n as usize;
  725. if n == 0 {
  726. return vec![]
  727. }
  728. trace!(target: "store::greylist_fetch_n_random_with_schemes", "[START]");
  729. // Retrieve all peers corresponding to that transport schemes
  730. let hosts = self.greylist_fetch_with_schemes(schemes, None).await;
  731. if hosts.is_empty() {
  732. debug!(target: "store::greylist_fetch_n_random_with_schemes",
  733. "No such schemes found on greylist!");
  734. return hosts
  735. }
  736. // Grab random ones
  737. let urls = hosts.iter().choose_multiple(&mut OsRng, n.min(hosts.len()));
  738. urls.iter().map(|&url| url.clone()).collect()
  739. }
  740. /// Get up to n random whitelist peers that match the given transport schemes.
  741. pub async fn whitelist_fetch_n_random_with_schemes(
  742. &self,
  743. schemes: &[String],
  744. n: u32,
  745. ) -> Vec<(Url, u64)> {
  746. let n = n as usize;
  747. if n == 0 {
  748. return vec![]
  749. }
  750. trace!(target: "store::whitelist_fetch_n_random_with_schemes", "[START]");
  751. // Retrieve all peers corresponding to that transport schemes
  752. let hosts = self.whitelist_fetch_with_schemes(schemes, None).await;
  753. if hosts.is_empty() {
  754. debug!(target: "store::whitelist_fetch_n_random_with_schemes",
  755. "No such schemes found on whitelist!");
  756. return hosts
  757. }
  758. // Grab random ones
  759. let urls = hosts.iter().choose_multiple(&mut OsRng, n.min(hosts.len()));
  760. urls.iter().map(|&url| url.clone()).collect()
  761. }
  762. /// Get up to limit peers that don't match the given transport schemes from the greylist.
  763. /// If limit was not provided, return all matching peers.
  764. pub async fn greylist_fetch_excluding_schemes(
  765. &self,
  766. schemes: &[String],
  767. limit: Option<usize>,
  768. ) -> Vec<(Url, u64)> {
  769. let greylist = self.greylist.read().await;
  770. let mut limit = match limit {
  771. Some(l) => l.min(greylist.len()),
  772. None => greylist.len(),
  773. };
  774. let mut ret = vec![];
  775. if limit == 0 {
  776. return ret
  777. }
  778. for (addr, last_seen) in greylist.iter() {
  779. if !schemes.contains(&addr.scheme().to_string()) {
  780. ret.push((addr.clone(), *last_seen));
  781. limit -= 1;
  782. if limit == 0 {
  783. return ret
  784. }
  785. }
  786. }
  787. if ret.is_empty() {
  788. debug!(target: "store::greylist_fetch_excluding_schemes",
  789. "No such schemes found on greylist!")
  790. }
  791. ret
  792. }
  793. /// Get up to limit peers that don't match the given transport schemes from the whitelist.
  794. /// If limit was not provided, return all matching peers.
  795. pub async fn whitelist_fetch_excluding_schemes(
  796. &self,
  797. schemes: &[String],
  798. limit: Option<usize>,
  799. ) -> Vec<(Url, u64)> {
  800. let addrs = self.whitelist.read().await;
  801. let mut limit = match limit {
  802. Some(l) => l.min(addrs.len()),
  803. None => addrs.len(),
  804. };
  805. let mut ret = vec![];
  806. if limit == 0 {
  807. return ret
  808. }
  809. for (addr, last_seen) in addrs.iter() {
  810. if !schemes.contains(&addr.scheme().to_string()) {
  811. ret.push((addr.clone(), *last_seen));
  812. limit -= 1;
  813. if limit == 0 {
  814. return ret
  815. }
  816. }
  817. }
  818. if ret.is_empty() {
  819. debug!(target: "store::whiteist_fetch_excluding_schemes",
  820. "No such schemes found on whitelist!")
  821. }
  822. ret
  823. }
  824. /// Get up to n random whitelisted peers that don't match the given transport schemes from the
  825. /// hosts set.
  826. pub async fn whitelist_fetch_n_random_excluding_schemes(
  827. &self,
  828. schemes: &[String],
  829. n: u32,
  830. ) -> Vec<(Url, u64)> {
  831. let n = n as usize;
  832. if n == 0 {
  833. return vec![]
  834. }
  835. trace!(target: "store::whitelist_fetch_excluding_schemes", "[START]");
  836. // Retrieve all peers not corresponding to that transport schemes
  837. let hosts = self.whitelist_fetch_excluding_schemes(schemes, None).await;
  838. if hosts.is_empty() {
  839. debug!(target: "store::whitelist_fetch_n_random_excluding_schemes",
  840. "No such schemes found on whitelist!");
  841. return hosts
  842. }
  843. // Grab random ones
  844. let urls = hosts.iter().choose_multiple(&mut OsRng, n.min(hosts.len()));
  845. urls.iter().map(|&url| url.clone()).collect()
  846. }
  847. /// Get up to limit peers that match the given transport schemes from the greylist.
  848. /// If limit was not provided, return all matching peers.
  849. async fn greylist_fetch_with_schemes(
  850. &self,
  851. schemes: &[String],
  852. limit: Option<usize>,
  853. ) -> Vec<(Url, u64)> {
  854. trace!(target: "store::greylist_fetch_with_schemes", "[START]");
  855. let greylist = self.greylist.read().await;
  856. let mut limit = match limit {
  857. Some(l) => l.min(greylist.len()),
  858. None => greylist.len(),
  859. };
  860. let mut ret = vec![];
  861. if limit == 0 {
  862. return ret
  863. }
  864. for (addr, last_seen) in greylist.iter() {
  865. if schemes.contains(&addr.scheme().to_string()) {
  866. ret.push((addr.clone(), *last_seen));
  867. limit -= 1;
  868. if limit == 0 {
  869. debug!(target: "store::greylist_fetch_with_schemes",
  870. "Found matching scheme, returning {} grey addresses",
  871. ret.len());
  872. return ret
  873. }
  874. }
  875. }
  876. if ret.is_empty() {
  877. debug!(target: "store::greylist_fetch_with_schemes",
  878. "No such schemes found on greylist!")
  879. }
  880. trace!(target: "store::greylist_fetch_with_schemes", "END");
  881. ret
  882. }
  883. /// Get up to limit peers that match the given transport schemes from the whitelist.
  884. /// If limit was not provided, return all matching peers.
  885. async fn whitelist_fetch_with_schemes(
  886. &self,
  887. schemes: &[String],
  888. limit: Option<usize>,
  889. ) -> Vec<(Url, u64)> {
  890. trace!(target: "store::whitelist_fetch_with_schemes", "[START]");
  891. let whitelist = self.whitelist.read().await;
  892. let mut limit = match limit {
  893. Some(l) => l.min(whitelist.len()),
  894. None => whitelist.len(),
  895. };
  896. let mut ret = vec![];
  897. if limit == 0 {
  898. return ret
  899. }
  900. for (addr, last_seen) in whitelist.iter() {
  901. if schemes.contains(&addr.scheme().to_string()) {
  902. ret.push((addr.clone(), *last_seen));
  903. limit -= 1;
  904. if limit == 0 {
  905. debug!(target: "store::whitelist_fetch_with_schemes",
  906. "Found matching scheme, returning {} white addresses",
  907. ret.len());
  908. return ret
  909. }
  910. }
  911. }
  912. if ret.is_empty() {
  913. debug!(target: "store::whitelist_fetch_with_schemes",
  914. "No such schemes found on whitelist!")
  915. }
  916. trace!(target: "store::whitelist_fetch_with_schemes", "END");
  917. ret
  918. }
  919. /// Get up to limit peers that match the given transport schemes from the anchorlist.
  920. /// If limit was not provided, return all matching peers.
  921. async fn anchorlist_fetch_with_schemes(
  922. &self,
  923. schemes: &[String],
  924. limit: Option<usize>,
  925. ) -> Vec<(Url, u64)> {
  926. //trace!(target: "store::anchorlist_fetch_with_schemes", "[START]");
  927. let anchorlist = self.anchorlist.read().await;
  928. let mut limit = match limit {
  929. Some(l) => l.min(anchorlist.len()),
  930. None => anchorlist.len(),
  931. };
  932. let mut ret = vec![];
  933. if limit == 0 {
  934. return ret
  935. }
  936. for (addr, last_seen) in anchorlist.iter() {
  937. if schemes.contains(&addr.scheme().to_string()) {
  938. ret.push((addr.clone(), *last_seen));
  939. limit -= 1;
  940. if limit == 0 {
  941. debug!(target: "store::anchorlist_fetch_with_schemes",
  942. "Found matching scheme, returning {} anchor addresses",
  943. ret.len());
  944. return ret
  945. }
  946. }
  947. }
  948. if ret.is_empty() {
  949. warn!(target: "store::anchorlist_fetch_with_schemes",
  950. "No matching schemes found on anchorlist")
  951. }
  952. trace!(target: "store::anchorlist_fetch_with_schemes", "END");
  953. ret
  954. }
  955. /// Load the hostlist from a file.
  956. pub async fn load_hosts(&self) -> Result<()> {
  957. let path = expand_path(&self.settings.hostlist)?;
  958. if !path.exists() {
  959. if let Some(parent) = path.parent() {
  960. fs::create_dir_all(parent)?;
  961. }
  962. File::create(path.clone())?;
  963. }
  964. let contents = load_file(&path);
  965. if let Err(e) = contents {
  966. warn!(target: "store", "Failed retrieving saved hosts: {}", e);
  967. return Ok(())
  968. }
  969. for line in contents.unwrap().lines() {
  970. let data: Vec<&str> = line.split('\t').collect();
  971. let url = match Url::parse(data[1]) {
  972. Ok(u) => u,
  973. Err(e) => {
  974. debug!(target: "store", "load_hosts(): Skipping malformed URL {}", e);
  975. continue
  976. }
  977. };
  978. let last_seen = match data[2].parse::<u64>() {
  979. Ok(t) => t,
  980. Err(e) => {
  981. debug!(target: "store", "load_hosts(): Skipping malformed last seen {}", e);
  982. continue
  983. }
  984. };
  985. match data[0] {
  986. "greylist" => {
  987. self.greylist_store(url, last_seen).await;
  988. }
  989. "whitelist" => {
  990. self.whitelist_store(url, last_seen).await;
  991. }
  992. "anchorlist" => {
  993. self.anchorlist_store(url, last_seen).await;
  994. }
  995. _ => {
  996. debug!(target: "store", "load_hosts(): Malformed list name...");
  997. }
  998. }
  999. }
  1000. Ok(())
  1001. }
  1002. /// Save the hostlist to a file. Whitelist gets written to the greylist to force
  1003. /// whitelist entries through the refinery on start.
  1004. pub async fn save_hosts(&self) -> Result<()> {
  1005. let path = expand_path(&self.settings.hostlist)?;
  1006. let mut tsv = String::new();
  1007. let mut whitelist = vec![];
  1008. // First gather all the whitelist entries we don't have in greylist.
  1009. for (url, last_seen) in self.whitelist_fetch_all().await {
  1010. if !self.greylist_contains(&url).await {
  1011. whitelist.push((url, last_seen))
  1012. }
  1013. }
  1014. // Collect the greylist and anchorlist entries, and append any whitelist entries to the
  1015. // greylist before saving.
  1016. for (name, mut list) in self.hostlist_fetch_safe().await {
  1017. if name == *"greylist".to_string() {
  1018. list.append(&mut whitelist)
  1019. }
  1020. for (url, last_seen) in list {
  1021. tsv.push_str(&format!("{}\t{}\t{}\n", name, url, last_seen));
  1022. }
  1023. }
  1024. if !tsv.eq("") {
  1025. info!(target: "store", "Saving hosts to: {:?}",
  1026. path);
  1027. if let Err(e) = save_file(&path, &tsv) {
  1028. error!(target: "store", "Failed saving hosts: {}", e);
  1029. }
  1030. }
  1031. Ok(())
  1032. }
  1033. }
  1034. #[cfg(test)]
  1035. mod tests {
  1036. use super::{
  1037. super::super::{settings::Settings, P2p},
  1038. *,
  1039. };
  1040. use crate::system::sleep;
  1041. use smol::Executor;
  1042. use std::{sync::Arc, time::UNIX_EPOCH};
  1043. #[test]
  1044. fn test_is_local_host() {
  1045. smol::block_on(async {
  1046. let settings = Settings {
  1047. localnet: false,
  1048. external_addrs: vec![
  1049. Url::parse("tcp://foo.bar:123").unwrap(),
  1050. Url::parse("tcp://lol.cat:321").unwrap(),
  1051. ],
  1052. ..Default::default()
  1053. };
  1054. let hosts = Hosts::new(Arc::new(settings.clone()));
  1055. let local_hosts: Vec<Url> = vec![
  1056. Url::parse("tcp://localhost").unwrap(),
  1057. Url::parse("tcp://127.0.0.1").unwrap(),
  1058. Url::parse("tcp+tls://[::1]").unwrap(),
  1059. Url::parse("tcp://localhost.localdomain").unwrap(),
  1060. Url::parse("tcp://192.168.10.65").unwrap(),
  1061. ];
  1062. for host in local_hosts {
  1063. eprintln!("{}", host);
  1064. assert!(hosts.is_local_host(host).await);
  1065. }
  1066. let remote_hosts: Vec<Url> = vec![
  1067. Url::parse("https://dyne.org").unwrap(),
  1068. Url::parse("tcp://77.168.10.65:2222").unwrap(),
  1069. Url::parse("tcp://[2345:0425:2CA1:0000:0000:0567:5673:23b5]").unwrap(),
  1070. Url::parse("http://eweiibe6tdjsdprb4px6rqrzzcsi22m4koia44kc5pcjr7nec2rlxyad.onion")
  1071. .unwrap(),
  1072. ];
  1073. for host in remote_hosts {
  1074. assert!(!(hosts.is_local_host(host).await))
  1075. }
  1076. });
  1077. }
  1078. #[test]
  1079. fn test_greylist_store() {
  1080. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  1081. smol::block_on(async {
  1082. let settings = Settings {
  1083. localnet: false,
  1084. external_addrs: vec![
  1085. Url::parse("tcp://foo.bar:123").unwrap(),
  1086. Url::parse("tcp://lol.cat:321").unwrap(),
  1087. ],
  1088. ..Default::default()
  1089. };
  1090. let hosts = Hosts::new(Arc::new(settings.clone()));
  1091. for addr in settings.external_addrs {
  1092. hosts.greylist_store(addr, last_seen).await;
  1093. }
  1094. assert!(!hosts.is_empty_greylist().await);
  1095. let local_hosts = vec![
  1096. (Url::parse("tcp://localhost:3921").unwrap()),
  1097. (Url::parse("tor://[::1]:21481").unwrap()),
  1098. (Url::parse("tcp://192.168.10.65:311").unwrap()),
  1099. (Url::parse("tcp+tls://0.0.0.0:2312").unwrap()),
  1100. (Url::parse("tcp://255.255.255.255:2131").unwrap()),
  1101. ];
  1102. for host in &local_hosts {
  1103. hosts.greylist_store(host.clone(), last_seen).await;
  1104. }
  1105. assert!(!hosts.is_empty_greylist().await);
  1106. let remote_hosts = vec![
  1107. (Url::parse("tcp://dark.fi:80").unwrap()),
  1108. (Url::parse("tcp://http.cat:401").unwrap()),
  1109. (Url::parse("tcp://foo.bar:111").unwrap()),
  1110. ];
  1111. for host in &remote_hosts {
  1112. hosts.greylist_store(host.clone(), last_seen).await;
  1113. }
  1114. assert!(hosts.greylist_contains(&remote_hosts[0]).await);
  1115. assert!(hosts.greylist_contains(&remote_hosts[1]).await);
  1116. assert!(hosts.greylist_contains(&remote_hosts[2]).await);
  1117. });
  1118. }
  1119. #[test]
  1120. fn test_whitelist_store() {
  1121. smol::block_on(async {
  1122. let settings = Settings {
  1123. localnet: false,
  1124. external_addrs: vec![
  1125. Url::parse("tcp://foo.bar:123").unwrap(),
  1126. Url::parse("tcp://lol.cat:321").unwrap(),
  1127. ],
  1128. ..Default::default()
  1129. };
  1130. let hosts = Hosts::new(Arc::new(settings.clone()));
  1131. assert!(hosts.is_empty_whitelist().await);
  1132. let url = Url::parse("tcp://dark.renaissance:333").unwrap();
  1133. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  1134. hosts.whitelist_store(url.clone(), last_seen).await;
  1135. assert!(!hosts.is_empty_whitelist().await);
  1136. assert!(hosts.whitelist_contains(&url).await);
  1137. });
  1138. }
  1139. #[test]
  1140. fn test_whitelist_get_last() {
  1141. smol::block_on(async {
  1142. let settings = Settings {
  1143. localnet: false,
  1144. external_addrs: vec![
  1145. Url::parse("tcp://foo.bar:123").unwrap(),
  1146. Url::parse("tcp://lol.cat:321").unwrap(),
  1147. ],
  1148. ..Default::default()
  1149. };
  1150. let hosts = Hosts::new(Arc::new(settings.clone()));
  1151. // Build up a hostlist
  1152. for i in 0..10 {
  1153. sleep(1).await;
  1154. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  1155. let url = Url::parse(&format!("tcp://whitelist{}:123", i)).unwrap();
  1156. hosts.whitelist_store(url.clone(), last_seen).await;
  1157. }
  1158. for (url, last_seen) in hosts.whitelist.read().await.iter() {
  1159. println!("{} {}", url, last_seen);
  1160. }
  1161. let (entry, _position) = hosts.whitelist_fetch_last().await;
  1162. println!("last entry: {} {}", entry.0, entry.1);
  1163. });
  1164. }
  1165. #[test]
  1166. fn test_hostlist_get_entry() {
  1167. smol::block_on(async {
  1168. let settings = Settings {
  1169. localnet: false,
  1170. external_addrs: vec![
  1171. Url::parse("tcp://foo.bar:123").unwrap(),
  1172. Url::parse("tcp://lol.cat:321").unwrap(),
  1173. ],
  1174. ..Default::default()
  1175. };
  1176. let hosts = Hosts::new(Arc::new(settings.clone()));
  1177. let url = Url::parse("tcp://dark.renaissance:333").unwrap();
  1178. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  1179. hosts.whitelist_store(url.clone(), last_seen).await;
  1180. hosts.anchorlist_store(url.clone(), last_seen).await;
  1181. assert!(hosts.get_whitelist_entry_at_addr(&url).await.is_some());
  1182. assert!(hosts.get_anchorlist_entry_at_addr(&url).await.is_some());
  1183. });
  1184. }
  1185. #[test]
  1186. fn test_remove() {
  1187. smol::block_on(async {
  1188. let settings = Settings {
  1189. outbound_connections: 8,
  1190. allowed_transports: vec!["tcp".to_string()],
  1191. ..Default::default()
  1192. };
  1193. let hosts = Hosts::new(Arc::new(settings.clone()));
  1194. let url = Url::parse("tcp://dark.renaissance:333").unwrap();
  1195. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  1196. hosts.whitelist_store(url.clone(), last_seen).await;
  1197. sleep(1).await;
  1198. let url = Url::parse("tcp://milady:333").unwrap();
  1199. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  1200. hosts.whitelist_store(url.clone(), last_seen).await;
  1201. sleep(1).await;
  1202. let url = Url::parse("tcp://king-ted:333").unwrap();
  1203. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  1204. hosts.whitelist_store(url.clone(), last_seen).await;
  1205. for (url, last_seen) in hosts.whitelist.read().await.iter() {
  1206. println!("{}, {}", url, last_seen);
  1207. }
  1208. let position = hosts.get_whitelist_index_at_addr(url.clone()).await.unwrap();
  1209. hosts.whitelist_remove(&url, position).await;
  1210. for (url, last_seen) in hosts.whitelist.read().await.iter() {
  1211. println!("{}, {}", url, last_seen);
  1212. }
  1213. });
  1214. }
  1215. #[test]
  1216. fn test_fetch_address() {
  1217. smol::block_on(async {
  1218. let mut hostlist = vec![];
  1219. let mut grey_urls = vec![];
  1220. let mut white_urls = vec![];
  1221. let mut anchor_urls = vec![];
  1222. let ex = Arc::new(Executor::new());
  1223. let settings = Settings {
  1224. outbound_connections: 8,
  1225. allowed_transports: vec!["tcp".to_string()],
  1226. ..Default::default()
  1227. };
  1228. let p2p = P2p::new(settings, ex.clone()).await;
  1229. let hosts = p2p.hosts();
  1230. // Build up a hostlist
  1231. for i in 0..5 {
  1232. let last_seen = UNIX_EPOCH.elapsed().unwrap().as_secs();
  1233. hosts
  1234. .anchorlist_store(
  1235. Url::parse(&format!("tcp://anchorlist{}:123", i)).unwrap(),
  1236. last_seen,
  1237. )
  1238. .await;
  1239. hosts
  1240. .whitelist_store(
  1241. Url::parse(&format!("tcp://whitelist{}:123", i)).unwrap(),
  1242. last_seen,
  1243. )
  1244. .await;
  1245. hosts
  1246. .greylist_store(
  1247. Url::parse(&format!("tcp://greylist{}:123", i)).unwrap(),
  1248. last_seen,
  1249. )
  1250. .await;
  1251. grey_urls
  1252. .push((Url::parse(&format!("tcp://greylist{}:123", i)).unwrap(), last_seen));
  1253. white_urls
  1254. .push((Url::parse(&format!("tcp://whitelist{}:123", i)).unwrap(), last_seen));
  1255. anchor_urls
  1256. .push((Url::parse(&format!("tcp://anchorlist{}:123", i)).unwrap(), last_seen));
  1257. }
  1258. assert!(!hosts.is_empty_anchorlist().await);
  1259. assert!(!hosts.is_empty_whitelist().await);
  1260. assert!(!hosts.is_empty_greylist().await);
  1261. let transports = &p2p.settings().allowed_transports;
  1262. let white_count =
  1263. p2p.settings().outbound_connections * p2p.settings().white_connection_percent / 100;
  1264. // Simulate the address selection logic found in outbound_session::fetch_address()
  1265. for i in 0..8 {
  1266. let addrs = {
  1267. if i < p2p.settings().anchor_connection_count {
  1268. hosts.anchorlist_fetch_address(transports).await
  1269. } else if i < white_count {
  1270. hosts.whitelist_fetch_address(transports).await
  1271. } else {
  1272. hosts.greylist_fetch_address(transports).await
  1273. }
  1274. };
  1275. hostlist.push(addrs);
  1276. }
  1277. //// Check we're returning the correct addresses.
  1278. anchor_urls.sort();
  1279. white_urls.sort();
  1280. grey_urls.sort();
  1281. hostlist[0].sort();
  1282. hostlist[4].sort();
  1283. hostlist[7].sort();
  1284. assert!(anchor_urls == hostlist[0]);
  1285. assert!(white_urls == hostlist[4]);
  1286. assert!(grey_urls == hostlist[7]);
  1287. // Now clear the anchorlist.
  1288. // anchorlist_fetch_address should return whitelist entries if
  1289. // the anchorlist is empty.
  1290. let mut anchorlist = hosts.anchorlist.write().await;
  1291. anchorlist.clear();
  1292. drop(anchorlist);
  1293. let mut addrs = hosts.anchorlist_fetch_address(transports).await;
  1294. addrs.sort();
  1295. assert!(white_urls == addrs);
  1296. // Now clear the whitelist.
  1297. // anchorlist_fetch_address should return greylist entries if
  1298. // both the anchorlist and the whitelist are empty.
  1299. let mut whitelist = hosts.whitelist.write().await;
  1300. whitelist.clear();
  1301. drop(whitelist);
  1302. let mut addrs = hosts.anchorlist_fetch_address(transports).await;
  1303. addrs.sort();
  1304. assert!(grey_urls == addrs);
  1305. })
  1306. }
  1307. }