harness.rs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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::{collections::HashMap, sync::Arc};
  19. use darkfi::{
  20. blockchain::{BlockInfo, Header, HeaderHash},
  21. net::Settings,
  22. rpc::jsonrpc::JsonSubscriber,
  23. system::sleep,
  24. tx::{ContractCallLeaf, TransactionBuilder},
  25. validator::{consensus::Proposal, Validator, ValidatorConfig},
  26. zk::{empty_witnesses, ProvingKey, ZkCircuit},
  27. Result,
  28. };
  29. use darkfi_contract_test_harness::vks;
  30. use darkfi_money_contract::{
  31. client::pow_reward_v1::PoWRewardCallBuilder, MoneyFunction, MONEY_CONTRACT_ZKAS_MINT_NS_V1,
  32. };
  33. use darkfi_sdk::{
  34. crypto::{Keypair, MONEY_CONTRACT_ID},
  35. pasta::pallas,
  36. ContractCall,
  37. };
  38. use darkfi_serial::Encodable;
  39. use num_bigint::BigUint;
  40. use url::Url;
  41. use crate::{proto::ProposalMessage, task::sync::sync_task, utils::spawn_p2p, Darkfid};
  42. pub struct HarnessConfig {
  43. pub pow_target: u32,
  44. pub pow_fixed_difficulty: Option<BigUint>,
  45. pub finalization_threshold: usize,
  46. pub alice_url: String,
  47. pub bob_url: String,
  48. }
  49. pub struct Harness {
  50. pub config: HarnessConfig,
  51. pub vks: Vec<(Vec<u8>, String, Vec<u8>)>,
  52. pub validator_config: ValidatorConfig,
  53. pub alice: Darkfid,
  54. pub bob: Darkfid,
  55. }
  56. impl Harness {
  57. pub async fn new(
  58. config: HarnessConfig,
  59. verify_fees: bool,
  60. ex: &Arc<smol::Executor<'static>>,
  61. ) -> Result<Self> {
  62. // Generate default genesis block
  63. let mut genesis_block = BlockInfo::default();
  64. // Retrieve genesis producer transaction
  65. let producer_tx = genesis_block.txs.pop().unwrap();
  66. // Append it again so its added to the merkle tree
  67. genesis_block.append_txs(vec![producer_tx]);
  68. // Generate validators configuration
  69. // NOTE: we are not using consensus constants here so we
  70. // don't get circular dependencies.
  71. let validator_config = ValidatorConfig {
  72. finalization_threshold: config.finalization_threshold,
  73. pow_target: config.pow_target,
  74. pow_fixed_difficulty: config.pow_fixed_difficulty.clone(),
  75. genesis_block,
  76. verify_fees,
  77. };
  78. // Generate validators using pregenerated vks
  79. let (_, vks) = vks::get_cached_pks_and_vks()?;
  80. let mut settings =
  81. Settings { localnet: true, inbound_connections: 3, ..Default::default() };
  82. // Alice
  83. let alice_url = Url::parse(&config.alice_url)?;
  84. settings.inbound_addrs = vec![alice_url.clone()];
  85. let alice = generate_node(&vks, &validator_config, &settings, ex, true, true, None).await?;
  86. // Bob
  87. let bob_url = Url::parse(&config.bob_url)?;
  88. settings.inbound_addrs = vec![bob_url];
  89. settings.peers = vec![alice_url];
  90. let bob = generate_node(&vks, &validator_config, &settings, ex, true, false, None).await?;
  91. Ok(Self { config, vks, validator_config, alice, bob })
  92. }
  93. pub async fn validate_chains(&self, total_blocks: usize) -> Result<()> {
  94. let alice = &self.alice.validator;
  95. let bob = &self.bob.validator;
  96. alice
  97. .validate_blockchain(self.config.pow_target, self.config.pow_fixed_difficulty.clone())
  98. .await?;
  99. bob.validate_blockchain(self.config.pow_target, self.config.pow_fixed_difficulty.clone())
  100. .await?;
  101. let alice_blockchain_len = alice.blockchain.len();
  102. assert_eq!(alice_blockchain_len, bob.blockchain.len());
  103. assert_eq!(alice_blockchain_len, total_blocks);
  104. assert!(alice.blockchain.headers.is_empty_sync());
  105. assert!(bob.blockchain.headers.is_empty_sync());
  106. Ok(())
  107. }
  108. pub async fn validate_fork_chains(&self, total_forks: usize, fork_sizes: Vec<usize>) {
  109. let alice = &self.alice.validator.consensus.forks.read().await;
  110. let bob = &self.bob.validator.consensus.forks.read().await;
  111. let alice_forks_len = alice.len();
  112. assert_eq!(alice_forks_len, bob.len());
  113. assert_eq!(alice_forks_len, total_forks);
  114. for (index, fork) in alice.iter().enumerate() {
  115. assert_eq!(fork.proposals.len(), fork_sizes[index]);
  116. assert_eq!(fork.diffs.len(), fork_sizes[index]);
  117. }
  118. for (index, fork) in bob.iter().enumerate() {
  119. assert_eq!(fork.proposals.len(), fork_sizes[index]);
  120. assert_eq!(fork.diffs.len(), fork_sizes[index]);
  121. }
  122. }
  123. pub async fn add_blocks(&self, blocks: &[BlockInfo]) -> Result<()> {
  124. // We append the block as a proposal to Alice,
  125. // and then we broadcast it to rest nodes
  126. for block in blocks {
  127. let proposal = Proposal::new(block.clone());
  128. self.alice.validator.append_proposal(&proposal).await?;
  129. let message = ProposalMessage(proposal);
  130. self.alice.p2p.broadcast(&message).await;
  131. }
  132. // Sleep a bit so blocks can be propagated and then
  133. // trigger finalization check to Alice and Bob
  134. sleep(10).await;
  135. self.alice.validator.finalization().await?;
  136. self.bob.validator.finalization().await?;
  137. Ok(())
  138. }
  139. pub async fn generate_next_block(&self, previous: &BlockInfo) -> Result<BlockInfo> {
  140. // Next block info
  141. let block_height = previous.header.height + 1;
  142. let last_nonce = previous.header.nonce;
  143. // Generate a producer transaction
  144. let keypair = Keypair::default();
  145. let (zkbin, _) = self.alice.validator.blockchain.contracts.get_zkas(
  146. &self.alice.validator.blockchain.sled_db,
  147. &MONEY_CONTRACT_ID,
  148. MONEY_CONTRACT_ZKAS_MINT_NS_V1,
  149. )?;
  150. let circuit = ZkCircuit::new(empty_witnesses(&zkbin)?, &zkbin);
  151. let pk = ProvingKey::build(zkbin.k, &circuit);
  152. // We're just going to be using a zero spend-hook and user-data
  153. let spend_hook = pallas::Base::zero().into();
  154. let user_data = pallas::Base::zero();
  155. // Build the transaction debris
  156. let debris = PoWRewardCallBuilder {
  157. secret: keypair.secret,
  158. recipient: keypair.public,
  159. block_height,
  160. fees: 0,
  161. spend_hook,
  162. user_data,
  163. mint_zkbin: zkbin.clone(),
  164. mint_pk: pk.clone(),
  165. }
  166. .build()?;
  167. // Generate and sign the actual transaction
  168. let mut data = vec![MoneyFunction::PoWRewardV1 as u8];
  169. debris.params.encode(&mut data)?;
  170. let call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  171. let mut tx_builder =
  172. TransactionBuilder::new(ContractCallLeaf { call, proofs: debris.proofs }, vec![])?;
  173. let mut tx = tx_builder.build()?;
  174. let sigs = tx.create_sigs(&[keypair.secret])?;
  175. tx.signatures = vec![sigs];
  176. // We increment timestamp so we don't have to use sleep
  177. let timestamp = previous.header.timestamp.checked_add(1.into())?;
  178. // Generate header
  179. let header = Header::new(previous.hash(), block_height, timestamp, last_nonce);
  180. // Generate the block
  181. let mut block = BlockInfo::new_empty(header);
  182. // Add producer transaction to the block
  183. block.append_txs(vec![tx]);
  184. // Attach signature
  185. block.sign(&keypair.secret);
  186. Ok(block)
  187. }
  188. }
  189. // Note: This function should mirror darkfid::main
  190. pub async fn generate_node(
  191. vks: &Vec<(Vec<u8>, String, Vec<u8>)>,
  192. config: &ValidatorConfig,
  193. settings: &Settings,
  194. ex: &Arc<smol::Executor<'static>>,
  195. miner: bool,
  196. skip_sync: bool,
  197. checkpoint: Option<(u32, HeaderHash)>,
  198. ) -> Result<Darkfid> {
  199. let sled_db = sled::Config::new().temporary(true).open()?;
  200. vks::inject(&sled_db, vks)?;
  201. let validator = Validator::new(&sled_db, config.clone()).await?;
  202. let mut subscribers = HashMap::new();
  203. subscribers.insert("blocks", JsonSubscriber::new("blockchain.subscribe_blocks"));
  204. subscribers.insert("txs", JsonSubscriber::new("blockchain.subscribe_txs"));
  205. subscribers.insert("proposals", JsonSubscriber::new("blockchain.subscribe_proposals"));
  206. let p2p = spawn_p2p(settings, &validator, &subscribers, ex.clone()).await;
  207. let node = Darkfid::new(p2p.clone(), validator, miner, 50, subscribers, None).await;
  208. p2p.start().await?;
  209. node.validator.consensus.generate_empty_fork().await?;
  210. if !skip_sync {
  211. sync_task(&node, checkpoint).await?;
  212. } else {
  213. *node.validator.synced.write().await = true;
  214. }
  215. node.validator.purge_pending_txs().await?;
  216. Ok(node)
  217. }