main.rs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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, 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, PublicKey, SecretKey},
  41. pasta::{group::ff::PrimeField, pallas},
  42. ContractCall,
  43. };
  44. use darkfi_serial::{deserialize_async, serialize_async, AsyncEncodable};
  45. use sled_overlay::sled;
  46. #[derive(Parser)]
  47. #[command(about = cli_desc!())]
  48. struct Args {
  49. #[command(subcommand)]
  50. command: Subcmd,
  51. }
  52. #[derive(Subcommand)]
  53. enum Subcmd {
  54. /// Read a Darkfi genesis block from stdin and display it
  55. Display,
  56. /// Generate a Darkfi genesis block and write it to stdin
  57. Generate {
  58. #[arg(short, long, default_value = "genesis_txs")]
  59. /// Path to folder containing the genesis transactions
  60. txs_folder: String,
  61. #[arg(short, long)]
  62. /// Genesis timestamp to use, instead of current one
  63. genesis_timestamp: Option<u64>,
  64. },
  65. /// Read a Darkfi genesis block from stdin and verify it
  66. Verify,
  67. /// Generate a Darkfi genesis transaction using the secret
  68. /// key from stdin
  69. GenerateTx {
  70. /// Amounts to mint for this genesis transaction
  71. amounts: Vec<String>,
  72. #[arg(short, long)]
  73. /// Optional recipient's public key, in case we want to mint to a different address
  74. recipient: Option<String>,
  75. #[arg(short, long)]
  76. /// Optional contract spend hook to use
  77. spend_hook: Option<String>,
  78. #[arg(short, long)]
  79. /// Optional user data to use
  80. user_data: Option<String>,
  81. },
  82. }
  83. /// Auxiliary function to read a base64 genesis block from stdin
  84. async fn read_block() -> Result<BlockInfo> {
  85. println!("Reading genesis block from stdin...");
  86. let mut buf = String::new();
  87. stdin().read_to_string(&mut buf)?;
  88. let bytes = base64::decode(buf.trim()).unwrap();
  89. let block = deserialize_async(&bytes).await?;
  90. Ok(block)
  91. }
  92. #[async_std::main]
  93. async fn main() -> Result<()> {
  94. // Parse arguments
  95. let args = Args::parse();
  96. // Execute a subcommand
  97. match args.command {
  98. Subcmd::Display => {
  99. let genesis_block = read_block().await;
  100. // TODO: display in more details
  101. println!("{genesis_block:?}");
  102. }
  103. Subcmd::Generate { txs_folder, genesis_timestamp } => {
  104. // Grab genesis transactions from folder
  105. let txs_folder = expand_path(&txs_folder).unwrap();
  106. let mut genesis_txs: Vec<Transaction> = vec![];
  107. for file in read_dir(txs_folder)? {
  108. let file = file?;
  109. let bytes = base64::decode(read_to_string(file.path())?.trim()).unwrap();
  110. let tx = deserialize_async(&bytes).await?;
  111. genesis_txs.push(tx);
  112. }
  113. // Generate the genesis block
  114. let mut genesis_block = BlockInfo::default();
  115. // Update timestamp if one was provided
  116. if let Some(timestamp) = genesis_timestamp {
  117. genesis_block.header.timestamp = Timestamp::from_u64(timestamp);
  118. }
  119. // Retrieve genesis producer transaction
  120. let producer_tx = genesis_block.txs.pop().unwrap();
  121. // Append genesis transactions
  122. if !genesis_txs.is_empty() {
  123. genesis_block.append_txs(genesis_txs);
  124. }
  125. genesis_block.append_txs(vec![producer_tx]);
  126. // Write generated genesis block to stdin
  127. let encoded = base64::encode(&serialize_async(&genesis_block).await);
  128. println!("{encoded}");
  129. }
  130. Subcmd::Verify => {
  131. let genesis_block = read_block().await?;
  132. let hash = genesis_block.hash();
  133. println!("Verifying genesis block: {hash}");
  134. // Initialize a temporary sled database
  135. let sled_db = sled::Config::new().temporary(true).open()?;
  136. let (_, vks) = vks::get_cached_pks_and_vks()?;
  137. vks::inject(&sled_db, &vks)?;
  138. // Create an overlay over whole blockchain
  139. let blockchain = Blockchain::new(&sled_db)?;
  140. let overlay = BlockchainOverlay::new(&blockchain)?;
  141. deploy_native_contracts(&overlay, 0).await?;
  142. verify_genesis_block(&overlay, &genesis_block, 0).await?;
  143. println!("Genesis block {hash} verified successfully!");
  144. }
  145. Subcmd::GenerateTx { amounts, recipient, spend_hook, user_data } => {
  146. let mut buf = String::new();
  147. stdin().read_to_string(&mut buf)?;
  148. let signature_secret = SecretKey::from_str(buf.trim())?;
  149. let mut coin_amounts = vec![];
  150. for amount in amounts {
  151. if let Err(e) = f64::from_str(&amount) {
  152. eprintln!("Invalid amount: {e:?}");
  153. exit(2);
  154. }
  155. coin_amounts.push(decode_base10(&amount, 8, true)?);
  156. }
  157. let recipient = match recipient {
  158. Some(r) => match PublicKey::from_str(&r) {
  159. Ok(r) => Some(r),
  160. Err(e) => {
  161. eprintln!("Invalid recipient: {e:?}");
  162. exit(2);
  163. }
  164. },
  165. None => None,
  166. };
  167. let spend_hook = match spend_hook {
  168. Some(s) => match FuncId::from_str(&s) {
  169. Ok(s) => Some(s),
  170. Err(e) => {
  171. eprintln!("Invalid spend hook: {e:?}");
  172. exit(2);
  173. }
  174. },
  175. None => None,
  176. };
  177. let user_data = match user_data {
  178. Some(u) => {
  179. let bytes: [u8; 32] = match bs58::decode(&u).into_vec()?.try_into() {
  180. Ok(b) => b,
  181. Err(e) => {
  182. eprintln!("Invalid user data: {e:?}");
  183. exit(2);
  184. }
  185. };
  186. match pallas::Base::from_repr(bytes).into() {
  187. Some(v) => Some(v),
  188. None => {
  189. eprintln!("Invalid user data");
  190. exit(2);
  191. }
  192. }
  193. }
  194. None => None,
  195. };
  196. // Grab mint proving keys and zkbin
  197. let (pks, _) = vks::get_cached_pks_and_vks()?;
  198. let mut mint = None;
  199. for (bincode, namespace, pk) in pks {
  200. if namespace.as_str() != MONEY_CONTRACT_ZKAS_MINT_NS_V1 {
  201. continue
  202. }
  203. let mut reader = Cursor::new(pk);
  204. let zkbin = ZkBinary::decode(&bincode)?;
  205. let circuit = ZkCircuit::new(empty_witnesses(&zkbin)?, &zkbin);
  206. let proving_key = ProvingKey::read(&mut reader, circuit)?;
  207. mint = Some((proving_key, zkbin));
  208. }
  209. let Some((mint_pk, mint_zkbin)) = mint else {
  210. eprintln!("Mint proving keys not found.");
  211. exit(2);
  212. };
  213. // Build the contract call
  214. let builder = GenesisMintCallBuilder {
  215. signature_public: PublicKey::from_secret(signature_secret),
  216. amounts: coin_amounts,
  217. recipient,
  218. spend_hook,
  219. user_data,
  220. mint_zkbin,
  221. mint_pk,
  222. };
  223. let debris = builder.build()?;
  224. // Encode and build the transaction
  225. let mut data = vec![MoneyFunction::GenesisMintV1 as u8];
  226. debris.params.encode_async(&mut data).await?;
  227. let call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  228. let mut tx_builder =
  229. TransactionBuilder::new(ContractCallLeaf { call, proofs: debris.proofs }, vec![])?;
  230. let mut tx = tx_builder.build()?;
  231. let sigs = tx.create_sigs(&[signature_secret])?;
  232. tx.signatures = vec![sigs];
  233. println!("{}", base64::encode(&serialize_async(&tx).await));
  234. }
  235. }
  236. Ok(())
  237. }