mod.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. use std::sync::Arc;
  19. use darkfi::{
  20. net::Settings,
  21. rpc::settings::RpcSettings,
  22. util::logger::{setup_test_logger, Level},
  23. validator::{consensus::Fork, utils::best_fork_index, verification::verify_block},
  24. Result,
  25. };
  26. use darkfi_contract_test_harness::init_logger;
  27. use darkfi_sdk::num_traits::One;
  28. use num_bigint::BigUint;
  29. use smol::Executor;
  30. use tracing::warn;
  31. use url::Url;
  32. mod harness;
  33. use harness::{generate_node, Harness, HarnessConfig};
  34. mod forks;
  35. mod sync_forks;
  36. mod unproposed_txs;
  37. mod metering;
  38. async fn sync_blocks_real(ex: Arc<Executor<'static>>) -> Result<()> {
  39. init_logger();
  40. // Initialize harness in testing mode
  41. let pow_target = 120;
  42. let pow_fixed_difficulty = Some(BigUint::one());
  43. let config = HarnessConfig {
  44. pow_target,
  45. pow_fixed_difficulty: pow_fixed_difficulty.clone(),
  46. confirmation_threshold: 3,
  47. alice_url: "tcp+tls://127.0.0.1:18340".to_string(),
  48. bob_url: "tcp+tls://127.0.0.1:18341".to_string(),
  49. };
  50. let th = Harness::new(config, true, &ex).await?;
  51. // Generate a fork to create new blocks
  52. let mut fork = th.alice.validator.consensus.forks.read().await[0].full_clone()?;
  53. // Generate next blocks
  54. let block1 = th.generate_next_block(&mut fork).await?;
  55. let block2 = th.generate_next_block(&mut fork).await?;
  56. let block3 = th.generate_next_block(&mut fork).await?;
  57. let block4 = th.generate_next_block(&mut fork).await?;
  58. // Add them to nodes
  59. th.add_blocks(&vec![block1, block2.clone(), block3.clone(), block4]).await?;
  60. // Nodes must have one fork with 2 blocks
  61. th.validate_fork_chains(1, vec![2]).await;
  62. // Extend current fork sequence
  63. let block5 = th.generate_next_block(&mut fork).await?;
  64. // Create a new fork extending canonical
  65. fork = Fork::new(
  66. th.alice.validator.consensus.blockchain.clone(),
  67. th.alice.validator.consensus.module.read().await.clone(),
  68. )
  69. .await?;
  70. // Append block3 to fork and generate the next one
  71. verify_block(
  72. &fork.overlay,
  73. &fork.module,
  74. &mut fork.state_monotree,
  75. &block3,
  76. &block2,
  77. th.alice.validator.verify_fees,
  78. )
  79. .await?;
  80. let block6 = th.generate_next_block(&mut fork).await?;
  81. // Add them to nodes
  82. th.add_blocks(&vec![block5, block6]).await?;
  83. // Grab current best fork index
  84. let forks = th.alice.validator.consensus.forks.read().await;
  85. // If index corresponds to the small fork, confirmation
  86. // did not occur, as it's size is not over the threshold.
  87. let small_best = best_fork_index(&forks)? == 1;
  88. drop(forks);
  89. if small_best {
  90. // Nodes must have one fork with 3 blocks and one with 2 blocks
  91. th.validate_fork_chains(2, vec![3, 2]).await;
  92. } else {
  93. // Nodes must have one fork with 2 blocks and one with 1 block
  94. th.validate_fork_chains(2, vec![2, 1]).await;
  95. }
  96. // We are going to create a third node and try to sync from Bob
  97. let mut settings = Settings { localnet: true, inbound_connections: 3, ..Default::default() };
  98. let charlie_url = Url::parse("tcp+tls://127.0.0.1:18342")?;
  99. settings.inbound_addrs = vec![charlie_url];
  100. let bob_url = th.bob.p2p_handler.p2p.settings().read().await.inbound_addrs[0].clone();
  101. settings.peers = vec![bob_url];
  102. let charlie = generate_node(
  103. &th.vks,
  104. &th.validator_config,
  105. &settings,
  106. &ex,
  107. false,
  108. Some((block2.header.height, block2.hash())),
  109. )
  110. .await?;
  111. // Verify node synced
  112. let alice = &th.alice.validator;
  113. let charlie = &charlie.validator;
  114. assert_eq!(alice.blockchain.len(), charlie.blockchain.len());
  115. assert!(charlie.blockchain.headers.is_empty_sync());
  116. // Node must have just the best fork
  117. let forks = alice.consensus.forks.read().await;
  118. let best_fork = &forks[best_fork_index(&forks)?];
  119. let charlie_forks = charlie.consensus.forks.read().await;
  120. assert_eq!(charlie_forks.len(), 1);
  121. assert_eq!(charlie_forks[0].proposals.len(), best_fork.proposals.len());
  122. assert_eq!(charlie_forks[0].diffs.len(), best_fork.diffs.len());
  123. drop(forks);
  124. drop(charlie_forks);
  125. // Extend the small fork sequence and add it to nodes
  126. th.add_blocks(&vec![th.generate_next_block(&mut fork).await?]).await?;
  127. // Nodes must have two forks with 2 blocks each
  128. th.validate_fork_chains(2, vec![2, 2]).await;
  129. // Check charlie has the correct forks
  130. let charlie_forks = charlie.consensus.forks.read().await;
  131. if small_best {
  132. // If Charlie already had the small fork as its best,
  133. // it will have a single fork with 3 blocks.
  134. assert_eq!(charlie_forks.len(), 1);
  135. assert_eq!(charlie_forks[0].proposals.len(), 3);
  136. assert_eq!(charlie_forks[0].diffs.len(), 3);
  137. } else {
  138. // Charlie didn't originaly have the fork, but it
  139. // should be synced when its proposal was received
  140. assert_eq!(charlie_forks.len(), 2);
  141. assert_eq!(charlie_forks[0].proposals.len(), 2);
  142. assert_eq!(charlie_forks[0].diffs.len(), 2);
  143. assert_eq!(charlie_forks[1].proposals.len(), 2);
  144. assert_eq!(charlie_forks[1].diffs.len(), 2);
  145. }
  146. drop(charlie_forks);
  147. // Since the don't know if the second fork was the best,
  148. // we extend it until it becomes best and a confirmation
  149. // occurred.
  150. loop {
  151. th.add_blocks(&vec![th.generate_next_block(&mut fork).await?]).await?;
  152. // Check if confirmation occured
  153. if th.alice.validator.blockchain.len() > 4 {
  154. break
  155. }
  156. }
  157. // Nodes must have executed confirmation, so we validate their chains
  158. th.validate_chains(4 + (fork.proposals.len() - 2)).await?;
  159. let bob = &th.bob.validator;
  160. let last = alice.blockchain.last()?.1;
  161. assert_eq!(last, fork.proposals[fork.proposals.len() - 3]);
  162. assert_eq!(last, bob.blockchain.last()?.1);
  163. // Nodes must have one fork with 2 blocks
  164. th.validate_fork_chains(1, vec![2]).await;
  165. let last_proposal = alice.consensus.forks.read().await[0].proposals[1];
  166. assert_eq!(last_proposal, *fork.proposals.last().unwrap());
  167. assert_eq!(last_proposal, bob.consensus.forks.read().await[0].proposals[1]);
  168. // Same for Charlie
  169. charlie.confirmation().await?;
  170. charlie.validate_blockchain(pow_target, pow_fixed_difficulty).await?;
  171. assert_eq!(alice.blockchain.len(), charlie.blockchain.len());
  172. assert!(charlie.blockchain.headers.is_empty_sync());
  173. assert_eq!(last, charlie.blockchain.last()?.1);
  174. let charlie_forks = charlie.consensus.forks.read().await;
  175. assert_eq!(charlie_forks.len(), 1);
  176. assert_eq!(charlie_forks[0].proposals.len(), 2);
  177. assert_eq!(charlie_forks[0].diffs.len(), 2);
  178. assert_eq!(last_proposal, charlie_forks[0].proposals[1]);
  179. // Thanks for reading
  180. Ok(())
  181. }
  182. #[test]
  183. fn sync_blocks() -> Result<()> {
  184. let ex = Arc::new(Executor::new());
  185. let (signal, shutdown) = smol::channel::unbounded::<()>();
  186. easy_parallel::Parallel::new().each(0..4, |_| smol::block_on(ex.run(shutdown.recv()))).finish(
  187. || {
  188. smol::block_on(async {
  189. sync_blocks_real(ex.clone()).await.unwrap();
  190. drop(signal);
  191. })
  192. },
  193. );
  194. Ok(())
  195. }
  196. #[test]
  197. /// Test the programmatic control of `Darkfid`.
  198. ///
  199. /// First we initialize a daemon, start it and then perform
  200. /// couple of restarts to verify everything works as expected.
  201. fn darkfid_programmatic_control() -> Result<()> {
  202. // We check this error so we can execute same file tests in parallel,
  203. // otherwise second one fails to init logger here.
  204. if setup_test_logger(
  205. &[],
  206. false,
  207. Level::Info,
  208. //Level::Verbose,
  209. //Level::Debug,
  210. //Level::Trace
  211. )
  212. .is_err()
  213. {
  214. warn!(target: "darkfid_programmatic_control", "Logger already initialized");
  215. }
  216. // Create an executor and communication signals
  217. let ex = Arc::new(smol::Executor::new());
  218. let (signal, shutdown) = smol::channel::unbounded::<()>();
  219. easy_parallel::Parallel::new().each(0..1, |_| smol::block_on(ex.run(shutdown.recv()))).finish(
  220. || {
  221. smol::block_on(async {
  222. // Daemon configuration
  223. let mut genesis_block = darkfi::blockchain::BlockInfo::default();
  224. let producer_tx = genesis_block.txs.pop().unwrap();
  225. genesis_block.append_txs(vec![producer_tx]);
  226. let sled_db = sled_overlay::sled::Config::new().temporary(true).open().unwrap();
  227. let (_, vks) = darkfi_contract_test_harness::vks::get_cached_pks_and_vks().unwrap();
  228. darkfi_contract_test_harness::vks::inject(&sled_db, &vks).unwrap();
  229. let overlay = darkfi::blockchain::BlockchainOverlay::new(
  230. &darkfi::blockchain::Blockchain::new(&sled_db).unwrap(),
  231. )
  232. .unwrap();
  233. darkfi::validator::utils::deploy_native_contracts(&overlay, 20).await.unwrap();
  234. genesis_block.header.state_root = overlay
  235. .lock()
  236. .unwrap()
  237. .contracts
  238. .get_state_monotree()
  239. .unwrap()
  240. .get_headroot()
  241. .unwrap()
  242. .unwrap();
  243. let bootstrap = genesis_block.header.timestamp.inner();
  244. let config = darkfi::validator::ValidatorConfig {
  245. confirmation_threshold: 1,
  246. pow_target: 20,
  247. pow_fixed_difficulty: Some(BigUint::one()),
  248. genesis_block,
  249. verify_fees: false,
  250. };
  251. let consensus_config = crate::ConsensusInitTaskConfig {
  252. skip_sync: true,
  253. checkpoint_height: None,
  254. checkpoint: None,
  255. miner: false,
  256. recipient: None,
  257. spend_hook: None,
  258. user_data: None,
  259. bootstrap,
  260. };
  261. let rpc_settings = RpcSettings {
  262. listen: Url::parse("tcp://127.0.0.1:8240").unwrap(),
  263. ..RpcSettings::default()
  264. };
  265. // Initialize a daemon
  266. let daemon = crate::Darkfid::init(
  267. &sled_db,
  268. &config,
  269. &darkfi::net::Settings::default(),
  270. &None,
  271. &None,
  272. &ex,
  273. )
  274. .await
  275. .unwrap();
  276. // Start it
  277. daemon.start(&ex, &rpc_settings, &None, &consensus_config).await.unwrap();
  278. // Stop it
  279. daemon.stop().await.unwrap();
  280. // Start it again
  281. daemon.start(&ex, &rpc_settings, &None, &consensus_config).await.unwrap();
  282. // Stop it
  283. daemon.stop().await.unwrap();
  284. // Shutdown entirely
  285. drop(signal);
  286. })
  287. },
  288. );
  289. Ok(())
  290. }