harness.rs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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::collections::HashMap;
  19. use darkfi::{
  20. consensus::{
  21. ValidatorState, ValidatorStatePtr, TESTNET_BOOTSTRAP_TIMESTAMP, TESTNET_GENESIS_HASH_BYTES,
  22. TESTNET_GENESIS_TIMESTAMP, TESTNET_INITIAL_DISTRIBUTION,
  23. },
  24. tx::Transaction,
  25. wallet::WalletDb,
  26. zk::{empty_witnesses, ProvingKey, ZkCircuit},
  27. zkas::ZkBinary,
  28. Result,
  29. };
  30. use darkfi_sdk::{
  31. crypto::{
  32. pasta_prelude::*, ContractId, Keypair, MerkleTree, PublicKey, TokenId, MONEY_CONTRACT_ID,
  33. },
  34. db::SMART_CONTRACT_ZKAS_DB_NAME,
  35. pasta::pallas,
  36. ContractCall,
  37. };
  38. use darkfi_serial::{serialize, Encodable};
  39. use log::{info, warn};
  40. use rand::rngs::OsRng;
  41. use darkfi_money_contract::{
  42. client::build_transfer_tx, model::MoneyTransferParams, MoneyFunction,
  43. MONEY_CONTRACT_ZKAS_BURN_NS_V1, MONEY_CONTRACT_ZKAS_MINT_NS_V1,
  44. };
  45. pub fn init_logger() -> Result<()> {
  46. let mut cfg = simplelog::ConfigBuilder::new();
  47. cfg.add_filter_ignore("sled".to_string());
  48. if let Err(_) = simplelog::TermLogger::init(
  49. //simplelog::LevelFilter::Info,
  50. simplelog::LevelFilter::Debug,
  51. //simplelog::LevelFilter::Trace,
  52. cfg.build(),
  53. simplelog::TerminalMode::Mixed,
  54. simplelog::ColorChoice::Auto,
  55. ) {
  56. warn!(target: "money_harness", "Logger already initialized");
  57. }
  58. Ok(())
  59. }
  60. pub struct MoneyTestHarness {
  61. pub faucet_kp: Keypair,
  62. pub alice_kp: Keypair,
  63. pub bob_kp: Keypair,
  64. pub charlie_kp: Keypair,
  65. pub faucet_pubkeys: Vec<PublicKey>,
  66. pub faucet_state: ValidatorStatePtr,
  67. pub alice_state: ValidatorStatePtr,
  68. pub bob_state: ValidatorStatePtr,
  69. pub charlie_state: ValidatorStatePtr,
  70. pub money_contract_id: ContractId,
  71. pub proving_keys: HashMap<[u8; 32], Vec<(&'static str, ProvingKey)>>,
  72. pub mint_zkbin: ZkBinary,
  73. pub burn_zkbin: ZkBinary,
  74. pub mint_pk: ProvingKey,
  75. pub burn_pk: ProvingKey,
  76. pub faucet_merkle_tree: MerkleTree,
  77. pub alice_merkle_tree: MerkleTree,
  78. pub bob_merkle_tree: MerkleTree,
  79. pub charlie_merkle_tree: MerkleTree,
  80. }
  81. impl MoneyTestHarness {
  82. pub async fn new() -> Result<Self> {
  83. let faucet_kp = Keypair::random(&mut OsRng);
  84. let alice_kp = Keypair::random(&mut OsRng);
  85. let bob_kp = Keypair::random(&mut OsRng);
  86. let charlie_kp = Keypair::random(&mut OsRng);
  87. let faucet_pubkeys = vec![faucet_kp.public];
  88. let faucet_wallet = WalletDb::new("sqlite::memory:", "foo").await?;
  89. let alice_wallet = WalletDb::new("sqlite::memory:", "foo").await?;
  90. let bob_wallet = WalletDb::new("sqlite::memory:", "foo").await?;
  91. let charlie_wallet = WalletDb::new("sqlite::memory:", "foo").await?;
  92. let faucet_sled_db = sled::Config::new().temporary(true).open()?;
  93. let alice_sled_db = sled::Config::new().temporary(true).open()?;
  94. let bob_sled_db = sled::Config::new().temporary(true).open()?;
  95. let charlie_sled_db = sled::Config::new().temporary(true).open()?;
  96. let faucet_state = ValidatorState::new(
  97. &faucet_sled_db,
  98. *TESTNET_BOOTSTRAP_TIMESTAMP,
  99. *TESTNET_GENESIS_TIMESTAMP,
  100. *TESTNET_GENESIS_HASH_BYTES,
  101. *TESTNET_INITIAL_DISTRIBUTION,
  102. faucet_wallet,
  103. faucet_pubkeys.clone(),
  104. false,
  105. )
  106. .await?;
  107. let alice_state = ValidatorState::new(
  108. &alice_sled_db,
  109. *TESTNET_BOOTSTRAP_TIMESTAMP,
  110. *TESTNET_GENESIS_TIMESTAMP,
  111. *TESTNET_GENESIS_HASH_BYTES,
  112. *TESTNET_INITIAL_DISTRIBUTION,
  113. alice_wallet,
  114. faucet_pubkeys.clone(),
  115. false,
  116. )
  117. .await?;
  118. let bob_state = ValidatorState::new(
  119. &bob_sled_db,
  120. *TESTNET_BOOTSTRAP_TIMESTAMP,
  121. *TESTNET_GENESIS_TIMESTAMP,
  122. *TESTNET_GENESIS_HASH_BYTES,
  123. *TESTNET_INITIAL_DISTRIBUTION,
  124. bob_wallet,
  125. faucet_pubkeys.clone(),
  126. false,
  127. )
  128. .await?;
  129. let charlie_state = ValidatorState::new(
  130. &charlie_sled_db,
  131. *TESTNET_BOOTSTRAP_TIMESTAMP,
  132. *TESTNET_GENESIS_TIMESTAMP,
  133. *TESTNET_GENESIS_HASH_BYTES,
  134. *TESTNET_INITIAL_DISTRIBUTION,
  135. charlie_wallet,
  136. faucet_pubkeys.clone(),
  137. false,
  138. )
  139. .await?;
  140. let money_contract_id = *MONEY_CONTRACT_ID;
  141. let alice_sled = alice_state.read().await.blockchain.sled_db.clone();
  142. let db_handle = alice_state.read().await.blockchain.contracts.lookup(
  143. &alice_sled,
  144. &money_contract_id,
  145. SMART_CONTRACT_ZKAS_DB_NAME,
  146. )?;
  147. let mint_zkbin = db_handle.get(&serialize(&MONEY_CONTRACT_ZKAS_MINT_NS_V1))?.unwrap();
  148. let burn_zkbin = db_handle.get(&serialize(&MONEY_CONTRACT_ZKAS_BURN_NS_V1))?.unwrap();
  149. info!(target: "money_harness", "Decoding bincode");
  150. let mint_zkbin = ZkBinary::decode(&mint_zkbin)?;
  151. let burn_zkbin = ZkBinary::decode(&burn_zkbin)?;
  152. let mint_witnesses = empty_witnesses(&mint_zkbin);
  153. let burn_witnesses = empty_witnesses(&burn_zkbin);
  154. let mint_circuit = ZkCircuit::new(mint_witnesses, mint_zkbin.clone());
  155. let burn_circuit = ZkCircuit::new(burn_witnesses, burn_zkbin.clone());
  156. info!(target: "money_harness", "Creating zk proving keys");
  157. let k = 13;
  158. let mut proving_keys = HashMap::<[u8; 32], Vec<(&str, ProvingKey)>>::new();
  159. let mint_pk = ProvingKey::build(k, &mint_circuit);
  160. let burn_pk = ProvingKey::build(k, &burn_circuit);
  161. let pks = vec![
  162. (MONEY_CONTRACT_ZKAS_MINT_NS_V1, mint_pk.clone()),
  163. (MONEY_CONTRACT_ZKAS_BURN_NS_V1, burn_pk.clone()),
  164. ];
  165. proving_keys.insert(money_contract_id.inner().to_repr(), pks);
  166. let faucet_merkle_tree = MerkleTree::new(100);
  167. let alice_merkle_tree = MerkleTree::new(100);
  168. let bob_merkle_tree = MerkleTree::new(100);
  169. let charlie_merkle_tree = MerkleTree::new(100);
  170. Ok(Self {
  171. faucet_kp,
  172. alice_kp,
  173. bob_kp,
  174. charlie_kp,
  175. faucet_pubkeys,
  176. faucet_state,
  177. alice_state,
  178. bob_state,
  179. charlie_state,
  180. money_contract_id,
  181. proving_keys,
  182. mint_pk,
  183. burn_pk,
  184. mint_zkbin,
  185. burn_zkbin,
  186. faucet_merkle_tree,
  187. alice_merkle_tree,
  188. bob_merkle_tree,
  189. charlie_merkle_tree,
  190. })
  191. }
  192. pub fn airdrop(
  193. &self,
  194. amount: u64,
  195. token_id: TokenId,
  196. rcpt: &PublicKey,
  197. ) -> Result<(Transaction, MoneyTransferParams)> {
  198. let (params, proofs, secret_keys, _) = build_transfer_tx(
  199. &self.faucet_kp,
  200. rcpt,
  201. amount,
  202. token_id,
  203. pallas::Base::zero(),
  204. pallas::Base::zero(),
  205. pallas::Base::random(&mut OsRng),
  206. &[],
  207. &self.faucet_merkle_tree,
  208. &self.mint_zkbin,
  209. &self.mint_pk,
  210. &self.burn_zkbin,
  211. &self.burn_pk,
  212. true,
  213. )?;
  214. let contract_id = *MONEY_CONTRACT_ID;
  215. let mut data = vec![MoneyFunction::Transfer as u8];
  216. params.encode(&mut data)?;
  217. let calls = vec![ContractCall { contract_id, data }];
  218. let proofs = vec![proofs];
  219. let mut tx = Transaction { calls, proofs, signatures: vec![] };
  220. let sigs = tx.create_sigs(&mut OsRng, &secret_keys)?;
  221. tx.signatures = vec![sigs];
  222. Ok((tx, params))
  223. }
  224. }