tests.rs 19 KB

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