main.rs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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::{
  19. fs::{read_dir, read_to_string},
  20. io::{stdin, Cursor, Read},
  21. process::exit,
  22. str::FromStr,
  23. };
  24. use clap::{Parser, Subcommand};
  25. use darkfi::{
  26. blockchain::{BlockInfo, Blockchain, BlockchainOverlay},
  27. cli_desc,
  28. tx::{ContractCallLeaf, Transaction, TransactionBuilder},
  29. util::{encoding::base64, parse::decode_base10, path::expand_path, time::Timestamp},
  30. validator::{utils::deploy_native_contracts, verification::verify_genesis_block},
  31. zk::{empty_witnesses, halo2::Field, ProvingKey, ZkCircuit},
  32. zkas::ZkBinary,
  33. Result,
  34. };
  35. use darkfi_contract_test_harness::vks;
  36. use darkfi_money_contract::{
  37. client::genesis_mint_v1::GenesisMintCallBuilder, MoneyFunction, MONEY_CONTRACT_ZKAS_MINT_NS_V1,
  38. };
  39. use darkfi_sdk::{
  40. crypto::{contract_id::MONEY_CONTRACT_ID, FuncId, Keypair, SecretKey},
  41. pasta::pallas,
  42. ContractCall,
  43. };
  44. use darkfi_serial::{deserialize_async, serialize_async, AsyncEncodable};
  45. #[derive(Parser)]
  46. #[command(about = cli_desc!())]
  47. struct Args {
  48. #[command(subcommand)]
  49. command: Subcmd,
  50. }
  51. #[derive(Subcommand)]
  52. enum Subcmd {
  53. /// Read a Darkfi genesis block from stdin and display it
  54. Display,
  55. /// Generate a Darkfi genesis block and write it to stdin
  56. Generate {
  57. #[arg(short, long, default_value = "genesis_txs")]
  58. /// Path to folder containing the genesis transactions
  59. txs_folder: String,
  60. #[arg(short, long)]
  61. /// Genesis timestamp to use, instead of current one
  62. genesis_timestamp: Option<u64>,
  63. },
  64. /// Read a Darkfi genesis block from stdin and verify it
  65. Verify,
  66. /// Generate a Darkfi genesis transaction using the secret
  67. /// key from stdin
  68. GenerateTx {
  69. /// Amount to mint for this genesis transaction
  70. amount: String,
  71. },
  72. }
  73. /// Auxiliary function to read a bs58 genesis block from stdin
  74. async fn read_block() -> Result<BlockInfo> {
  75. println!("Reading genesis block from stdin...");
  76. let mut buf = String::new();
  77. stdin().read_to_string(&mut buf)?;
  78. let bytes = base64::decode(buf.trim()).unwrap();
  79. let block = deserialize_async(&bytes).await?;
  80. Ok(block)
  81. }
  82. #[async_std::main]
  83. async fn main() -> Result<()> {
  84. // Parse arguments
  85. let args = Args::parse();
  86. // Execute a subcommand
  87. match args.command {
  88. Subcmd::Display => {
  89. let genesis_block = read_block().await;
  90. println!("{genesis_block:#?}");
  91. }
  92. Subcmd::Generate { txs_folder, genesis_timestamp } => {
  93. // Grab genesis transactions from folder
  94. let txs_folder = expand_path(&txs_folder).unwrap();
  95. let mut genesis_txs: Vec<Transaction> = vec![];
  96. for file in read_dir(txs_folder)? {
  97. let file = file?;
  98. let bytes = base64::decode(read_to_string(file.path())?.trim()).unwrap();
  99. let tx = deserialize_async(&bytes).await?;
  100. genesis_txs.push(tx);
  101. }
  102. // Generate the genesis block
  103. let mut genesis_block = BlockInfo::default();
  104. // Update timestamp if one was provided
  105. if let Some(timestamp) = genesis_timestamp {
  106. genesis_block.header.timestamp = Timestamp::from_u64(timestamp);
  107. }
  108. // Retrieve genesis producer transaction
  109. let producer_tx = genesis_block.txs.pop().unwrap();
  110. // Append genesis transactions
  111. if !genesis_txs.is_empty() {
  112. genesis_block.append_txs(genesis_txs);
  113. }
  114. genesis_block.append_txs(vec![producer_tx]);
  115. // Write generated genesis block to stdin
  116. let encoded = base64::encode(&serialize_async(&genesis_block).await);
  117. println!("{encoded}");
  118. }
  119. Subcmd::Verify => {
  120. let genesis_block = read_block().await?;
  121. let hash = genesis_block.hash();
  122. println!("Verifying genesis block: {hash}");
  123. // Initialize a temporary sled database
  124. let sled_db = sled::Config::new().temporary(true).open()?;
  125. let (_, vks) = vks::get_cached_pks_and_vks()?;
  126. vks::inject(&sled_db, &vks)?;
  127. // Create an overlay over whole blockchain
  128. let blockchain = Blockchain::new(&sled_db)?;
  129. let overlay = BlockchainOverlay::new(&blockchain)?;
  130. deploy_native_contracts(&overlay).await?;
  131. verify_genesis_block(&overlay, &genesis_block).await?;
  132. println!("Genesis block {hash} verified successfully!");
  133. }
  134. Subcmd::GenerateTx { amount } => {
  135. let mut buf = String::new();
  136. stdin().read_to_string(&mut buf)?;
  137. let Ok(bytes) = bs58::decode(&buf.trim()).into_vec() else {
  138. eprintln!("Error: Failed to decode stdin buffer");
  139. exit(2);
  140. };
  141. let secret = deserialize_async::<SecretKey>(&bytes).await?;
  142. let keypair = Keypair::new(secret);
  143. if let Err(e) = f64::from_str(&amount) {
  144. eprintln!("Invalid amount: {e:?}");
  145. exit(2);
  146. }
  147. let amount = decode_base10(&amount, 8, false)?;
  148. // Grab mint proving keys and zkbin
  149. let (pks, _) = vks::get_cached_pks_and_vks()?;
  150. let mut mint = None;
  151. for (bincode, namespace, pk) in pks {
  152. if namespace.as_str() != MONEY_CONTRACT_ZKAS_MINT_NS_V1 {
  153. continue
  154. }
  155. let mut reader = Cursor::new(pk);
  156. let zkbin = ZkBinary::decode(&bincode)?;
  157. let circuit = ZkCircuit::new(empty_witnesses(&zkbin)?, &zkbin);
  158. let proving_key = ProvingKey::read(&mut reader, circuit)?;
  159. mint = Some((proving_key, zkbin));
  160. }
  161. let Some((mint_pk, mint_zkbin)) = mint else {
  162. eprintln!("Mint proving keys not found.");
  163. exit(2);
  164. };
  165. // Build the contract call
  166. let builder = GenesisMintCallBuilder {
  167. keypair,
  168. amount,
  169. spend_hook: FuncId::none(),
  170. user_data: pallas::Base::ZERO,
  171. mint_zkbin,
  172. mint_pk,
  173. };
  174. let debris = builder.build()?;
  175. // Encode and build the transaction
  176. let mut data = vec![MoneyFunction::GenesisMintV1 as u8];
  177. debris.params.encode_async(&mut data).await?;
  178. let call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  179. let mut tx_builder =
  180. TransactionBuilder::new(ContractCallLeaf { call, proofs: debris.proofs }, vec![])?;
  181. let mut tx = tx_builder.build()?;
  182. let sigs = tx.create_sigs(&[keypair.secret])?;
  183. tx.signatures = vec![sigs];
  184. println!("{}", base64::encode(&serialize_async(&tx).await));
  185. }
  186. }
  187. Ok(())
  188. }