harness.rs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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::{
  19. collections::HashMap,
  20. time::{Duration, Instant},
  21. };
  22. use darkfi::{
  23. consensus::{
  24. SlotCheckpoint, ValidatorState, ValidatorStatePtr, TESTNET_BOOTSTRAP_TIMESTAMP,
  25. TESTNET_GENESIS_HASH_BYTES, TESTNET_GENESIS_TIMESTAMP, TESTNET_INITIAL_DISTRIBUTION,
  26. },
  27. runtime::vm_runtime::SMART_CONTRACT_ZKAS_DB_NAME,
  28. tx::Transaction,
  29. wallet::{WalletDb, WalletPtr},
  30. zk::{empty_witnesses, halo2::Field, ProvingKey, ZkCircuit},
  31. zkas::ZkBinary,
  32. Result,
  33. };
  34. use darkfi_sdk::{
  35. crypto::{
  36. merkle_prelude::*, poseidon_hash, Keypair, MerkleNode, MerkleTree, Nullifier, PublicKey,
  37. SecretKey, CONSENSUS_CONTRACT_ID, DARK_TOKEN_ID, MONEY_CONTRACT_ID,
  38. },
  39. pasta::pallas,
  40. ContractCall,
  41. };
  42. use darkfi_serial::{deserialize, serialize, Encodable};
  43. use log::{info, warn};
  44. use rand::rngs::OsRng;
  45. use darkfi_consensus_contract::{
  46. client::{
  47. genesis_stake_v1::ConsensusGenesisStakeCallBuilder,
  48. proposal_v1::ConsensusProposalCallBuilder, stake_v1::ConsensusStakeCallBuilder,
  49. unstake_request_v1::ConsensusUnstakeRequestCallBuilder,
  50. unstake_v1::ConsensusUnstakeCallBuilder,
  51. },
  52. model::{ConsensusGenesisStakeParamsV1, ConsensusProposalParamsV1},
  53. ConsensusFunction,
  54. };
  55. use darkfi_money_contract::{
  56. client::{
  57. stake_v1::MoneyStakeCallBuilder, transfer_v1::TransferCallBuilder,
  58. unstake_v1::MoneyUnstakeCallBuilder, ConsensusNote, ConsensusOwnCoin, MoneyNote, OwnCoin,
  59. },
  60. model::{
  61. Coin, ConsensusOutput, ConsensusStakeParamsV1, ConsensusUnstakeReqParamsV1,
  62. MoneyTransferParamsV1, MoneyUnstakeParamsV1, Output,
  63. },
  64. MoneyFunction, CONSENSUS_CONTRACT_ZKAS_BURN_NS_V1, CONSENSUS_CONTRACT_ZKAS_MINT_NS_V1,
  65. CONSENSUS_CONTRACT_ZKAS_PROPOSAL_NS_V1, MONEY_CONTRACT_ZKAS_BURN_NS_V1,
  66. MONEY_CONTRACT_ZKAS_MINT_NS_V1,
  67. };
  68. pub fn init_logger() {
  69. let mut cfg = simplelog::ConfigBuilder::new();
  70. cfg.add_filter_ignore("sled".to_string());
  71. cfg.add_filter_ignore("blockchain::contractstore".to_string());
  72. // We check this error so we can execute same file tests in parallel,
  73. // otherwise second one fails to init logger here.
  74. if let Err(_) = simplelog::TermLogger::init(
  75. //simplelog::LevelFilter::Info,
  76. simplelog::LevelFilter::Debug,
  77. //simplelog::LevelFilter::Trace,
  78. cfg.build(),
  79. simplelog::TerminalMode::Mixed,
  80. simplelog::ColorChoice::Auto,
  81. ) {
  82. warn!(target: "money_harness", "Logger already initialized");
  83. }
  84. }
  85. /// Enum representing configured wallet holders
  86. #[derive(Debug, Eq, Hash, PartialEq)]
  87. pub enum Holder {
  88. Faucet,
  89. Alice,
  90. }
  91. /// Enum representing transaction actions
  92. #[derive(Debug, Eq, Hash, PartialEq)]
  93. pub enum TxAction {
  94. Airdrop,
  95. GenesisStake,
  96. Stake,
  97. Proposal,
  98. UnstakeRequest,
  99. Unstake,
  100. }
  101. /// Auxiliary struct to calculate transaction actions benchmarks
  102. pub struct TxActionBenchmarks {
  103. /// Vector holding each transaction size in Bytes
  104. pub sizes: Vec<usize>,
  105. /// Vector holding each transaction broadcasted size in Bytes
  106. pub broadcasted_sizes: Vec<usize>,
  107. /// Vector holding each transaction creation time
  108. pub creation_times: Vec<Duration>,
  109. /// Vector holding each transaction verify time
  110. pub verify_times: Vec<Duration>,
  111. }
  112. impl TxActionBenchmarks {
  113. pub fn new() -> Self {
  114. Self {
  115. sizes: vec![],
  116. broadcasted_sizes: vec![],
  117. creation_times: vec![],
  118. verify_times: vec![],
  119. }
  120. }
  121. pub fn statistics(&self, action: &TxAction) {
  122. if !self.sizes.is_empty() {
  123. let avg = self.sizes.iter().sum::<usize>();
  124. let avg = avg / self.sizes.len();
  125. info!(target: "consensus", "Average {:?} size: {:?} Bytes", action, avg);
  126. }
  127. if !self.broadcasted_sizes.is_empty() {
  128. let avg = self.broadcasted_sizes.iter().sum::<usize>();
  129. let avg = avg / self.broadcasted_sizes.len();
  130. info!(target: "consensus", "Average {:?} broadcasted size: {:?} Bytes", action, avg);
  131. }
  132. if !self.creation_times.is_empty() {
  133. let avg = self.creation_times.iter().sum::<Duration>();
  134. let avg = avg / self.creation_times.len() as u32;
  135. info!(target: "consensus", "Average {:?} creation time: {:?}", action, avg);
  136. }
  137. if !self.verify_times.is_empty() {
  138. let avg = self.verify_times.iter().sum::<Duration>();
  139. let avg = avg / self.verify_times.len() as u32;
  140. info!(target: "consensus", "Average {:?} verification time: {:?}", action, avg);
  141. }
  142. }
  143. }
  144. pub struct Wallet {
  145. pub keypair: Keypair,
  146. pub state: ValidatorStatePtr,
  147. pub money_merkle_tree: MerkleTree,
  148. pub consensus_staked_merkle_tree: MerkleTree,
  149. pub consensus_unstaked_merkle_tree: MerkleTree,
  150. pub wallet: WalletPtr,
  151. pub coins: Vec<OwnCoin>,
  152. pub spent_coins: Vec<OwnCoin>,
  153. }
  154. impl Wallet {
  155. async fn new(keypair: Keypair, faucet_pubkeys: &[PublicKey]) -> Result<Self> {
  156. let wallet = WalletDb::new("sqlite::memory:", "foo").await?;
  157. let sled_db = sled::Config::new().temporary(true).open()?;
  158. let state = ValidatorState::new(
  159. &sled_db,
  160. *TESTNET_BOOTSTRAP_TIMESTAMP,
  161. *TESTNET_GENESIS_TIMESTAMP,
  162. *TESTNET_GENESIS_HASH_BYTES,
  163. *TESTNET_INITIAL_DISTRIBUTION,
  164. wallet.clone(),
  165. faucet_pubkeys.to_vec(),
  166. false,
  167. false,
  168. )
  169. .await?;
  170. let money_merkle_tree = MerkleTree::new(100);
  171. let consensus_staked_merkle_tree = MerkleTree::new(100);
  172. let consensus_unstaked_merkle_tree = MerkleTree::new(100);
  173. let coins = vec![];
  174. let spent_coins = vec![];
  175. Ok(Self {
  176. keypair,
  177. state,
  178. money_merkle_tree,
  179. consensus_staked_merkle_tree,
  180. consensus_unstaked_merkle_tree,
  181. wallet,
  182. coins,
  183. spent_coins,
  184. })
  185. }
  186. }
  187. pub struct ConsensusTestHarness {
  188. pub holders: HashMap<Holder, Wallet>,
  189. pub proving_keys: HashMap<&'static str, (ProvingKey, ZkBinary)>,
  190. pub tx_action_benchmarks: HashMap<TxAction, TxActionBenchmarks>,
  191. }
  192. impl ConsensusTestHarness {
  193. pub async fn new() -> Result<Self> {
  194. let mut holders = HashMap::new();
  195. let faucet_kp = Keypair::random(&mut OsRng);
  196. let faucet_pubkeys = vec![faucet_kp.public];
  197. let faucet = Wallet::new(faucet_kp, &faucet_pubkeys).await?;
  198. holders.insert(Holder::Faucet, faucet);
  199. let alice_kp = Keypair::random(&mut OsRng);
  200. let alice = Wallet::new(alice_kp, &faucet_pubkeys).await?;
  201. // Get the zkas circuits and build proving keys
  202. let mut proving_keys = HashMap::new();
  203. let alice_sled = alice.state.read().await.blockchain.sled_db.clone();
  204. let mut db_handle = alice.state.read().await.blockchain.contracts.lookup(
  205. &alice_sled,
  206. &MONEY_CONTRACT_ID,
  207. SMART_CONTRACT_ZKAS_DB_NAME,
  208. )?;
  209. macro_rules! mkpk {
  210. ($ns:expr) => {
  211. let zkas_bytes = db_handle.get(&serialize(&$ns))?.unwrap();
  212. let (zkbin, _): (Vec<u8>, Vec<u8>) = deserialize(&zkas_bytes)?;
  213. let zkbin = ZkBinary::decode(&zkbin)?;
  214. let witnesses = empty_witnesses(&zkbin);
  215. let circuit = ZkCircuit::new(witnesses, zkbin.clone());
  216. let pk = ProvingKey::build(13, &circuit);
  217. proving_keys.insert($ns, (pk, zkbin));
  218. };
  219. }
  220. mkpk!(MONEY_CONTRACT_ZKAS_MINT_NS_V1);
  221. mkpk!(MONEY_CONTRACT_ZKAS_BURN_NS_V1);
  222. db_handle = alice.state.read().await.blockchain.contracts.lookup(
  223. &alice_sled,
  224. &CONSENSUS_CONTRACT_ID,
  225. SMART_CONTRACT_ZKAS_DB_NAME,
  226. )?;
  227. mkpk!(CONSENSUS_CONTRACT_ZKAS_MINT_NS_V1);
  228. mkpk!(CONSENSUS_CONTRACT_ZKAS_BURN_NS_V1);
  229. mkpk!(CONSENSUS_CONTRACT_ZKAS_PROPOSAL_NS_V1);
  230. holders.insert(Holder::Alice, alice);
  231. // Build benchmarks map
  232. let mut tx_action_benchmarks = HashMap::new();
  233. tx_action_benchmarks.insert(TxAction::Airdrop, TxActionBenchmarks::new());
  234. tx_action_benchmarks.insert(TxAction::GenesisStake, TxActionBenchmarks::new());
  235. tx_action_benchmarks.insert(TxAction::Stake, TxActionBenchmarks::new());
  236. tx_action_benchmarks.insert(TxAction::Proposal, TxActionBenchmarks::new());
  237. tx_action_benchmarks.insert(TxAction::UnstakeRequest, TxActionBenchmarks::new());
  238. tx_action_benchmarks.insert(TxAction::Unstake, TxActionBenchmarks::new());
  239. Ok(Self { holders, proving_keys, tx_action_benchmarks })
  240. }
  241. pub fn airdrop_native(
  242. &mut self,
  243. value: u64,
  244. holder: Holder,
  245. ) -> Result<(Transaction, MoneyTransferParamsV1)> {
  246. let recipient = self.holders.get_mut(&holder).unwrap().keypair.public;
  247. let faucet = self.holders.get_mut(&Holder::Faucet).unwrap();
  248. let (mint_pk, mint_zkbin) = self.proving_keys.get(&MONEY_CONTRACT_ZKAS_MINT_NS_V1).unwrap();
  249. let (burn_pk, burn_zkbin) = self.proving_keys.get(&MONEY_CONTRACT_ZKAS_BURN_NS_V1).unwrap();
  250. let tx_action_benchmark = self.tx_action_benchmarks.get_mut(&TxAction::Airdrop).unwrap();
  251. let timer = Instant::now();
  252. let builder = TransferCallBuilder {
  253. keypair: faucet.keypair,
  254. recipient,
  255. value,
  256. token_id: *DARK_TOKEN_ID,
  257. rcpt_spend_hook: pallas::Base::zero(),
  258. rcpt_user_data: pallas::Base::zero(),
  259. rcpt_user_data_blind: pallas::Base::random(&mut OsRng),
  260. change_spend_hook: pallas::Base::zero(),
  261. change_user_data: pallas::Base::zero(),
  262. change_user_data_blind: pallas::Base::random(&mut OsRng),
  263. coins: vec![],
  264. tree: faucet.money_merkle_tree.clone(),
  265. mint_zkbin: mint_zkbin.clone(),
  266. mint_pk: mint_pk.clone(),
  267. burn_zkbin: burn_zkbin.clone(),
  268. burn_pk: burn_pk.clone(),
  269. clear_input: true,
  270. };
  271. let debris = builder.build()?;
  272. let mut data = vec![MoneyFunction::TransferV1 as u8];
  273. debris.params.encode(&mut data)?;
  274. let calls = vec![ContractCall { contract_id: *MONEY_CONTRACT_ID, data }];
  275. let proofs = vec![debris.proofs];
  276. let mut tx = Transaction { calls, proofs, signatures: vec![] };
  277. let sigs = tx.create_sigs(&mut OsRng, &debris.signature_secrets)?;
  278. tx.signatures = vec![sigs];
  279. tx_action_benchmark.creation_times.push(timer.elapsed());
  280. // Calculate transaction sizes
  281. let encoded: Vec<u8> = serialize(&tx);
  282. let size = std::mem::size_of_val(&*encoded);
  283. tx_action_benchmark.sizes.push(size);
  284. let base58 = bs58::encode(&encoded).into_string();
  285. let size = std::mem::size_of_val(&*base58);
  286. tx_action_benchmark.broadcasted_sizes.push(size);
  287. Ok((tx, debris.params))
  288. }
  289. pub async fn execute_airdrop_native_tx(
  290. &mut self,
  291. holder: Holder,
  292. tx: Transaction,
  293. params: &MoneyTransferParamsV1,
  294. slot: u64,
  295. ) -> Result<()> {
  296. let wallet = self.holders.get_mut(&holder).unwrap();
  297. let tx_action_benchmark = self.tx_action_benchmarks.get_mut(&TxAction::Airdrop).unwrap();
  298. let timer = Instant::now();
  299. let erroneous_txs =
  300. wallet.state.read().await.verify_transactions(&[tx], slot, true).await?;
  301. assert!(erroneous_txs.is_empty());
  302. wallet.money_merkle_tree.append(&MerkleNode::from(params.outputs[0].coin.inner()));
  303. tx_action_benchmark.verify_times.push(timer.elapsed());
  304. Ok(())
  305. }
  306. pub fn genesis_stake(
  307. &mut self,
  308. holder: Holder,
  309. amount: u64,
  310. ) -> Result<(Transaction, ConsensusGenesisStakeParamsV1)> {
  311. let wallet = self.holders.get_mut(&holder).unwrap();
  312. let (mint_pk, mint_zkbin) =
  313. self.proving_keys.get(&CONSENSUS_CONTRACT_ZKAS_MINT_NS_V1).unwrap();
  314. let tx_action_benchmark =
  315. self.tx_action_benchmarks.get_mut(&TxAction::GenesisStake).unwrap();
  316. let timer = Instant::now();
  317. // Building Consensus::GenesisStake params
  318. let genesis_stake_call_debris = ConsensusGenesisStakeCallBuilder {
  319. keypair: wallet.keypair,
  320. recipient: wallet.keypair.public,
  321. amount,
  322. mint_zkbin: mint_zkbin.clone(),
  323. mint_pk: mint_pk.clone(),
  324. }
  325. .build()?;
  326. let (genesis_stake_params, genesis_stake_proofs) =
  327. (genesis_stake_call_debris.params, genesis_stake_call_debris.proofs);
  328. // Building genesis stake tx
  329. let mut data = vec![ConsensusFunction::GenesisStakeV1 as u8];
  330. genesis_stake_params.encode(&mut data)?;
  331. let contract_call = ContractCall { contract_id: *CONSENSUS_CONTRACT_ID, data };
  332. let calls = vec![contract_call];
  333. let proofs = vec![genesis_stake_proofs];
  334. let mut genesis_stake_tx = Transaction { calls, proofs, signatures: vec![] };
  335. let sigs = genesis_stake_tx.create_sigs(&mut OsRng, &[wallet.keypair.secret])?;
  336. genesis_stake_tx.signatures = vec![sigs];
  337. tx_action_benchmark.creation_times.push(timer.elapsed());
  338. // Calculate transaction sizes
  339. let encoded: Vec<u8> = serialize(&genesis_stake_tx);
  340. let size = std::mem::size_of_val(&*encoded);
  341. tx_action_benchmark.sizes.push(size);
  342. let base58 = bs58::encode(&encoded).into_string();
  343. let size = std::mem::size_of_val(&*base58);
  344. tx_action_benchmark.broadcasted_sizes.push(size);
  345. Ok((genesis_stake_tx, genesis_stake_params))
  346. }
  347. pub async fn execute_genesis_stake_tx(
  348. &mut self,
  349. holder: Holder,
  350. tx: Transaction,
  351. params: &ConsensusGenesisStakeParamsV1,
  352. slot: u64,
  353. ) -> Result<()> {
  354. let wallet = self.holders.get_mut(&holder).unwrap();
  355. let tx_action_benchmark =
  356. self.tx_action_benchmarks.get_mut(&TxAction::GenesisStake).unwrap();
  357. let timer = Instant::now();
  358. let erroneous_txs =
  359. wallet.state.read().await.verify_transactions(&[tx], slot, true).await?;
  360. assert!(erroneous_txs.is_empty());
  361. wallet.consensus_staked_merkle_tree.append(&MerkleNode::from(params.output.coin.inner()));
  362. tx_action_benchmark.verify_times.push(timer.elapsed());
  363. Ok(())
  364. }
  365. pub async fn execute_erroneous_genesis_stake_txs(
  366. &mut self,
  367. holder: Holder,
  368. txs: Vec<Transaction>,
  369. slot: u64,
  370. erroneous: usize,
  371. ) -> Result<()> {
  372. let wallet = self.holders.get_mut(&holder).unwrap();
  373. let tx_action_benchmark =
  374. self.tx_action_benchmarks.get_mut(&TxAction::GenesisStake).unwrap();
  375. let timer = Instant::now();
  376. let erroneous_txs =
  377. wallet.state.read().await.verify_transactions(&txs, slot, false).await?;
  378. assert_eq!(erroneous_txs.len(), erroneous);
  379. tx_action_benchmark.verify_times.push(timer.elapsed());
  380. Ok(())
  381. }
  382. pub async fn stake(
  383. &mut self,
  384. holder: Holder,
  385. slot: u64,
  386. owncoin: OwnCoin,
  387. ) -> Result<(Transaction, ConsensusStakeParamsV1, SecretKey)> {
  388. let wallet = self.holders.get_mut(&holder).unwrap();
  389. let (mint_pk, mint_zkbin) =
  390. self.proving_keys.get(&CONSENSUS_CONTRACT_ZKAS_MINT_NS_V1).unwrap();
  391. let (burn_pk, burn_zkbin) = self.proving_keys.get(&MONEY_CONTRACT_ZKAS_BURN_NS_V1).unwrap();
  392. let tx_action_benchmark = self.tx_action_benchmarks.get_mut(&TxAction::Stake).unwrap();
  393. let epoch = wallet.state.read().await.consensus.time_keeper.slot_epoch(slot);
  394. let timer = Instant::now();
  395. // Building Money::Stake params
  396. let money_stake_call_debris = MoneyStakeCallBuilder {
  397. coin: owncoin.clone(),
  398. tree: wallet.money_merkle_tree.clone(),
  399. burn_zkbin: burn_zkbin.clone(),
  400. burn_pk: burn_pk.clone(),
  401. }
  402. .build()?;
  403. let (
  404. money_stake_params,
  405. money_stake_proofs,
  406. money_stake_secret_key,
  407. money_stake_value_blind,
  408. ) = (
  409. money_stake_call_debris.params,
  410. money_stake_call_debris.proofs,
  411. money_stake_call_debris.signature_secret,
  412. money_stake_call_debris.value_blind,
  413. );
  414. // Building Consensus::Stake params
  415. let consensus_stake_call_debris = ConsensusStakeCallBuilder {
  416. coin: owncoin,
  417. epoch,
  418. value_blind: money_stake_value_blind,
  419. money_input: money_stake_params.input.clone(),
  420. mint_zkbin: mint_zkbin.clone(),
  421. mint_pk: mint_pk.clone(),
  422. }
  423. .build()?;
  424. let (consensus_stake_params, consensus_stake_proofs, consensus_stake_secret_key) = (
  425. consensus_stake_call_debris.params,
  426. consensus_stake_call_debris.proofs,
  427. consensus_stake_call_debris.signature_secret,
  428. );
  429. // Building stake tx
  430. let mut data = vec![MoneyFunction::StakeV1 as u8];
  431. money_stake_params.encode(&mut data)?;
  432. let money_call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  433. let mut data = vec![ConsensusFunction::StakeV1 as u8];
  434. consensus_stake_params.encode(&mut data)?;
  435. let consensus_call = ContractCall { contract_id: *CONSENSUS_CONTRACT_ID, data };
  436. let calls = vec![money_call, consensus_call];
  437. let proofs = vec![money_stake_proofs, consensus_stake_proofs];
  438. let mut stake_tx = Transaction { calls, proofs, signatures: vec![] };
  439. let money_sigs = stake_tx.create_sigs(&mut OsRng, &[money_stake_secret_key])?;
  440. let consensus_sigs = stake_tx.create_sigs(&mut OsRng, &[consensus_stake_secret_key])?;
  441. stake_tx.signatures = vec![money_sigs, consensus_sigs];
  442. tx_action_benchmark.creation_times.push(timer.elapsed());
  443. // Calculate transaction sizes
  444. let encoded: Vec<u8> = serialize(&stake_tx);
  445. let size = std::mem::size_of_val(&*encoded);
  446. tx_action_benchmark.sizes.push(size);
  447. let base58 = bs58::encode(&encoded).into_string();
  448. let size = std::mem::size_of_val(&*base58);
  449. tx_action_benchmark.broadcasted_sizes.push(size);
  450. Ok((stake_tx, consensus_stake_params, consensus_stake_secret_key))
  451. }
  452. pub async fn execute_stake_tx(
  453. &mut self,
  454. holder: Holder,
  455. tx: Transaction,
  456. params: &ConsensusStakeParamsV1,
  457. slot: u64,
  458. ) -> Result<()> {
  459. let wallet = self.holders.get_mut(&holder).unwrap();
  460. let tx_action_benchmark = self.tx_action_benchmarks.get_mut(&TxAction::Stake).unwrap();
  461. let timer = Instant::now();
  462. let erroneous_txs =
  463. wallet.state.read().await.verify_transactions(&[tx], slot, true).await?;
  464. assert!(erroneous_txs.is_empty());
  465. wallet.consensus_staked_merkle_tree.append(&MerkleNode::from(params.output.coin.inner()));
  466. tx_action_benchmark.verify_times.push(timer.elapsed());
  467. Ok(())
  468. }
  469. pub async fn proposal(
  470. &mut self,
  471. holder: Holder,
  472. slot_checkpoint: SlotCheckpoint,
  473. staked_oc: ConsensusOwnCoin,
  474. ) -> Result<(Transaction, ConsensusProposalParamsV1, SecretKey, SecretKey)> {
  475. let wallet = self.holders.get_mut(&holder).unwrap();
  476. let (proposal_pk, proposal_zkbin) =
  477. self.proving_keys.get(&CONSENSUS_CONTRACT_ZKAS_PROPOSAL_NS_V1).unwrap();
  478. let tx_action_benchmark = self.tx_action_benchmarks.get_mut(&TxAction::Proposal).unwrap();
  479. let timer = Instant::now();
  480. // Proposals always extend genesis block
  481. let fork_hash = wallet.state.read().await.consensus.genesis_block;
  482. // Building Consensus::Propose params
  483. let proposal_call_debris = ConsensusProposalCallBuilder {
  484. owncoin: staked_oc,
  485. slot_checkpoint,
  486. fork_hash,
  487. fork_previous_hash: fork_hash,
  488. merkle_tree: wallet.consensus_staked_merkle_tree.clone(),
  489. proposal_zkbin: proposal_zkbin.clone(),
  490. proposal_pk: proposal_pk.clone(),
  491. }
  492. .build()?;
  493. let (params, proofs, output_keypair, signature_secret_key) = (
  494. proposal_call_debris.params,
  495. proposal_call_debris.proofs,
  496. proposal_call_debris.keypair,
  497. proposal_call_debris.signature_secret,
  498. );
  499. let mut data = vec![ConsensusFunction::ProposalV1 as u8];
  500. params.encode(&mut data)?;
  501. let call = ContractCall { contract_id: *CONSENSUS_CONTRACT_ID, data };
  502. let calls = vec![call];
  503. let proofs = vec![proofs];
  504. let mut tx = Transaction { calls, proofs, signatures: vec![] };
  505. let sigs = tx.create_sigs(&mut OsRng, &[signature_secret_key])?;
  506. tx.signatures = vec![sigs];
  507. tx_action_benchmark.creation_times.push(timer.elapsed());
  508. // Calculate transaction sizes
  509. let encoded: Vec<u8> = serialize(&tx);
  510. let size = std::mem::size_of_val(&*encoded);
  511. tx_action_benchmark.sizes.push(size);
  512. let base58 = bs58::encode(&encoded).into_string();
  513. let size = std::mem::size_of_val(&*base58);
  514. tx_action_benchmark.broadcasted_sizes.push(size);
  515. Ok((tx, params, signature_secret_key, output_keypair.secret))
  516. }
  517. pub async fn execute_proposal_tx(
  518. &mut self,
  519. holder: Holder,
  520. tx: Transaction,
  521. params: &ConsensusProposalParamsV1,
  522. slot: u64,
  523. ) -> Result<()> {
  524. let wallet = self.holders.get_mut(&holder).unwrap();
  525. let tx_action_benchmark = self.tx_action_benchmarks.get_mut(&TxAction::Proposal).unwrap();
  526. let timer = Instant::now();
  527. let erroneous_txs =
  528. wallet.state.read().await.verify_transactions(&[tx], slot, true).await?;
  529. assert!(erroneous_txs.is_empty());
  530. wallet.consensus_staked_merkle_tree.append(&MerkleNode::from(params.output.coin.inner()));
  531. tx_action_benchmark.verify_times.push(timer.elapsed());
  532. Ok(())
  533. }
  534. pub async fn execute_erroneous_proposal_txs(
  535. &mut self,
  536. holder: Holder,
  537. txs: Vec<Transaction>,
  538. slot: u64,
  539. erroneous: usize,
  540. ) -> Result<()> {
  541. let wallet = self.holders.get_mut(&holder).unwrap();
  542. let tx_action_benchmark = self.tx_action_benchmarks.get_mut(&TxAction::Proposal).unwrap();
  543. let timer = Instant::now();
  544. let erroneous_txs =
  545. wallet.state.read().await.verify_transactions(&txs, slot, false).await?;
  546. assert_eq!(erroneous_txs.len(), erroneous);
  547. tx_action_benchmark.verify_times.push(timer.elapsed());
  548. Ok(())
  549. }
  550. pub async fn unstake_request(
  551. &mut self,
  552. holder: Holder,
  553. slot: u64,
  554. staked_oc: ConsensusOwnCoin,
  555. ) -> Result<(Transaction, ConsensusUnstakeReqParamsV1, SecretKey, SecretKey)> {
  556. let wallet = self.holders.get_mut(&holder).unwrap();
  557. let (burn_pk, burn_zkbin) =
  558. self.proving_keys.get(&CONSENSUS_CONTRACT_ZKAS_BURN_NS_V1).unwrap();
  559. let (mint_pk, mint_zkbin) =
  560. self.proving_keys.get(&CONSENSUS_CONTRACT_ZKAS_MINT_NS_V1).unwrap();
  561. let tx_action_benchmark =
  562. self.tx_action_benchmarks.get_mut(&TxAction::UnstakeRequest).unwrap();
  563. let epoch = wallet.state.read().await.consensus.time_keeper.slot_epoch(slot);
  564. let timer = Instant::now();
  565. // Building Consensus::Unstake params
  566. let unstake_request_call_debris = ConsensusUnstakeRequestCallBuilder {
  567. owncoin: staked_oc.clone(),
  568. epoch,
  569. tree: wallet.consensus_staked_merkle_tree.clone(),
  570. burn_zkbin: burn_zkbin.clone(),
  571. burn_pk: burn_pk.clone(),
  572. mint_zkbin: mint_zkbin.clone(),
  573. mint_pk: mint_pk.clone(),
  574. }
  575. .build()?;
  576. let (
  577. unstake_request_params,
  578. unstake_request_proofs,
  579. unstake_request_output_keypair,
  580. unstake_request_signature_secret_key,
  581. ) = (
  582. unstake_request_call_debris.params,
  583. unstake_request_call_debris.proofs,
  584. unstake_request_call_debris.keypair,
  585. unstake_request_call_debris.signature_secret,
  586. );
  587. // Building unstake request tx
  588. let mut data = vec![ConsensusFunction::UnstakeRequestV1 as u8];
  589. unstake_request_params.encode(&mut data)?;
  590. let call = ContractCall { contract_id: *CONSENSUS_CONTRACT_ID, data };
  591. let calls = vec![call];
  592. let proofs = vec![unstake_request_proofs];
  593. let mut unstake_request_tx = Transaction { calls, proofs, signatures: vec![] };
  594. let sigs =
  595. unstake_request_tx.create_sigs(&mut OsRng, &[unstake_request_signature_secret_key])?;
  596. unstake_request_tx.signatures = vec![sigs];
  597. tx_action_benchmark.creation_times.push(timer.elapsed());
  598. // Calculate transaction sizes
  599. let encoded: Vec<u8> = serialize(&unstake_request_tx);
  600. let size = std::mem::size_of_val(&*encoded);
  601. tx_action_benchmark.sizes.push(size);
  602. let base58 = bs58::encode(&encoded).into_string();
  603. let size = std::mem::size_of_val(&*base58);
  604. tx_action_benchmark.broadcasted_sizes.push(size);
  605. Ok((
  606. unstake_request_tx,
  607. unstake_request_params,
  608. unstake_request_output_keypair.secret,
  609. unstake_request_signature_secret_key,
  610. ))
  611. }
  612. pub async fn execute_unstake_request_tx(
  613. &mut self,
  614. holder: Holder,
  615. tx: Transaction,
  616. params: &ConsensusUnstakeReqParamsV1,
  617. slot: u64,
  618. ) -> Result<()> {
  619. let wallet = self.holders.get_mut(&holder).unwrap();
  620. let tx_action_benchmark =
  621. self.tx_action_benchmarks.get_mut(&TxAction::UnstakeRequest).unwrap();
  622. let timer = Instant::now();
  623. let erroneous_txs =
  624. wallet.state.read().await.verify_transactions(&[tx], slot, true).await?;
  625. assert!(erroneous_txs.is_empty());
  626. wallet.consensus_unstaked_merkle_tree.append(&MerkleNode::from(params.output.coin.inner()));
  627. tx_action_benchmark.verify_times.push(timer.elapsed());
  628. Ok(())
  629. }
  630. pub async fn execute_erroneous_unstake_request_txs(
  631. &mut self,
  632. holder: Holder,
  633. txs: Vec<Transaction>,
  634. slot: u64,
  635. erroneous: usize,
  636. ) -> Result<()> {
  637. let wallet = self.holders.get_mut(&holder).unwrap();
  638. let tx_action_benchmark =
  639. self.tx_action_benchmarks.get_mut(&TxAction::UnstakeRequest).unwrap();
  640. let timer = Instant::now();
  641. let erroneous_txs =
  642. wallet.state.read().await.verify_transactions(&txs, slot, false).await?;
  643. assert_eq!(erroneous_txs.len(), erroneous);
  644. tx_action_benchmark.verify_times.push(timer.elapsed());
  645. Ok(())
  646. }
  647. pub fn unstake(
  648. &mut self,
  649. holder: Holder,
  650. staked_oc: ConsensusOwnCoin,
  651. ) -> Result<(Transaction, MoneyUnstakeParamsV1, SecretKey)> {
  652. let wallet = self.holders.get_mut(&holder).unwrap();
  653. let (burn_pk, burn_zkbin) =
  654. self.proving_keys.get(&CONSENSUS_CONTRACT_ZKAS_BURN_NS_V1).unwrap();
  655. let (mint_pk, mint_zkbin) = self.proving_keys.get(&MONEY_CONTRACT_ZKAS_MINT_NS_V1).unwrap();
  656. let tx_action_benchmark = self.tx_action_benchmarks.get_mut(&TxAction::Unstake).unwrap();
  657. let timer = Instant::now();
  658. // Building Consensus::Unstake params
  659. let consensus_unstake_call_debris = ConsensusUnstakeCallBuilder {
  660. owncoin: staked_oc.clone(),
  661. tree: wallet.consensus_unstaked_merkle_tree.clone(),
  662. burn_zkbin: burn_zkbin.clone(),
  663. burn_pk: burn_pk.clone(),
  664. }
  665. .build()?;
  666. let (
  667. consensus_unstake_params,
  668. consensus_unstake_proofs,
  669. consensus_unstake_secret_key,
  670. consensus_unstake_value_blind,
  671. ) = (
  672. consensus_unstake_call_debris.params,
  673. consensus_unstake_call_debris.proofs,
  674. consensus_unstake_call_debris.signature_secret,
  675. consensus_unstake_call_debris.value_blind,
  676. );
  677. // Building Money::Unstake params
  678. let money_unstake_call_debris = MoneyUnstakeCallBuilder {
  679. owncoin: staked_oc.into(),
  680. recipient: self.holders.get_mut(&holder).unwrap().keypair.public,
  681. value_blind: consensus_unstake_value_blind,
  682. nullifier: consensus_unstake_params.input.nullifier,
  683. merkle_root: consensus_unstake_params.input.merkle_root,
  684. signature_public: consensus_unstake_params.input.signature_public,
  685. mint_zkbin: mint_zkbin.clone(),
  686. mint_pk: mint_pk.clone(),
  687. }
  688. .build()?;
  689. let (money_unstake_params, money_unstake_proofs) =
  690. (money_unstake_call_debris.params, money_unstake_call_debris.proofs);
  691. // Building unstake tx
  692. let mut data = vec![ConsensusFunction::UnstakeV1 as u8];
  693. consensus_unstake_params.encode(&mut data)?;
  694. let consensus_call = ContractCall { contract_id: *CONSENSUS_CONTRACT_ID, data };
  695. let mut data = vec![MoneyFunction::UnstakeV1 as u8];
  696. money_unstake_params.encode(&mut data)?;
  697. let money_call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  698. let calls = vec![consensus_call, money_call];
  699. let proofs = vec![consensus_unstake_proofs, money_unstake_proofs];
  700. let mut unstake_tx = Transaction { calls, proofs, signatures: vec![] };
  701. let consensus_sigs = unstake_tx.create_sigs(&mut OsRng, &[consensus_unstake_secret_key])?;
  702. let money_sigs = unstake_tx.create_sigs(&mut OsRng, &[consensus_unstake_secret_key])?;
  703. unstake_tx.signatures = vec![consensus_sigs, money_sigs];
  704. tx_action_benchmark.creation_times.push(timer.elapsed());
  705. // Calculate transaction sizes
  706. let encoded: Vec<u8> = serialize(&unstake_tx);
  707. let size = ::std::mem::size_of_val(&*encoded);
  708. tx_action_benchmark.sizes.push(size);
  709. let base58 = bs58::encode(&encoded).into_string();
  710. let size = ::std::mem::size_of_val(&*base58);
  711. tx_action_benchmark.broadcasted_sizes.push(size);
  712. Ok((unstake_tx, money_unstake_params, consensus_unstake_secret_key))
  713. }
  714. pub async fn execute_unstake_tx(
  715. &mut self,
  716. holder: Holder,
  717. tx: Transaction,
  718. params: &MoneyUnstakeParamsV1,
  719. slot: u64,
  720. ) -> Result<()> {
  721. let wallet = self.holders.get_mut(&holder).unwrap();
  722. let tx_action_benchmark = self.tx_action_benchmarks.get_mut(&TxAction::Unstake).unwrap();
  723. let timer = Instant::now();
  724. let erroneous_txs =
  725. wallet.state.read().await.verify_transactions(&[tx], slot, true).await?;
  726. assert!(erroneous_txs.is_empty());
  727. wallet.money_merkle_tree.append(&MerkleNode::from(params.output.coin.inner()));
  728. tx_action_benchmark.verify_times.push(timer.elapsed());
  729. Ok(())
  730. }
  731. pub fn gather_owncoin(
  732. &mut self,
  733. holder: Holder,
  734. output: Output,
  735. secret_key: Option<SecretKey>,
  736. ) -> Result<OwnCoin> {
  737. let wallet = self.holders.get_mut(&holder).unwrap();
  738. let leaf_position = wallet.money_merkle_tree.witness().unwrap();
  739. let secret_key = match secret_key {
  740. Some(key) => key,
  741. None => wallet.keypair.secret,
  742. };
  743. let note: MoneyNote = output.note.decrypt(&secret_key)?;
  744. let oc = OwnCoin {
  745. coin: Coin::from(output.coin),
  746. note: note.clone(),
  747. secret: secret_key,
  748. nullifier: Nullifier::from(poseidon_hash([wallet.keypair.secret.inner(), note.serial])),
  749. leaf_position,
  750. };
  751. Ok(oc)
  752. }
  753. pub fn gather_consensus_staked_owncoin(
  754. &mut self,
  755. holder: Holder,
  756. output: ConsensusOutput,
  757. secret_key: Option<SecretKey>,
  758. ) -> Result<ConsensusOwnCoin> {
  759. let wallet = self.holders.get_mut(&holder).unwrap();
  760. let leaf_position = wallet.consensus_staked_merkle_tree.witness().unwrap();
  761. let secret_key = match secret_key {
  762. Some(key) => key,
  763. None => wallet.keypair.secret,
  764. };
  765. let note: ConsensusNote = output.note.decrypt(&secret_key)?;
  766. let oc = ConsensusOwnCoin {
  767. coin: Coin::from(output.coin),
  768. note: note.clone(),
  769. secret: secret_key,
  770. nullifier: Nullifier::from(poseidon_hash([wallet.keypair.secret.inner(), note.serial])),
  771. leaf_position,
  772. };
  773. Ok(oc)
  774. }
  775. pub fn gather_consensus_unstaked_owncoin(
  776. &mut self,
  777. holder: Holder,
  778. output: ConsensusOutput,
  779. secret_key: Option<SecretKey>,
  780. ) -> Result<ConsensusOwnCoin> {
  781. let wallet = self.holders.get_mut(&holder).unwrap();
  782. let leaf_position = wallet.consensus_unstaked_merkle_tree.witness().unwrap();
  783. let secret_key = match secret_key {
  784. Some(key) => key,
  785. None => wallet.keypair.secret,
  786. };
  787. let note: ConsensusNote = output.note.decrypt(&secret_key)?;
  788. let oc = ConsensusOwnCoin {
  789. coin: Coin::from(output.coin),
  790. note: note.clone(),
  791. secret: secret_key,
  792. nullifier: Nullifier::from(poseidon_hash([wallet.keypair.secret.inner(), note.serial])),
  793. leaf_position,
  794. };
  795. Ok(oc)
  796. }
  797. pub async fn get_slot_checkpoint_by_slot(&self, slot: u64) -> Result<SlotCheckpoint> {
  798. let faucet = self.holders.get(&Holder::Faucet).unwrap();
  799. let slot_checkpoint =
  800. faucet.state.read().await.blockchain.get_slot_checkpoints_by_slot(&[slot])?[0]
  801. .clone()
  802. .unwrap();
  803. Ok(slot_checkpoint)
  804. }
  805. pub async fn generate_slot_checkpoint(&self, slot: u64) -> Result<SlotCheckpoint> {
  806. // We grab the genesis slot to generate slot checkpoint
  807. // using same consensus parameters
  808. let faucet = self.holders.get(&Holder::Faucet).unwrap();
  809. let genesis_block = faucet.state.read().await.consensus.genesis_block;
  810. let fork_hashes = vec![genesis_block];
  811. let fork_previous_hashes = vec![genesis_block];
  812. let genesis_slot = self.get_slot_checkpoint_by_slot(0).await?;
  813. let slot_checkpoint = SlotCheckpoint {
  814. slot,
  815. previous_eta: genesis_slot.previous_eta,
  816. fork_hashes,
  817. fork_previous_hashes,
  818. sigma1: genesis_slot.sigma1,
  819. sigma2: genesis_slot.sigma2,
  820. };
  821. // Store generated slot checkpoint
  822. for wallet in self.holders.values() {
  823. wallet.state.write().await.receive_slot_checkpoints(&[slot_checkpoint.clone()]).await?;
  824. }
  825. Ok(slot_checkpoint)
  826. }
  827. pub fn assert_trees(&self) {
  828. let faucet = self.holders.get(&Holder::Faucet).unwrap();
  829. let money_root = faucet.money_merkle_tree.root(0).unwrap();
  830. let consensus_stake_root = faucet.consensus_staked_merkle_tree.root(0).unwrap();
  831. let consensus_unstake_root = faucet.consensus_unstaked_merkle_tree.root(0).unwrap();
  832. for wallet in self.holders.values() {
  833. assert!(money_root == wallet.money_merkle_tree.root(0).unwrap());
  834. assert!(consensus_stake_root == wallet.consensus_staked_merkle_tree.root(0).unwrap());
  835. assert!(
  836. consensus_unstake_root == wallet.consensus_unstaked_merkle_tree.root(0).unwrap()
  837. );
  838. }
  839. }
  840. pub fn statistics(&self) {
  841. info!(target: "consensus", "==================== Statistics ====================");
  842. for (action, tx_action_benchmark) in &self.tx_action_benchmarks {
  843. tx_action_benchmark.statistics(action);
  844. }
  845. info!(target: "consensus", "====================================================");
  846. }
  847. }