mod.rs 11 KB

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