mod.rs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. use std::sync::Arc;
  19. use darkfi::{net::Settings, validator::utils::best_fork_index, Result};
  20. use darkfi_contract_test_harness::init_logger;
  21. use darkfi_sdk::num_traits::One;
  22. use num_bigint::BigUint;
  23. use smol::Executor;
  24. use url::Url;
  25. mod harness;
  26. use harness::{generate_node, Harness, HarnessConfig};
  27. mod forks;
  28. mod sync_forks;
  29. async fn sync_blocks_real(ex: Arc<Executor<'static>>) -> Result<()> {
  30. init_logger();
  31. // Initialize harness in testing mode
  32. let pow_target = 90;
  33. let pow_fixed_difficulty = Some(BigUint::one());
  34. let config = HarnessConfig {
  35. pow_target,
  36. pow_fixed_difficulty: pow_fixed_difficulty.clone(),
  37. finalization_threshold: 3,
  38. alice_initial: 1000,
  39. bob_initial: 500,
  40. };
  41. let th = Harness::new(config, true, &ex).await?;
  42. // Retrieve genesis block
  43. let genesis = th.alice.validator.blockchain.last_block()?;
  44. // Generate next blocks
  45. let block1 = th.generate_next_block(&genesis).await?;
  46. let block2 = th.generate_next_block(&block1).await?;
  47. let block3 = th.generate_next_block(&block2).await?;
  48. let block4 = th.generate_next_block(&block3).await?;
  49. // Add them to nodes
  50. th.add_blocks(&vec![block1, block2, block3.clone(), block4.clone()]).await?;
  51. // Nodes must have one fork with 2 blocks
  52. th.validate_fork_chains(1, vec![2]).await;
  53. // Extend current fork sequence
  54. let block5 = th.generate_next_block(&block4).await?;
  55. // Create a new fork extending canonical
  56. let block6 = th.generate_next_block(&block3).await?;
  57. // Add them to nodes
  58. th.add_blocks(&vec![block5, block6.clone()]).await?;
  59. // Grab current best fork index
  60. let forks = th.alice.validator.consensus.forks.read().await;
  61. // If index corresponds to the small fork, finalization
  62. // did not occur, as it's size is not over the threshold.
  63. let small_best = best_fork_index(&forks)? == 1;
  64. drop(forks);
  65. if small_best {
  66. // Nodes must have one fork with 3 blocks and one with 2 blocks
  67. th.validate_fork_chains(2, vec![3, 2]).await;
  68. } else {
  69. // Nodes must have one fork with 2 blocks and one with 1 block
  70. th.validate_fork_chains(2, vec![2, 1]).await;
  71. }
  72. // We are going to create a third node and try to sync from Bob
  73. let mut settings = Settings { localnet: true, inbound_connections: 3, ..Default::default() };
  74. let charlie_url = Url::parse("tcp+tls://127.0.0.1:18342")?;
  75. settings.inbound_addrs = vec![charlie_url];
  76. let bob_url = th.bob.p2p.settings().inbound_addrs[0].clone();
  77. settings.peers = vec![bob_url];
  78. let charlie =
  79. generate_node(&th.vks, &th.validator_config, &settings, &ex, false, false).await?;
  80. // Verify node synced
  81. let alice = &th.alice.validator;
  82. let charlie = &charlie.validator;
  83. charlie.validate_blockchain(pow_target, pow_fixed_difficulty.clone()).await?;
  84. assert_eq!(alice.blockchain.len(), charlie.blockchain.len());
  85. // Node must have just the best fork
  86. let forks = alice.consensus.forks.read().await;
  87. let best_fork = &forks[best_fork_index(&forks)?];
  88. let charlie_forks = charlie.consensus.forks.read().await;
  89. assert_eq!(charlie_forks.len(), 1);
  90. assert_eq!(charlie_forks[0].proposals.len(), best_fork.proposals.len());
  91. assert_eq!(charlie_forks[0].diffs.len(), best_fork.diffs.len());
  92. drop(forks);
  93. drop(charlie_forks);
  94. // Extend the small fork sequence and add it to nodes
  95. let block7 = th.generate_next_block(&block6).await?;
  96. th.add_blocks(&vec![block7.clone()]).await?;
  97. // Nodes must have two forks with 2 blocks each
  98. th.validate_fork_chains(2, vec![2, 2]).await;
  99. // Check charlie has the correct forks
  100. let charlie_forks = charlie.consensus.forks.read().await;
  101. if small_best {
  102. // If Charlie already had the small fork as its best,
  103. // it will have a single fork with 2 blocks.
  104. assert_eq!(charlie_forks.len(), 1);
  105. assert_eq!(charlie_forks[0].proposals.len(), 2);
  106. assert_eq!(charlie_forks[0].diffs.len(), 2);
  107. } else {
  108. // Charlie didn't originaly have the fork, but it
  109. // should be synced when its proposal was received
  110. assert_eq!(charlie_forks.len(), 2);
  111. assert_eq!(charlie_forks[0].proposals.len(), 2);
  112. assert_eq!(charlie_forks[0].diffs.len(), 2);
  113. assert_eq!(charlie_forks[1].proposals.len(), 2);
  114. assert_eq!(charlie_forks[1].diffs.len(), 2);
  115. }
  116. drop(charlie_forks);
  117. // Since the don't know if the second fork was the best,
  118. // we extend it until it becomes best and a finalization
  119. // occurred.
  120. let mut fork_sequence = vec![block6, block7];
  121. loop {
  122. let proposal = th.generate_next_block(fork_sequence.last().unwrap()).await?;
  123. th.add_blocks(&vec![proposal.clone()]).await?;
  124. fork_sequence.push(proposal);
  125. // Check if finalization occured
  126. if th.alice.validator.blockchain.len() > 4 {
  127. break
  128. }
  129. }
  130. // Nodes must have executed finalization, so we validate their chains
  131. th.validate_chains(4 + (fork_sequence.len() - 2)).await?;
  132. let bob = &th.bob.validator;
  133. let last = alice.blockchain.last()?.1;
  134. assert_eq!(last, fork_sequence[fork_sequence.len() - 3].hash()?);
  135. assert_eq!(last, bob.blockchain.last()?.1);
  136. // Nodes must have one fork with 2 blocks
  137. th.validate_fork_chains(1, vec![2]).await;
  138. let last_proposal = alice.consensus.forks.read().await[0].proposals[1];
  139. assert_eq!(last_proposal, fork_sequence.last().unwrap().hash()?);
  140. assert_eq!(last_proposal, bob.consensus.forks.read().await[0].proposals[1]);
  141. // Same for Charlie
  142. charlie.finalization().await?;
  143. charlie.validate_blockchain(pow_target, pow_fixed_difficulty).await?;
  144. assert_eq!(alice.blockchain.len(), charlie.blockchain.len());
  145. assert_eq!(last, charlie.blockchain.last()?.1);
  146. let charlie_forks = charlie.consensus.forks.read().await;
  147. assert_eq!(charlie_forks.len(), 1);
  148. assert_eq!(charlie_forks[0].proposals.len(), 2);
  149. assert_eq!(charlie_forks[0].diffs.len(), 2);
  150. assert_eq!(last_proposal, charlie_forks[0].proposals[1]);
  151. // Thanks for reading
  152. Ok(())
  153. }
  154. #[test]
  155. fn sync_blocks() -> Result<()> {
  156. let ex = Arc::new(Executor::new());
  157. let (signal, shutdown) = smol::channel::unbounded::<()>();
  158. easy_parallel::Parallel::new().each(0..4, |_| smol::block_on(ex.run(shutdown.recv()))).finish(
  159. || {
  160. smol::block_on(async {
  161. sync_blocks_real(ex.clone()).await.unwrap();
  162. drop(signal);
  163. })
  164. },
  165. );
  166. Ok(())
  167. }