tests.rs 19 KB

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