tests.rs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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 test --release --features=net --lib p2p -- --include-ignored
  19. use std::{collections::HashSet, net::TcpListener, panic, sync::Arc};
  20. use darkfi_serial::{async_trait, SerialDecodable, SerialEncodable};
  21. use rand::{prelude::SliceRandom, rngs::ThreadRng, Rng};
  22. use smol::{channel, future, Executor};
  23. use tracing::{error, info, warn};
  24. use url::Url;
  25. use crate::{
  26. net::{
  27. hosts::HostColor,
  28. message::{GetAddrsMessage, Message},
  29. metering::{MeteringConfiguration, DEFAULT_METERING_CONFIGURATION},
  30. P2p, Settings,
  31. },
  32. system::sleep,
  33. util::logger::{setup_test_logger, Level},
  34. };
  35. fn init_logger() {
  36. let ignored_targets = [
  37. "sled",
  38. "net::protocol_ping",
  39. "net::channel::subscribe_stop()",
  40. "net::hosts",
  41. "net::session",
  42. "net::outbound_session",
  43. "net::inbound_session",
  44. "net::message_publisher",
  45. "net::protocol_address",
  46. "net::protocol_version",
  47. "net::protocol_registry",
  48. "net::protocol_jobs_manager",
  49. "net::channel::send()",
  50. "net::channel::start()",
  51. "net::channel::handle_stop()",
  52. "net::channel::subscribe_msg()",
  53. "net::channel::main_receive_loop()",
  54. "net::tcp",
  55. ];
  56. // We check this error so we can execute same file tests in parallel,
  57. // otherwise second one fails to init logger here.
  58. if setup_test_logger(
  59. &ignored_targets,
  60. false,
  61. //Level::Info,
  62. Level::Verbose,
  63. //Level::Debug,
  64. //Level::Trace,
  65. )
  66. .is_err()
  67. {
  68. warn!(target: "test_harness", "Logger already initialized");
  69. }
  70. }
  71. fn get_random_available_port() -> usize {
  72. let listener = TcpListener::bind("127.0.0.1:0").unwrap();
  73. let port = listener.local_addr().unwrap().port();
  74. drop(listener);
  75. port.into()
  76. }
  77. fn get_unique_ports(n_nodes: usize) -> Vec<usize> {
  78. let mut ports = HashSet::new();
  79. while ports.len() < n_nodes {
  80. ports.insert(get_random_available_port());
  81. }
  82. ports.into_iter().collect()
  83. }
  84. async fn spawn_seed_session(
  85. seed_addr: Url,
  86. ex: Arc<Executor<'static>>,
  87. n_nodes: usize,
  88. ) -> Vec<Arc<P2p>> {
  89. info!("========================================================");
  90. info!("Initializing outbound nodes...");
  91. info!("========================================================");
  92. let mut outbound_instances = vec![];
  93. let ports = get_unique_ports(n_nodes);
  94. for port in ports {
  95. let settings = Settings {
  96. localnet: true,
  97. inbound_addrs: vec![Url::parse(&format!("tcp://127.0.0.1:{port}")).unwrap()],
  98. external_addrs: vec![Url::parse(&format!("tcp://127.0.0.1:{port}")).unwrap()],
  99. outbound_connections: 2,
  100. outbound_peer_discovery_cooloff_time: 2,
  101. outbound_connect_timeout: 2,
  102. inbound_connections: usize::MAX,
  103. greylist_refinery_interval: 15,
  104. peers: vec![],
  105. seeds: vec![seed_addr.clone()],
  106. node_id: (port).to_string(),
  107. allowed_transports: vec!["tcp".to_string()],
  108. ..Default::default()
  109. };
  110. let p2p = P2p::new(settings, ex.clone()).await.unwrap();
  111. outbound_instances.push(p2p);
  112. }
  113. outbound_instances
  114. }
  115. async fn spawn_manual_session(
  116. ex: Arc<Executor<'static>>,
  117. n_nodes: usize,
  118. n_conns: usize,
  119. ) -> Vec<Arc<P2p>> {
  120. info!("========================================================");
  121. info!("Initializing manual nodes...");
  122. info!("========================================================");
  123. let mut manual_instances = vec![];
  124. let mut rng = rand::thread_rng();
  125. let ports = get_unique_ports(n_nodes);
  126. for i in 0..n_nodes {
  127. let mut peer_indexes_copy: Vec<usize> = (0..n_nodes).collect();
  128. peer_indexes_copy.remove(i);
  129. let peer_indexes_to_connect: Vec<_> =
  130. peer_indexes_copy.choose_multiple(&mut rng, n_conns).collect();
  131. let mut peers = vec![];
  132. for &peer_index in peer_indexes_to_connect {
  133. let port = ports[peer_index];
  134. peers.push(Url::parse(&format!("tcp://127.0.0.1:{port}")).unwrap());
  135. }
  136. let inbound_port = ports[i];
  137. let settings = Settings {
  138. localnet: true,
  139. inbound_addrs: vec![Url::parse(&format!("tcp://127.0.0.1:{inbound_port}")).unwrap()],
  140. external_addrs: vec![Url::parse(&format!("tcp://127.0.0.1:{inbound_port}")).unwrap()],
  141. outbound_connections: 2,
  142. outbound_peer_discovery_cooloff_time: 2,
  143. outbound_connect_timeout: 2,
  144. inbound_connections: usize::MAX,
  145. greylist_refinery_interval: 15,
  146. peers,
  147. seeds: vec![],
  148. node_id: inbound_port.to_string(),
  149. allowed_transports: vec!["tcp".to_string()],
  150. ..Default::default()
  151. };
  152. let p2p = P2p::new(settings, ex.clone()).await.unwrap();
  153. manual_instances.push(p2p);
  154. }
  155. manual_instances
  156. }
  157. async fn get_random_gold_host(
  158. outbound_instances: &[Arc<P2p>],
  159. index: usize,
  160. ) -> ((Url, u64), usize) {
  161. let random_node = &outbound_instances[index];
  162. let hosts = random_node.hosts();
  163. let external_addr = random_node.settings().read().await.external_addrs[0].clone();
  164. info!("========================================================");
  165. info!("Getting gold addr from node={external_addr}");
  166. info!("========================================================");
  167. let list = hosts.container.hostlists[HostColor::Gold as usize].read().unwrap();
  168. assert!(!list.is_empty());
  169. let position = rand::thread_rng().gen_range(0..list.len());
  170. let entry = &list[position];
  171. (entry.clone(), position)
  172. }
  173. async fn _check_random_hostlist(outbound_instances: &[Arc<P2p>], rng: &mut ThreadRng) {
  174. let mut urls = HashSet::new();
  175. let random_node = outbound_instances.choose(rng).unwrap();
  176. let external_addr = random_node.settings().read().await.external_addrs[0].clone();
  177. info!("========================================================");
  178. info!("Checking node={external_addr}");
  179. info!("========================================================");
  180. let greylist = random_node.hosts().container.fetch_all(HostColor::Grey);
  181. let whitelist = random_node.hosts().container.fetch_all(HostColor::White);
  182. let goldlist = random_node.hosts().container.fetch_all(HostColor::Gold);
  183. for (url, _) in greylist {
  184. assert!(urls.insert(url));
  185. }
  186. for (url, _) in whitelist {
  187. assert!(urls.insert(url));
  188. }
  189. for (url, _) in goldlist {
  190. assert!(urls.insert(url));
  191. }
  192. assert!(!urls.is_empty());
  193. }
  194. async fn check_all_hostlist(outbound_instances: &Vec<Arc<P2p>>) {
  195. for node in outbound_instances {
  196. let external_addr = &node.settings().read().await.external_addrs[0].clone();
  197. info!("========================================================");
  198. info!("Checking node={external_addr}");
  199. info!("========================================================");
  200. let mut urls = HashSet::new();
  201. let greylist = node.hosts().container.fetch_all(HostColor::Grey);
  202. let whitelist = node.hosts().container.fetch_all(HostColor::White);
  203. let goldlist = node.hosts().container.fetch_all(HostColor::Gold);
  204. for (url, _) in greylist {
  205. assert!(urls.insert(url));
  206. }
  207. for (url, _) in whitelist {
  208. assert!(urls.insert(url));
  209. }
  210. for (url, _) in goldlist {
  211. assert!(urls.insert(url));
  212. }
  213. assert!(!urls.is_empty());
  214. }
  215. }
  216. async fn kill_node(outbound_instances: &Vec<Arc<P2p>>, node: Url) {
  217. for p2p in outbound_instances {
  218. if p2p.settings().read().await.external_addrs[0] == node {
  219. info!("========================================================");
  220. info!("Shutting down node: {}", p2p.settings().read().await.external_addrs[0]);
  221. info!("========================================================");
  222. p2p.stop().await;
  223. }
  224. }
  225. }
  226. macro_rules! test_body {
  227. ($real_call:ident, $threads:expr) => {
  228. init_logger();
  229. let ex = Arc::new(Executor::new());
  230. let ex_ = ex.clone();
  231. let (signal, shutdown) = channel::unbounded::<()>();
  232. panic::set_hook(Box::new(|panic_info| {
  233. error!("Panic occurred: {:?}", panic_info);
  234. }));
  235. // Run a thread for each node.
  236. easy_parallel::Parallel::new()
  237. .each(0..$threads, |_| {
  238. let result = std::panic::catch_unwind(|| {
  239. let res = future::block_on(ex.run(shutdown.recv()));
  240. res
  241. });
  242. if let Err(err) = result {
  243. error!("Thread panicked: {:?}", err);
  244. }
  245. })
  246. .finish(|| {
  247. future::block_on(async {
  248. $real_call(ex_).await;
  249. drop(signal);
  250. });
  251. });
  252. };
  253. }
  254. #[test]
  255. fn p2p_test() {
  256. test_body!(p2p_test_real, 5);
  257. }
  258. async fn p2p_test_real(ex: Arc<Executor<'static>>) {
  259. // Number of nodes to spawn and number of peers each node connects to
  260. const N_NODES: usize = 5;
  261. const N_CONNS: usize = 4;
  262. // ============================================================
  263. // 1. Create a new seed node.
  264. // ============================================================
  265. let seed_port = get_random_available_port();
  266. let seed_addr = Url::parse(&format!("tcp://127.0.0.1:{seed_port}")).unwrap();
  267. let settings = Settings {
  268. localnet: true,
  269. inbound_addrs: vec![seed_addr.clone()],
  270. outbound_connections: 0,
  271. inbound_connections: usize::MAX,
  272. seeds: vec![],
  273. peers: vec![],
  274. allowed_transports: vec!["tcp".to_string()],
  275. greylist_refinery_interval: 12,
  276. node_id: "seed".to_string(),
  277. ..Default::default()
  278. };
  279. let seed = P2p::new(settings, ex.clone()).await.unwrap();
  280. info!("========================================================");
  281. info!("Starting seed node on {seed_addr}");
  282. info!("========================================================");
  283. seed.clone().start().await.unwrap();
  284. // ============================================================
  285. // 2. Spawn outbound nodes that will connect to the seed node.
  286. // ============================================================
  287. let outbound_instances = spawn_seed_session(seed_addr, ex.clone(), N_NODES).await;
  288. for p2p in &outbound_instances {
  289. info!("========================================================");
  290. info!("Starting node={}", p2p.settings().read().await.external_addrs[0]);
  291. info!("========================================================");
  292. p2p.clone().start().await.unwrap();
  293. }
  294. info!("========================================================");
  295. info!("Waiting 10s for all peers to reach the seed node");
  296. info!("========================================================");
  297. sleep(10).await;
  298. // ===========================================================
  299. // 3. Assert that all nodes have shared their external addr
  300. // with the seed node.
  301. // ===========================================================
  302. let greylist = seed.hosts().container.fetch_all(HostColor::Grey);
  303. assert!(greylist.len() == N_NODES);
  304. info!("========================================================");
  305. info!("Seedsync session successful!");
  306. info!("========================================================");
  307. info!("========================================================");
  308. info!("Waiting 5s for seed node refinery to kick in...");
  309. info!("========================================================");
  310. sleep(5).await;
  311. // ===========================================================
  312. // 4. Assert that seed node has at least one whitelist entry,
  313. // indicating that the refinery process is happening correctly.
  314. // ===========================================================
  315. assert!(!seed.hosts().container.is_empty(HostColor::White));
  316. info!("========================================================");
  317. info!("Checking seed={}", seed.settings().read().await.inbound_addrs[0]);
  318. info!("========================================================");
  319. let mut urls = HashSet::new();
  320. let greylist = seed.hosts().container.fetch_all(HostColor::Grey);
  321. let whitelist = seed.hosts().container.fetch_all(HostColor::White);
  322. let goldlist = seed.hosts().container.fetch_all(HostColor::Gold);
  323. for (url, _) in greylist {
  324. info!("Found grey url: {url}");
  325. assert!(urls.insert(url));
  326. }
  327. for (url, _) in whitelist {
  328. info!("Found white url: {url}");
  329. assert!(urls.insert(url));
  330. }
  331. for (url, _) in goldlist {
  332. info!("Found gold url: {url}");
  333. assert!(urls.insert(url));
  334. }
  335. assert!(!urls.is_empty());
  336. info!("========================================================");
  337. info!("Seed node refinery operating successfully!");
  338. info!("========================================================");
  339. info!("========================================================");
  340. info!("Waiting 10s for seed refinery...");
  341. info!("========================================================");
  342. sleep(10).await;
  343. let whitelist = seed.hosts().container.fetch_all(HostColor::White);
  344. assert!(whitelist.len() >= 2);
  345. // ===========================================================
  346. // 5. Select a random peer and ensure that its hostlist is not
  347. // empty. This ensures the seed node is sharing whitelisted
  348. // nodes around the network.
  349. // ===========================================================
  350. check_all_hostlist(&outbound_instances).await;
  351. info!("========================================================");
  352. info!("Peers successfully received addrs!");
  353. info!("========================================================");
  354. info!("========================================================");
  355. info!("Waiting 5s for outbound loop to connect...");
  356. info!("========================================================");
  357. sleep(5).await;
  358. // ===========================================================
  359. // 6. Select a random gold peer from one of the nodes and kill
  360. // it.
  361. // ===========================================================
  362. info!("========================================================");
  363. info!("Selecting a random gold entry...");
  364. info!("========================================================");
  365. let random_node_index = rand::thread_rng().gen_range(0..outbound_instances.len());
  366. let ((addr, _), _) = get_random_gold_host(&outbound_instances, random_node_index).await;
  367. kill_node(&outbound_instances, addr.clone()).await;
  368. info!("========================================================");
  369. info!("Waiting for greylist downgrade sequence to occur...");
  370. info!("========================================================");
  371. // ===========================================================
  372. // 7. Verify the peer has been removed from the Gold list.
  373. // ===========================================================
  374. outbound_instances[random_node_index]
  375. .hosts()
  376. .container
  377. .contains(HostColor::Grey as usize, &addr);
  378. info!("========================================================");
  379. info!("Greylist downgrade occured successfully!");
  380. info!("========================================================");
  381. info!("========================================================");
  382. info!("Seed session successful! Shutting down seed test...");
  383. info!("========================================================");
  384. // ===========================================================
  385. // 8. Stop the P2P network
  386. // ===========================================================
  387. for p2p in outbound_instances.iter() {
  388. p2p.clone().stop().await;
  389. }
  390. seed.clone().stop().await;
  391. info!("========================================================");
  392. info!("Seed test shutdown complete! Starting manual test...");
  393. info!("========================================================");
  394. let manual_instances = spawn_manual_session(ex.clone(), N_NODES, N_CONNS).await;
  395. for p2p in &manual_instances {
  396. info!("========================================================");
  397. info!("Starting node={}", p2p.settings().read().await.external_addrs[0]);
  398. info!("========================================================");
  399. p2p.clone().start().await.unwrap();
  400. }
  401. info!("========================================================");
  402. info!("Waiting 5s for all manual peers to connect");
  403. info!("========================================================");
  404. sleep(5).await;
  405. info!("========================================================");
  406. info!("Checking manual nodes connected successfully...");
  407. info!("========================================================");
  408. for p2p in manual_instances.clone() {
  409. // We should have (N_CONNS outbound + N_CONNS inbound)
  410. // connections at this point.
  411. info!("========================================================");
  412. info!("Checking manual node={}", p2p.settings().read().await.node_id);
  413. info!("========================================================");
  414. let peers = p2p.hosts().peers();
  415. assert!(peers.len() == N_CONNS * 2);
  416. }
  417. info!("========================================================");
  418. info!("Manual session successful! Shutting down manual test...");
  419. info!("========================================================");
  420. // ===========================================================
  421. // 8. Stop the P2P network
  422. // ===========================================================
  423. for p2p in manual_instances.clone() {
  424. p2p.clone().stop().await;
  425. }
  426. }
  427. #[test]
  428. fn p2p_channel_unsupported_message_type_gets_banned() {
  429. test_body!(p2p_channel_unsupported_message_type_gets_banned_real, 2);
  430. }
  431. async fn p2p_channel_unsupported_message_type_gets_banned_real(ex: Arc<Executor<'static>>) {
  432. // Test with two nodes directly connected to each other
  433. let manual_instances = spawn_manual_session(ex.clone(), 2, 1).await;
  434. for p2p in &manual_instances {
  435. p2p.clone().start().await.unwrap();
  436. }
  437. // Let's wait for the nodes to connect to each other
  438. sleep(5).await;
  439. let node1_p2p = manual_instances[0].clone();
  440. let node2_p2p = manual_instances[1].clone();
  441. let channel = node1_p2p.hosts().channels().first().unwrap().clone();
  442. // Create a new message type
  443. #[derive(SerialEncodable, SerialDecodable)]
  444. struct CustomMessage(u32);
  445. crate::impl_p2p_message!(
  446. CustomMessage,
  447. "UnsupportedMessage",
  448. 0,
  449. 0,
  450. DEFAULT_METERING_CONFIGURATION
  451. );
  452. let instance = CustomMessage(23);
  453. channel.send(&instance).await.unwrap();
  454. sleep(1).await;
  455. // Node1 should be banned by Node2
  456. assert_eq!(node2_p2p.hosts().container.fetch_all(HostColor::Black).len(), 1);
  457. node1_p2p.stop().await;
  458. node2_p2p.stop().await;
  459. }
  460. #[test]
  461. fn p2p_channel_invalid_command_length_gets_banned() {
  462. test_body!(p2p_channel_invalid_command_length_gets_banned_real, 2);
  463. }
  464. async fn p2p_channel_invalid_command_length_gets_banned_real(ex: Arc<Executor<'static>>) {
  465. // Test with two nodes directly connected to each other
  466. let manual_instances = spawn_manual_session(ex.clone(), 2, 1).await;
  467. for p2p in &manual_instances {
  468. p2p.clone().start().await.unwrap();
  469. }
  470. // Let's wait for the nodes to connect to each other
  471. sleep(5).await;
  472. let node1_p2p = manual_instances[0].clone();
  473. let node2_p2p = manual_instances[1].clone();
  474. let channel = node1_p2p.hosts().channels().first().unwrap().clone();
  475. // Create a custom message that has invalid length command name
  476. #[derive(SerialEncodable, SerialDecodable)]
  477. struct CustomMessage(u32);
  478. // The length of COMMAND_NAME is greater than message::MAX_COMMAND_LENGTH, this one is 256
  479. const COMMAND_NAME: &str =
  480. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\
  481. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\
  482. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
  483. crate::impl_p2p_message!(CustomMessage, &COMMAND_NAME, 0, 0, DEFAULT_METERING_CONFIGURATION);
  484. let instance = CustomMessage(23);
  485. channel.send(&instance).await.unwrap();
  486. sleep(1).await;
  487. // Node1 should be banned by Node2
  488. assert_eq!(node2_p2p.hosts().container.fetch_all(HostColor::Black).len(), 1);
  489. node1_p2p.stop().await;
  490. node2_p2p.stop().await;
  491. }
  492. #[test]
  493. fn p2p_channel_invalid_message_length_gets_banned() {
  494. test_body!(p2p_channel_invalid_message_length_gets_banned_real, 2);
  495. }
  496. async fn p2p_channel_invalid_message_length_gets_banned_real(ex: Arc<Executor<'static>>) {
  497. // Test with two nodes directly connected to each other
  498. let manual_instances = spawn_manual_session(ex.clone(), 2, 1).await;
  499. for p2p in &manual_instances {
  500. p2p.clone().start().await.unwrap();
  501. }
  502. // Let's wait for the nodes to connect to each other
  503. sleep(5).await;
  504. let node1_p2p = manual_instances[0].clone();
  505. let node2_p2p = manual_instances[1].clone();
  506. let channel = node1_p2p.hosts().channels().first().unwrap().clone();
  507. // Let's create a GetAddrsMessage that will be over the GET_ADDRS_MAX_BYTES threshold
  508. let message = GetAddrsMessage { max: 20, transports: vec!["tor".to_string(); 256] };
  509. channel.send(&message).await.unwrap();
  510. sleep(1).await;
  511. // Node1 should be banned by Node2
  512. assert_eq!(node2_p2p.hosts().container.fetch_all(HostColor::Black).len(), 1);
  513. node1_p2p.stop().await;
  514. node2_p2p.stop().await;
  515. }