tests.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. // 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. assert!(!list.is_empty());
  173. let position = rand::thread_rng().gen_range(0..list.len());
  174. let entry = &list[position];
  175. (entry.clone(), position)
  176. }
  177. async fn check_random_hostlist(outbound_instances: &Vec<Arc<P2p>>, rng: &mut ThreadRng) {
  178. let mut urls = HashSet::new();
  179. let random_node = outbound_instances.choose(rng).unwrap();
  180. let external_addr = &random_node.settings().external_addrs[0];
  181. info!("========================================================");
  182. info!("Checking node={}", external_addr);
  183. info!("========================================================");
  184. let greylist = random_node.hosts().container.fetch_all(HostColor::Grey).await;
  185. let whitelist = random_node.hosts().container.fetch_all(HostColor::White).await;
  186. let goldlist = random_node.hosts().container.fetch_all(HostColor::Gold).await;
  187. for (url, _) in greylist {
  188. assert!(urls.insert(url));
  189. }
  190. for (url, _) in whitelist {
  191. assert!(urls.insert(url));
  192. }
  193. for (url, _) in goldlist {
  194. assert!(urls.insert(url));
  195. }
  196. assert!(!urls.is_empty());
  197. }
  198. async fn kill_node(outbound_instances: &Vec<Arc<P2p>>, node: Url) {
  199. for p2p in outbound_instances {
  200. if p2p.settings().external_addrs[0] == node {
  201. info!("========================================================");
  202. info!("Shutting down node: {}", p2p.settings().external_addrs[0]);
  203. info!("========================================================");
  204. p2p.stop().await;
  205. }
  206. }
  207. }
  208. macro_rules! test_body {
  209. ($real_call:ident) => {
  210. init_logger();
  211. let ex = Arc::new(Executor::new());
  212. let ex_ = ex.clone();
  213. let (signal, shutdown) = channel::unbounded::<()>();
  214. // Run a thread for each node.
  215. easy_parallel::Parallel::new()
  216. .each(0..N_NODES, |_| future::block_on(ex.run(shutdown.recv())))
  217. .finish(|| {
  218. future::block_on(async {
  219. $real_call(ex_).await;
  220. drop(signal);
  221. })
  222. });
  223. };
  224. }
  225. #[test]
  226. fn p2p_test() {
  227. test_body!(p2p_test_real);
  228. }
  229. async fn p2p_test_real(ex: Arc<Executor<'static>>) {
  230. let mut rng = rand::thread_rng();
  231. // ============================================================
  232. // 1. Create a new seed node.
  233. // ============================================================
  234. let seed_addr = Url::parse(SEED).unwrap();
  235. let settings = Settings {
  236. localnet: true,
  237. inbound_addrs: vec![seed_addr.clone()],
  238. outbound_connections: 0,
  239. inbound_connections: usize::MAX,
  240. seeds: vec![],
  241. peers: vec![],
  242. allowed_transports: vec!["tcp".to_string()],
  243. greylist_refinery_interval: 12,
  244. node_id: "seed".to_string(),
  245. ..Default::default()
  246. };
  247. let seed = P2p::new(settings, ex.clone()).await;
  248. info!("========================================================");
  249. info!("Starting seed node on {}", SEED);
  250. info!("========================================================");
  251. seed.clone().start().await.unwrap();
  252. // ============================================================
  253. // 2. Spawn outbound nodes that will connect to the seed node.
  254. // ============================================================
  255. let outbound_instances = spawn_seed_session(43200, ex.clone()).await;
  256. info!("========================================================");
  257. info!("Waiting 10s for all peers to reach the seed node");
  258. info!("========================================================");
  259. sleep(10).await;
  260. // ===========================================================
  261. // 3. Assert that all nodes have shared their external addr
  262. // with the seed node.
  263. // ===========================================================
  264. let greylist = seed.hosts().container.fetch_all(HostColor::Grey).await;
  265. assert!(greylist.len() == N_NODES);
  266. info!("========================================================");
  267. info!("Seedsync session successful!");
  268. info!("========================================================");
  269. info!("========================================================");
  270. info!("Waiting 5s for seed node refinery to kick in...");
  271. info!("========================================================");
  272. sleep(5).await;
  273. // ===========================================================
  274. // 4. Assert that seed node has at least one whitelist entry,
  275. // indicating that the refinery process is happening correctly.
  276. // ===========================================================
  277. assert!(!seed.hosts().container.is_empty(HostColor::White).await);
  278. info!("========================================================");
  279. info!("Seed node refinery operating successfully!");
  280. info!("========================================================");
  281. info!("========================================================");
  282. info!("Waiting 5s for peers to propagate...");
  283. info!("========================================================");
  284. sleep(5).await;
  285. // ===========================================================
  286. // 5. Select a random peer and ensure that its hostlist is not
  287. // empty. This ensures the seed node is sharing whitelisted
  288. // nodes around the network.
  289. // ===========================================================
  290. check_random_hostlist(&outbound_instances, &mut rng).await;
  291. info!("========================================================");
  292. info!("Peer successfully received addrs!");
  293. info!("========================================================");
  294. info!("========================================================");
  295. info!("Waiting 5s for outbound loop to connect...");
  296. info!("========================================================");
  297. sleep(5).await;
  298. // ===========================================================
  299. // 6. Select a random gold peer from one of the nodes and kill
  300. // it.
  301. // ===========================================================
  302. info!("========================================================");
  303. info!("Selecting a random gold entry...");
  304. info!("========================================================");
  305. let random_node_index = rand::thread_rng().gen_range(0..outbound_instances.len());
  306. let ((addr, _), _) = get_random_gold_host(&outbound_instances, random_node_index).await;
  307. kill_node(&outbound_instances, addr.clone()).await;
  308. info!("========================================================");
  309. info!("Waiting for greylist downgrade sequence to occur...");
  310. info!("========================================================");
  311. // ===========================================================
  312. // 7. Verify the peer has been removed from the Gold list.
  313. // ===========================================================
  314. outbound_instances[random_node_index]
  315. .hosts()
  316. .container
  317. .contains(HostColor::Grey as usize, &addr)
  318. .await;
  319. info!("========================================================");
  320. info!("Greylist downgrade occured successfully!");
  321. info!("========================================================");
  322. info!("========================================================");
  323. info!("Seed session successful! Shutting down seed test...");
  324. info!("========================================================");
  325. // ===========================================================
  326. // 8. Stop the P2P network
  327. // ===========================================================
  328. for p2p in outbound_instances.iter() {
  329. p2p.clone().stop().await;
  330. }
  331. seed.clone().stop().await;
  332. info!("========================================================");
  333. info!("Seed test shutdown complete! Starting manual test...");
  334. info!("========================================================");
  335. let mut rng = rand::thread_rng();
  336. let peer_indexes: Vec<usize> = (0..N_NODES).collect();
  337. let manual_instances = spawn_manual_session(&peer_indexes, 64200, &mut rng, ex.clone()).await;
  338. info!("========================================================");
  339. info!("Waiting 5s for all manual peers to connect");
  340. info!("========================================================");
  341. sleep(5).await;
  342. info!("========================================================");
  343. info!("Checking manual nodes connected successfully...");
  344. info!("========================================================");
  345. for p2p in manual_instances.clone() {
  346. // We should have (N_CONNS outbound + N_CONNS inbound)
  347. // connections at this point.
  348. let channels = p2p.hosts().channels().await;
  349. assert!(channels.len() == N_CONNS * 2);
  350. }
  351. info!("========================================================");
  352. info!("Manual session successful! Shutting down manual test...");
  353. info!("========================================================");
  354. // ===========================================================
  355. // 8. Stop the P2P network
  356. // ===========================================================
  357. for p2p in manual_instances.clone() {
  358. p2p.clone().stop().await;
  359. }
  360. }