harness.rs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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},
  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, Holder, TestHarness};
  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 rand::rngs::OsRng;
  41. use url::Url;
  42. use crate::{
  43. proto::ProposalMessage,
  44. task::sync::sync_task,
  45. utils::{spawn_miners_p2p, spawn_sync_p2p},
  46. Darkfid,
  47. };
  48. pub struct HarnessConfig {
  49. pub pow_target: usize,
  50. pub pow_fixed_difficulty: Option<BigUint>,
  51. pub alice_initial: u64,
  52. pub bob_initial: u64,
  53. }
  54. pub struct Harness {
  55. pub config: HarnessConfig,
  56. pub vks: Vec<(Vec<u8>, String, Vec<u8>)>,
  57. pub validator_config: ValidatorConfig,
  58. pub alice: Darkfid,
  59. pub bob: Darkfid,
  60. }
  61. impl Harness {
  62. pub async fn new(
  63. config: HarnessConfig,
  64. verify_fees: bool,
  65. ex: &Arc<smol::Executor<'static>>,
  66. ) -> Result<Self> {
  67. // Use test harness to generate genesis transactions
  68. let mut th = TestHarness::new(&[Holder::Bob], verify_fees).await?;
  69. let (genesis_mint_tx, _) =
  70. th.genesis_mint(&Holder::Bob, config.bob_initial, None, None).await?;
  71. // Generate default genesis block
  72. let mut genesis_block = BlockInfo::default();
  73. // Retrieve genesis producer transaction
  74. let producer_tx = genesis_block.txs.pop().unwrap();
  75. // Append genesis transactions
  76. genesis_block.append_txs(vec![genesis_mint_tx, producer_tx])?;
  77. // Generate validators configuration
  78. // NOTE: we are not using consensus constants here so we
  79. // don't get circular dependencies.
  80. let validator_config = ValidatorConfig {
  81. finalization_threshold: 3,
  82. pow_target: config.pow_target,
  83. pow_fixed_difficulty: config.pow_fixed_difficulty.clone(),
  84. genesis_block,
  85. verify_fees,
  86. };
  87. // Generate validators using pregenerated vks
  88. let (_, vks) = vks::get_cached_pks_and_vks()?;
  89. let mut sync_settings =
  90. Settings { localnet: true, inbound_connections: 3, ..Default::default() };
  91. let mut miners_settings =
  92. Settings { localnet: true, inbound_connections: 3, ..Default::default() };
  93. // Alice
  94. let alice_url = Url::parse("tcp+tls://127.0.0.1:18340")?;
  95. sync_settings.inbound_addrs = vec![alice_url.clone()];
  96. let alice_miners_url = Url::parse("tcp+tls://127.0.0.1:18350")?;
  97. miners_settings.inbound_addrs = vec![alice_miners_url.clone()];
  98. let alice = generate_node(
  99. &vks,
  100. &validator_config,
  101. &sync_settings,
  102. Some(&miners_settings),
  103. ex,
  104. true,
  105. )
  106. .await?;
  107. // Bob
  108. let bob_url = Url::parse("tcp+tls://127.0.0.1:18341")?;
  109. sync_settings.inbound_addrs = vec![bob_url];
  110. sync_settings.peers = vec![alice_url];
  111. let bob_miners_url = Url::parse("tcp+tls://127.0.0.1:18351")?;
  112. miners_settings.inbound_addrs = vec![bob_miners_url];
  113. miners_settings.peers = vec![alice_miners_url];
  114. let bob = generate_node(
  115. &vks,
  116. &validator_config,
  117. &sync_settings,
  118. Some(&miners_settings),
  119. ex,
  120. false,
  121. )
  122. .await?;
  123. Ok(Self { config, vks, validator_config, alice, bob })
  124. }
  125. pub async fn validate_chains(&self, total_blocks: usize) -> Result<()> {
  126. let alice = &self.alice.validator;
  127. let bob = &self.bob.validator;
  128. alice
  129. .validate_blockchain(self.config.pow_target, self.config.pow_fixed_difficulty.clone())
  130. .await?;
  131. bob.validate_blockchain(self.config.pow_target, self.config.pow_fixed_difficulty.clone())
  132. .await?;
  133. let alice_blockchain_len = alice.blockchain.len();
  134. assert_eq!(alice_blockchain_len, bob.blockchain.len());
  135. // Last block is not finalized yet
  136. assert_eq!(alice_blockchain_len, total_blocks - 1);
  137. Ok(())
  138. }
  139. pub async fn add_blocks(&self, blocks: &[BlockInfo]) -> Result<()> {
  140. // We append the block as a proposal to Alice,
  141. // and then we broadcast it to rest nodes
  142. for block in blocks {
  143. let proposal = Proposal::new(block.clone())?;
  144. self.alice.validator.consensus.append_proposal(&proposal).await?;
  145. let message = ProposalMessage(proposal);
  146. self.alice.miners_p2p.as_ref().unwrap().broadcast(&message).await;
  147. }
  148. // Sleep a bit so blocks can be propagated and then
  149. // trigger finalization check to Alice and Bob
  150. sleep(1).await;
  151. self.alice.validator.finalization().await?;
  152. self.bob.validator.finalization().await?;
  153. Ok(())
  154. }
  155. pub async fn generate_next_block(&self, previous: &BlockInfo) -> Result<BlockInfo> {
  156. // Next block info
  157. let block_height = previous.header.height + 1;
  158. let last_nonce = previous.header.nonce;
  159. let fork_previous_hash = previous.header.previous;
  160. // Generate a producer transaction
  161. let keypair = Keypair::default();
  162. let (zkbin, _) = self.alice.validator.blockchain.contracts.get_zkas(
  163. &self.alice.validator.blockchain.sled_db,
  164. &MONEY_CONTRACT_ID,
  165. MONEY_CONTRACT_ZKAS_MINT_NS_V1,
  166. )?;
  167. let circuit = ZkCircuit::new(empty_witnesses(&zkbin)?, &zkbin);
  168. let pk = ProvingKey::build(zkbin.k, &circuit);
  169. // We're just going to be using a zero spend-hook and user-data
  170. let spend_hook = pallas::Base::zero().into();
  171. let user_data = pallas::Base::zero();
  172. // Build the transaction debris
  173. let debris = PoWRewardCallBuilder {
  174. secret: keypair.secret,
  175. recipient: keypair.public,
  176. block_height,
  177. last_nonce,
  178. fork_previous_hash,
  179. spend_hook,
  180. user_data,
  181. mint_zkbin: zkbin.clone(),
  182. mint_pk: pk.clone(),
  183. }
  184. .build()?;
  185. // Generate and sign the actual transaction
  186. let mut data = vec![MoneyFunction::PoWRewardV1 as u8];
  187. debris.params.encode(&mut data)?;
  188. let call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  189. let mut tx_builder =
  190. TransactionBuilder::new(ContractCallLeaf { call, proofs: debris.proofs }, vec![])?;
  191. let mut tx = tx_builder.build()?;
  192. let sigs = tx.create_sigs(&mut OsRng, &[keypair.secret])?;
  193. tx.signatures = vec![sigs];
  194. // We increment timestamp so we don't have to use sleep
  195. let mut timestamp = previous.header.timestamp;
  196. timestamp.add(1);
  197. // Generate header
  198. let header = Header::new(previous.hash()?, block_height, timestamp, last_nonce);
  199. // Generate the block
  200. let mut block = BlockInfo::new_empty(header);
  201. // Add producer transaction to the block
  202. block.append_txs(vec![tx])?;
  203. // Attach signature
  204. block.sign(&keypair.secret)?;
  205. Ok(block)
  206. }
  207. }
  208. // Note: This function should mirror darkfid::main
  209. pub async fn generate_node(
  210. vks: &Vec<(Vec<u8>, String, Vec<u8>)>,
  211. config: &ValidatorConfig,
  212. sync_settings: &Settings,
  213. miners_settings: Option<&Settings>,
  214. ex: &Arc<smol::Executor<'static>>,
  215. skip_sync: bool,
  216. ) -> Result<Darkfid> {
  217. let sled_db = sled::Config::new().temporary(true).open()?;
  218. vks::inject(&sled_db, vks)?;
  219. let validator = Validator::new(&sled_db, config.clone()).await?;
  220. let mut subscribers = HashMap::new();
  221. subscribers.insert("blocks", JsonSubscriber::new("blockchain.subscribe_blocks"));
  222. subscribers.insert("txs", JsonSubscriber::new("blockchain.subscribe_txs"));
  223. subscribers.insert("proposals", JsonSubscriber::new("blockchain.subscribe_proposals"));
  224. let sync_p2p = spawn_sync_p2p(sync_settings, &validator, &subscribers, ex.clone()).await;
  225. let miners_p2p = if let Some(settings) = miners_settings {
  226. Some(spawn_miners_p2p(settings, &validator, &subscribers, ex.clone()).await)
  227. } else {
  228. None
  229. };
  230. let node =
  231. Darkfid::new(sync_p2p.clone(), miners_p2p.clone(), validator, subscribers, None).await;
  232. sync_p2p.clone().start().await?;
  233. if miners_settings.is_some() {
  234. let miners_p2p = miners_p2p.unwrap();
  235. miners_p2p.clone().start().await?;
  236. }
  237. if !skip_sync {
  238. sync_task(&node).await?;
  239. } else {
  240. *node.validator.synced.write().await = true;
  241. }
  242. node.validator.purge_pending_txs().await?;
  243. Ok(node)
  244. }