tests.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. /* This file is part 10f 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. // cargo +nightly test --release --features=net --lib p2p -- --include-ignored
  19. use std::{collections::HashSet, sync::Arc};
  20. use log::{info, warn};
  21. use rand::{prelude::SliceRandom, rngs::ThreadRng, Rng};
  22. use smol::{channel, future, Executor};
  23. use url::Url;
  24. use crate::{
  25. net::{hosts::HostColor, P2p, Settings},
  26. system::sleep,
  27. };
  28. // Number of nodes to spawn and number of peers each node connects to
  29. const N_NODES: usize = 5;
  30. const N_CONNS: usize = 4;
  31. const SEED: &str = "tcp://127.0.0.1:51505";
  32. fn init_logger() {
  33. let mut cfg = simplelog::ConfigBuilder::new();
  34. cfg.add_filter_ignore("sled".to_string());
  35. cfg.add_filter_ignore("net::protocol_ping".to_string());
  36. cfg.add_filter_ignore("net::channel::subscribe_stop()".to_string());
  37. cfg.add_filter_ignore("net::hosts".to_string());
  38. cfg.add_filter_ignore("net::session".to_string());
  39. cfg.add_filter_ignore("net::outbound_session".to_string());
  40. cfg.add_filter_ignore("net::inbound_session".to_string());
  41. cfg.add_filter_ignore("net::message_subscriber".to_string());
  42. cfg.add_filter_ignore("net::protocol_address".to_string());
  43. cfg.add_filter_ignore("net::protocol_version".to_string());
  44. cfg.add_filter_ignore("net::protocol_registry".to_string());
  45. cfg.add_filter_ignore("net::protocol_jobs_manager".to_string());
  46. cfg.add_filter_ignore("net::channel::send()".to_string());
  47. cfg.add_filter_ignore("net::channel::start()".to_string());
  48. cfg.add_filter_ignore("net::channel::handle_stop()".to_string());
  49. cfg.add_filter_ignore("net::channel::subscribe_msg()".to_string());
  50. cfg.add_filter_ignore("net::channel::main_receive_loop()".to_string());
  51. cfg.add_filter_ignore("net::tcp".to_string());
  52. // We check this error so we can execute same file tests in parallel,
  53. // otherwise second one fails to init logger here.
  54. if simplelog::TermLogger::init(
  55. simplelog::LevelFilter::Info,
  56. //simplelog::LevelFilter::Debug,
  57. //simplelog::LevelFilter::Trace,
  58. cfg.build(),
  59. simplelog::TerminalMode::Mixed,
  60. simplelog::ColorChoice::Auto,
  61. )
  62. .is_err()
  63. {
  64. warn!(target: "test_harness", "Logger already initialized");
  65. }
  66. }
  67. async fn spawn_node(
  68. inbound_addrs: Vec<Url>,
  69. external_addrs: Vec<Url>,
  70. peers: Vec<Url>,
  71. seeds: Vec<Url>,
  72. node_id: String,
  73. ex: Arc<Executor<'static>>,
  74. ) -> Arc<P2p> {
  75. let settings = Settings {
  76. localnet: true,
  77. inbound_addrs,
  78. external_addrs,
  79. outbound_connections: 2,
  80. outbound_peer_discovery_cooloff_time: 2,
  81. outbound_connect_timeout: 2,
  82. inbound_connections: usize::MAX,
  83. greylist_refinery_interval: 15,
  84. peers,
  85. seeds,
  86. node_id,
  87. allowed_transports: vec!["tcp".to_string()],
  88. ..Default::default()
  89. };
  90. P2p::new(settings, ex.clone()).await
  91. }
  92. async fn spawn_seed_session(starting_port: usize, ex: Arc<Executor<'static>>) -> Vec<Arc<P2p>> {
  93. let mut outbound_instances = vec![];
  94. let seed_addr = Url::parse(SEED).unwrap();
  95. info!("========================================================");
  96. info!("Initializing outbound nodes...");
  97. info!("========================================================");
  98. for i in 0..N_NODES {
  99. let p2p = spawn_node(
  100. vec![Url::parse(&format!("tcp://127.0.0.1:{}", starting_port + i)).unwrap()],
  101. vec![Url::parse(&format!("tcp://127.0.0.1:{}", starting_port + i)).unwrap()],
  102. vec![],
  103. vec![seed_addr.clone()],
  104. (starting_port + i).to_string(),
  105. ex.clone(),
  106. )
  107. .await;
  108. outbound_instances.push(p2p);
  109. }
  110. // Start the P2P network
  111. for p2p in outbound_instances.iter() {
  112. info!("========================================================");
  113. info!("Starting node={}", p2p.settings().external_addrs[0]);
  114. info!("========================================================");
  115. p2p.clone().start().await.unwrap();
  116. }
  117. outbound_instances
  118. }
  119. async fn spawn_manual_session(
  120. peer_indexes: &[usize],
  121. starting_port: usize,
  122. rng: &mut ThreadRng,
  123. ex: Arc<Executor<'static>>,
  124. ) -> Vec<Arc<P2p>> {
  125. let mut manual_instances = vec![];
  126. info!("========================================================");
  127. info!("Initializing manual nodes...");
  128. info!("========================================================");
  129. // Initialize the nodes
  130. for i in 0..N_NODES {
  131. // Everyone will connect to N_CONNS random peers.
  132. let mut peer_indexes_copy = peer_indexes.to_owned();
  133. peer_indexes_copy.remove(i);
  134. let peer_indexes_to_connect: Vec<_> =
  135. peer_indexes_copy.choose_multiple(rng, N_CONNS).collect();
  136. let mut peers = vec![];
  137. for peer_index in peer_indexes_to_connect {
  138. let port = starting_port + peer_index;
  139. peers.push(Url::parse(&format!("tcp://127.0.0.1:{}", port)).unwrap());
  140. }
  141. let p2p = spawn_node(
  142. vec![Url::parse(&format!("tcp://127.0.0.1:{}", starting_port + i)).unwrap()],
  143. vec![Url::parse(&format!("tcp://127.0.0.1:{}", starting_port + i)).unwrap()],
  144. peers,
  145. vec![],
  146. (starting_port + i).to_string(),
  147. ex.clone(),
  148. )
  149. .await;
  150. manual_instances.push(p2p);
  151. }
  152. // Start the P2P network
  153. for p2p in manual_instances.iter() {
  154. info!("========================================================");
  155. info!("Starting node={}", p2p.settings().external_addrs[0]);
  156. info!("========================================================");
  157. p2p.clone().start().await.unwrap();
  158. }
  159. manual_instances
  160. }
  161. async fn get_random_gold_host(
  162. outbound_instances: &[Arc<P2p>],
  163. index: usize,
  164. ) -> ((Url, u64), usize) {
  165. let random_node = &outbound_instances[index];
  166. let hosts = random_node.hosts();
  167. let external_addr = &random_node.settings().external_addrs[0];
  168. info!("========================================================");
  169. info!("Getting gold addr from node={}", external_addr);
  170. info!("========================================================");
  171. let list = hosts.container.hostlists[HostColor::Gold as usize].read().await;
  172. // TODO: This assert fails ~10% of the time. Need to figure out why.
  173. assert!(!list.is_empty());
  174. let position = rand::thread_rng().gen_range(0..list.len());
  175. let entry = &list[position];
  176. (entry.clone(), position)
  177. }
  178. async fn check_random_hostlist(outbound_instances: &Vec<Arc<P2p>>, rng: &mut ThreadRng) {
  179. let mut urls = HashSet::new();
  180. let random_node = outbound_instances.choose(rng).unwrap();
  181. let external_addr = &random_node.settings().external_addrs[0];
  182. info!("========================================================");
  183. info!("Checking node={}", external_addr);
  184. info!("========================================================");
  185. let greylist = random_node.hosts().container.fetch_all(HostColor::Grey).await;
  186. let whitelist = random_node.hosts().container.fetch_all(HostColor::White).await;
  187. let goldlist = random_node.hosts().container.fetch_all(HostColor::Gold).await;
  188. for (url, _) in greylist {
  189. assert!(urls.insert(url));
  190. }
  191. for (url, _) in whitelist {
  192. assert!(urls.insert(url));
  193. }
  194. for (url, _) in goldlist {
  195. assert!(urls.insert(url));
  196. }
  197. assert!(!urls.is_empty());
  198. }
  199. async fn kill_node(outbound_instances: &Vec<Arc<P2p>>, node: Url) {
  200. for p2p in outbound_instances {
  201. if p2p.settings().external_addrs[0] == node {
  202. info!("========================================================");
  203. info!("Shutting down node: {}", p2p.settings().external_addrs[0]);
  204. info!("========================================================");
  205. p2p.stop().await;
  206. }
  207. }
  208. }
  209. macro_rules! test_body {
  210. ($real_call:ident) => {
  211. init_logger();
  212. let ex = Arc::new(Executor::new());
  213. let ex_ = ex.clone();
  214. let (signal, shutdown) = channel::unbounded::<()>();
  215. // Run a thread for each node.
  216. easy_parallel::Parallel::new()
  217. .each(0..N_NODES, |_| future::block_on(ex.run(shutdown.recv())))
  218. .finish(|| {
  219. future::block_on(async {
  220. $real_call(ex_).await;
  221. drop(signal);
  222. })
  223. });
  224. };
  225. }
  226. #[test]
  227. fn p2p_test() {
  228. test_body!(p2p_test_real);
  229. }
  230. async fn p2p_test_real(ex: Arc<Executor<'static>>) {
  231. let mut rng = rand::thread_rng();
  232. // ============================================================
  233. // 1. Create a new seed node.
  234. // ============================================================
  235. let seed_addr = Url::parse(SEED).unwrap();
  236. let settings = Settings {
  237. localnet: true,
  238. inbound_addrs: vec![seed_addr.clone()],
  239. outbound_connections: 0,
  240. inbound_connections: usize::MAX,
  241. seeds: vec![],
  242. peers: vec![],
  243. allowed_transports: vec!["tcp".to_string()],
  244. greylist_refinery_interval: 12,
  245. node_id: "seed".to_string(),
  246. ..Default::default()
  247. };
  248. let seed = P2p::new(settings, ex.clone()).await;
  249. info!("========================================================");
  250. info!("Starting seed node on {}", SEED);
  251. info!("========================================================");
  252. seed.clone().start().await.unwrap();
  253. // ============================================================
  254. // 2. Spawn outbound nodes that will connect to the seed node.
  255. // ============================================================
  256. let outbound_instances = spawn_seed_session(43200, ex.clone()).await;
  257. info!("========================================================");
  258. info!("Waiting 10s for all peers to reach the seed node");
  259. info!("========================================================");
  260. sleep(10).await;
  261. // ===========================================================
  262. // 3. Assert that all nodes have shared their external addr
  263. // with the seed node.
  264. // ===========================================================
  265. let greylist = seed.hosts().container.fetch_all(HostColor::Grey).await;
  266. assert!(greylist.len() == N_NODES);
  267. info!("========================================================");
  268. info!("Seedsync session successful!");
  269. info!("========================================================");
  270. info!("========================================================");
  271. info!("Waiting 5s for seed node refinery to kick in...");
  272. info!("========================================================");
  273. sleep(5).await;
  274. // ===========================================================
  275. // 4. Assert that seed node has at least one whitelist entry,
  276. // indicating that the refinery process is happening correctly.
  277. // ===========================================================
  278. assert!(!seed.hosts().container.is_empty(HostColor::White).await);
  279. info!("========================================================");
  280. info!("Seed node refinery operating successfully!");
  281. info!("========================================================");
  282. info!("========================================================");
  283. info!("Waiting 5s for peers to propagate...");
  284. info!("========================================================");
  285. sleep(5).await;
  286. // ===========================================================
  287. // 5. Select a random peer and ensure that its hostlist is not
  288. // empty. This ensures the seed node is sharing whitelisted
  289. // nodes around the network.
  290. // ===========================================================
  291. check_random_hostlist(&outbound_instances, &mut rng).await;
  292. info!("========================================================");
  293. info!("Peer successfully received addrs!");
  294. info!("========================================================");
  295. // ===========================================================
  296. // 6. Select a random gold peer from one of the nodes and kill
  297. // it.
  298. // ===========================================================
  299. info!("========================================================");
  300. info!("Selecting a random gold entry...");
  301. info!("========================================================");
  302. let random_node_index = rand::thread_rng().gen_range(0..outbound_instances.len());
  303. let ((addr, _), _) = get_random_gold_host(&outbound_instances, random_node_index).await;
  304. kill_node(&outbound_instances, addr.clone()).await;
  305. info!("========================================================");
  306. info!("Waiting for greylist downgrade sequence to occur...");
  307. info!("========================================================");
  308. // ===========================================================
  309. // 7. Verify the peer has been removed from the Gold list.
  310. // ===========================================================
  311. outbound_instances[random_node_index]
  312. .hosts()
  313. .container
  314. .contains(HostColor::Grey as usize, &addr)
  315. .await;
  316. info!("========================================================");
  317. info!("Greylist downgrade occured successfully!");
  318. info!("========================================================");
  319. info!("========================================================");
  320. info!("Seed session successful! Shutting down seed test...");
  321. info!("========================================================");
  322. // ===========================================================
  323. // 8. Stop the P2P network
  324. // ===========================================================
  325. for p2p in outbound_instances.iter() {
  326. p2p.clone().stop().await;
  327. }
  328. seed.clone().stop().await;
  329. info!("========================================================");
  330. info!("Seed test shutdown complete! Starting manual test...");
  331. info!("========================================================");
  332. let mut rng = rand::thread_rng();
  333. let peer_indexes: Vec<usize> = (0..N_NODES).collect();
  334. let manual_instances = spawn_manual_session(&peer_indexes, 64200, &mut rng, ex.clone()).await;
  335. info!("========================================================");
  336. info!("Waiting 5s for all manual peers to connect");
  337. info!("========================================================");
  338. sleep(5).await;
  339. info!("========================================================");
  340. info!("Checking manual nodes connected successfully...");
  341. info!("========================================================");
  342. for p2p in manual_instances.clone() {
  343. let goldlist = p2p.hosts().container.fetch_all(HostColor::Gold).await;
  344. assert!(goldlist.len() == N_CONNS);
  345. }
  346. info!("========================================================");
  347. info!("Manual session connected successfully!");
  348. info!("========================================================");
  349. info!("========================================================");
  350. info!("Selecting a random gold entry...");
  351. info!("========================================================");
  352. let random_node_index = rand::thread_rng().gen_range(0..manual_instances.len());
  353. let ((addr, _), _) = get_random_gold_host(&manual_instances, random_node_index).await;
  354. kill_node(&manual_instances, addr.clone()).await;
  355. info!("========================================================");
  356. info!("Waiting for greylist downgrade sequence to occur...");
  357. info!("========================================================");
  358. // ===========================================================
  359. // 7. Verify the peer has been removed from the Gold list.
  360. // ===========================================================
  361. manual_instances[random_node_index]
  362. .hosts()
  363. .container
  364. .contains(HostColor::Grey as usize, &addr)
  365. .await;
  366. info!("========================================================");
  367. info!("Greylist downgrade occured successfully!");
  368. info!("========================================================");
  369. info!("========================================================");
  370. info!("Manual session successful! Shutting down manual test...");
  371. info!("========================================================");
  372. // ===========================================================
  373. // 8. Stop the P2P network
  374. // ===========================================================
  375. for p2p in manual_instances.clone() {
  376. p2p.clone().stop().await;
  377. }
  378. }