tests.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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 = 5;
  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 p2p_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. p2p_instances.push(p2p);
  109. }
  110. // Start the P2P network
  111. for p2p in p2p_instances.iter() {
  112. info!("========================================================");
  113. info!("Starting node={}", p2p.settings().external_addrs[0]);
  114. info!("========================================================");
  115. p2p.clone().start().await.unwrap();
  116. }
  117. p2p_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 p2p_instances = vec![];
  126. // Initialize the nodes
  127. for i in 0..N_NODES {
  128. // Everyone will connect to N_CONNS random peers.
  129. let mut peer_indexes_copy = peer_indexes.to_owned();
  130. peer_indexes_copy.remove(i);
  131. let peer_indexes_to_connect: Vec<_> =
  132. peer_indexes_copy.choose_multiple(rng, N_CONNS).collect();
  133. let mut peers = vec![];
  134. for peer_index in peer_indexes_to_connect {
  135. let port = starting_port + peer_index;
  136. peers.push(Url::parse(&format!("tcp://127.0.0.1:{}", port)).unwrap());
  137. }
  138. let p2p = spawn_node(
  139. vec![Url::parse(&format!("tcp://127.0.0.1:{}", starting_port + i)).unwrap()],
  140. vec![Url::parse(&format!("tcp://127.0.0.1:{}", starting_port + i)).unwrap()],
  141. vec![],
  142. peers,
  143. (starting_port + i).to_string(),
  144. ex.clone(),
  145. )
  146. .await;
  147. p2p_instances.push(p2p);
  148. }
  149. // Start the P2P network
  150. for p2p in p2p_instances.iter() {
  151. p2p.clone().start().await.unwrap();
  152. }
  153. info!("Waiting 5s until all peers connect");
  154. sleep(5).await;
  155. p2p_instances
  156. }*/
  157. /*async fn assert_hostlist_not_empty(
  158. p2p_instances: &Vec<Arc<P2p>>,
  159. rng: &mut ThreadRng,
  160. color: HostColor,
  161. ) {
  162. let random_node = p2p_instances.choose(rng).unwrap();
  163. assert!(!random_node.hosts().container.is_empty(color).await);
  164. }*/
  165. /*async fn assert_entry_exists(
  166. p2p_instances: &Vec<Arc<P2p>>,
  167. rng: &mut ThreadRng,
  168. color: HostColor,
  169. entry: &Url,
  170. ) {
  171. let mut urls = HashSet::new();
  172. let random_node = p2p_instances.choose(rng).unwrap();
  173. let external_addr = &random_node.settings().external_addrs[0];
  174. info!("Checking {} entry exists on {:?} list node={}", entry, color, external_addr);
  175. assert!(random_node.hosts().container.contains(color as usize, entry).await);
  176. }*/
  177. async fn get_random_gold_host(p2p_instances: &[Arc<P2p>], index: usize) -> ((Url, u64), usize) {
  178. let random_node = &p2p_instances[index];
  179. let external_addr = &random_node.settings().external_addrs[0];
  180. info!("========================================================");
  181. info!("Getting gold addr from node={}", external_addr);
  182. info!("========================================================");
  183. random_node.hosts().container.fetch_random(HostColor::Gold).await
  184. }
  185. async fn check_random_hostlist(p2p_instances: &Vec<Arc<P2p>>, rng: &mut ThreadRng) {
  186. let mut urls = HashSet::new();
  187. let random_node = p2p_instances.choose(rng).unwrap();
  188. let external_addr = &random_node.settings().external_addrs[0];
  189. info!("========================================================");
  190. info!("Checking node={}", external_addr);
  191. info!("========================================================");
  192. let greylist = random_node.hosts().container.fetch_all(HostColor::Grey).await;
  193. let whitelist = random_node.hosts().container.fetch_all(HostColor::White).await;
  194. let goldlist = random_node.hosts().container.fetch_all(HostColor::Gold).await;
  195. for (url, _) in greylist {
  196. assert!(urls.insert(url));
  197. }
  198. for (url, _) in whitelist {
  199. assert!(urls.insert(url));
  200. }
  201. for (url, _) in goldlist {
  202. assert!(urls.insert(url));
  203. }
  204. assert!(!urls.is_empty());
  205. }
  206. async fn kill_node(p2p_instances: &Vec<Arc<P2p>>, node: Url) {
  207. for p2p in p2p_instances {
  208. if p2p.settings().external_addrs[0] == node {
  209. info!("========================================================");
  210. info!("Shutting down node: {}", p2p.settings().external_addrs[0]);
  211. info!("========================================================");
  212. p2p.stop().await;
  213. }
  214. }
  215. }
  216. macro_rules! test_body {
  217. ($real_call:ident) => {
  218. init_logger();
  219. let ex = Arc::new(Executor::new());
  220. let ex_ = ex.clone();
  221. let (signal, shutdown) = channel::unbounded::<()>();
  222. // Run a thread for each node.
  223. easy_parallel::Parallel::new()
  224. .each(0..N_NODES, |_| future::block_on(ex.run(shutdown.recv())))
  225. .finish(|| {
  226. future::block_on(async {
  227. $real_call(ex_).await;
  228. drop(signal);
  229. })
  230. });
  231. };
  232. }
  233. #[test]
  234. fn p2p_test() {
  235. test_body!(p2p_test_real);
  236. }
  237. async fn p2p_test_real(ex: Arc<Executor<'static>>) {
  238. let mut rng = rand::thread_rng();
  239. // ============================================================
  240. // 1. Create a new seed node.
  241. // ============================================================
  242. //let peer_indexes: Vec<usize> = (0..N_NODES).collect();
  243. let seed_addr = Url::parse(SEED).unwrap();
  244. let settings = Settings {
  245. localnet: true,
  246. inbound_addrs: vec![seed_addr.clone()],
  247. outbound_connections: 0,
  248. inbound_connections: usize::MAX,
  249. seeds: vec![],
  250. peers: vec![],
  251. allowed_transports: vec!["tcp".to_string()],
  252. greylist_refinery_interval: 12,
  253. node_id: "seed".to_string(),
  254. ..Default::default()
  255. };
  256. let seed = P2p::new(settings, ex.clone()).await;
  257. info!("========================================================");
  258. info!("Starting seed node on {}", SEED);
  259. info!("========================================================");
  260. seed.clone().start().await.unwrap();
  261. // ============================================================
  262. // 2. Spawn outbound nodes that will connect to the seed node.
  263. // ============================================================
  264. let p2p_instances = spawn_seed_session(43200, ex.clone()).await;
  265. info!("========================================================");
  266. info!("Waiting 10s for all peers to reach the seed node");
  267. info!("========================================================");
  268. sleep(10).await;
  269. // ===========================================================
  270. // 3. Assert that all nodes have shared their external addr
  271. // with the seed node.
  272. // ===========================================================
  273. let greylist = seed.hosts().container.fetch_all(HostColor::Grey).await;
  274. assert!(greylist.len() == N_NODES);
  275. info!("========================================================");
  276. info!("Seedsync session successful!");
  277. info!("========================================================");
  278. info!("========================================================");
  279. info!("Waiting 5s for seed node refinery to kick in...");
  280. info!("========================================================");
  281. sleep(5).await;
  282. // ===========================================================
  283. // 4. Assert that seed node has at least one whitelist entry,
  284. // indicating that the refinery process is happening correctly.
  285. // ===========================================================
  286. assert!(!seed.hosts().container.is_empty(HostColor::White).await);
  287. info!("========================================================");
  288. info!("Seed node refinery operating successfully!");
  289. info!("========================================================");
  290. info!("========================================================");
  291. info!("Waiting 5s for peers to propagate...");
  292. info!("========================================================");
  293. sleep(5).await;
  294. // ===========================================================
  295. // 5. Select a random peer and ensure that its hostlist is not
  296. // empty. This ensures the seed node is sharing whitelisted
  297. // nodes around the network.
  298. // ===========================================================
  299. check_random_hostlist(&p2p_instances, &mut rng).await;
  300. info!("========================================================");
  301. info!("Peer successfully received addrs!");
  302. info!("========================================================");
  303. // ===========================================================
  304. // 6. Select a random gold peer from one of the nodes and kill
  305. // it.
  306. // ===========================================================
  307. info!("========================================================");
  308. info!("Selecting a random gold entry...");
  309. info!("========================================================");
  310. let random_node_index = rand::thread_rng().gen_range(0..p2p_instances.len());
  311. let ((addr, _), _) = get_random_gold_host(&p2p_instances, random_node_index).await;
  312. kill_node(&p2p_instances, addr.clone()).await;
  313. info!("========================================================");
  314. info!("Waiting for greylist downgrade sequence to occur...");
  315. info!("========================================================");
  316. // ===========================================================
  317. // 7. Verify the peer has been removed from the Gold list.
  318. // ===========================================================
  319. p2p_instances[random_node_index]
  320. .hosts()
  321. .container
  322. .contains(HostColor::Grey as usize, &addr)
  323. .await;
  324. info!("========================================================");
  325. info!("Greylist downgrade occured successfully!");
  326. info!("========================================================");
  327. // ===========================================================
  328. // 8. Stop the P2P network
  329. // ===========================================================
  330. for p2p in p2p_instances.iter() {
  331. p2p.clone().stop().await;
  332. }
  333. }