harness.rs 9.2 KB

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