main.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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::{create_dir, read_dir, read_to_string},
  20. io::{stdin, Cursor, Read},
  21. process::exit,
  22. str::FromStr,
  23. sync::Arc,
  24. };
  25. use clap::{Parser, Subcommand};
  26. use darkfi::{
  27. blockchain::{block_store::append_tx_to_merkle_tree, BlockInfo, Blockchain, BlockchainOverlay},
  28. cli_desc,
  29. tx::{ContractCallLeaf, TransactionBuilder},
  30. util::{encoding::base64, parse::decode_base10, path::expand_path, time::Timestamp},
  31. validator::{
  32. utils::deploy_native_contracts,
  33. verification::{apply_transaction, verify_genesis_block},
  34. },
  35. zk::{empty_witnesses, ProvingKey, ZkCircuit},
  36. zkas::ZkBinary,
  37. Error, Result,
  38. };
  39. use darkfi_contract_test_harness::vks;
  40. use darkfi_money_contract::{
  41. client::genesis_mint_v1::GenesisMintCallBuilder, MoneyFunction, MONEY_CONTRACT_ZKAS_MINT_NS_V1,
  42. };
  43. use darkfi_sdk::{
  44. crypto::{contract_id::MONEY_CONTRACT_ID, FuncId, MerkleTree, PublicKey, SecretKey},
  45. pasta::{group::ff::PrimeField, pallas},
  46. ContractCall,
  47. };
  48. use darkfi_serial::{deserialize_async, serialize_async, AsyncEncodable};
  49. use sled_overlay::sled;
  50. use smol::Executor;
  51. #[derive(Parser)]
  52. #[command(about = cli_desc!())]
  53. struct Args {
  54. #[command(subcommand)]
  55. command: Subcmd,
  56. }
  57. #[derive(Subcommand)]
  58. enum Subcmd {
  59. /// Read a Darkfi genesis block from stdin and display it
  60. Display,
  61. /// Generate a Darkfi genesis block and write it to stdin
  62. Generate {
  63. #[arg(short, long, default_value = "genesis_txs")]
  64. /// Path to folder containing the genesis transactions
  65. txs_folder: String,
  66. #[arg(short, long)]
  67. /// Genesis timestamp to use, instead of current one
  68. genesis_timestamp: Option<u64>,
  69. #[arg(short, long, default_value = "120")]
  70. /// Configured PoW target
  71. pow_target: u32,
  72. },
  73. /// Read a Darkfi genesis block from stdin and verify it
  74. Verify,
  75. /// Generate a Darkfi genesis transaction using the secret
  76. /// key from stdin
  77. GenerateTx {
  78. /// Amounts to mint for this genesis transaction
  79. amounts: Vec<String>,
  80. #[arg(short, long)]
  81. /// Optional recipient's public key, in case we want to mint to a different address
  82. recipient: Option<String>,
  83. #[arg(short, long)]
  84. /// Optional contract spend hook to use
  85. spend_hook: Option<String>,
  86. #[arg(short, long)]
  87. /// Optional user data to use
  88. user_data: Option<String>,
  89. },
  90. }
  91. /// Auxiliary function to read a base64 genesis block from stdin
  92. async fn read_block() -> Result<BlockInfo> {
  93. println!("Reading genesis block from stdin...");
  94. let mut buf = String::new();
  95. stdin().read_to_string(&mut buf)?;
  96. let bytes = base64::decode(buf.trim()).unwrap();
  97. let block = deserialize_async(&bytes).await?;
  98. Ok(block)
  99. }
  100. fn main() -> Result<()> {
  101. // Initialize an executor
  102. let executor = Arc::new(Executor::new());
  103. smol::block_on(executor.run(async {
  104. // Parse arguments
  105. let args = Args::parse();
  106. // Execute a subcommand
  107. match args.command {
  108. Subcmd::Display => {
  109. let genesis_block = read_block().await;
  110. // TODO: display in more details
  111. println!("{genesis_block:?}");
  112. }
  113. Subcmd::Generate { txs_folder, genesis_timestamp, pow_target } => {
  114. // Generate the genesis block
  115. let mut genesis_block = BlockInfo::default();
  116. // Retrieve genesis producer transaction
  117. let producer_tx = genesis_block.txs.pop().unwrap();
  118. // Initialize a temporary sled database
  119. let sled_db = sled::Config::new().temporary(true).open()?;
  120. let (_, vks) = vks::get_cached_pks_and_vks()?;
  121. vks::inject(&sled_db, &vks)?;
  122. // Create an overlay over whole blockchain
  123. let blockchain = Blockchain::new(&sled_db)?;
  124. let overlay = BlockchainOverlay::new(&blockchain)?;
  125. deploy_native_contracts(&overlay, 0).await?;
  126. // Grab genesis transactions from folder
  127. let txs_folder = expand_path(&txs_folder).unwrap();
  128. if !txs_folder.exists() {
  129. create_dir(&txs_folder)?;
  130. }
  131. let mut tree = MerkleTree::new(1);
  132. for file in read_dir(txs_folder)? {
  133. let file = file?;
  134. let bytes = base64::decode(read_to_string(file.path())?.trim()).unwrap();
  135. let tx = deserialize_async(&bytes).await?;
  136. apply_transaction(&overlay, 0, pow_target, &tx, &mut tree).await?;
  137. genesis_block.txs.push(tx);
  138. }
  139. // Update timestamp if one was provided
  140. if let Some(timestamp) = genesis_timestamp {
  141. genesis_block.header.timestamp = Timestamp::from_u64(timestamp);
  142. }
  143. // Append producer tx
  144. append_tx_to_merkle_tree(&mut tree, &producer_tx);
  145. genesis_block.txs.push(producer_tx);
  146. // Update the transactions root
  147. genesis_block.header.transactions_root = tree.root(0).unwrap();
  148. // Grab the updated contracts states root
  149. let state_monotree = overlay.lock().unwrap().get_state_monotree()?;
  150. let Some(state_root) = state_monotree.get_headroot()? else {
  151. return Err(Error::ContractsStatesRootNotFoundError);
  152. };
  153. genesis_block.header.state_root = state_root;
  154. // Write generated genesis block to stdin
  155. let encoded = base64::encode(&serialize_async(&genesis_block).await);
  156. println!("{encoded}");
  157. }
  158. Subcmd::Verify => {
  159. let genesis_block = read_block().await?;
  160. let hash = genesis_block.hash();
  161. println!("Verifying genesis block: {hash}");
  162. // Initialize a temporary sled database
  163. let sled_db = sled::Config::new().temporary(true).open()?;
  164. let (_, vks) = vks::get_cached_pks_and_vks()?;
  165. vks::inject(&sled_db, &vks)?;
  166. // Create an overlay over whole blockchain
  167. let blockchain = Blockchain::new(&sled_db)?;
  168. let overlay = BlockchainOverlay::new(&blockchain)?;
  169. deploy_native_contracts(&overlay, 0).await?;
  170. verify_genesis_block(&overlay, &genesis_block, 0).await?;
  171. println!("Genesis block {hash} verified successfully!");
  172. }
  173. Subcmd::GenerateTx { amounts, recipient, spend_hook, user_data } => {
  174. let mut buf = String::new();
  175. stdin().read_to_string(&mut buf)?;
  176. let signature_secret = SecretKey::from_str(buf.trim())?;
  177. let mut coin_amounts = vec![];
  178. for amount in amounts {
  179. if let Err(e) = f64::from_str(&amount) {
  180. eprintln!("Invalid amount: {e:?}");
  181. exit(2);
  182. }
  183. coin_amounts.push(decode_base10(&amount, 8, true)?);
  184. }
  185. let recipient = match recipient {
  186. Some(r) => match PublicKey::from_str(&r) {
  187. Ok(r) => Some(r),
  188. Err(e) => {
  189. eprintln!("Invalid recipient: {e:?}");
  190. exit(2);
  191. }
  192. },
  193. None => None,
  194. };
  195. let spend_hook = match spend_hook {
  196. Some(s) => match FuncId::from_str(&s) {
  197. Ok(s) => Some(s),
  198. Err(e) => {
  199. eprintln!("Invalid spend hook: {e:?}");
  200. exit(2);
  201. }
  202. },
  203. None => None,
  204. };
  205. let user_data = match user_data {
  206. Some(u) => {
  207. let bytes: [u8; 32] = match bs58::decode(&u).into_vec()?.try_into() {
  208. Ok(b) => b,
  209. Err(e) => {
  210. eprintln!("Invalid user data: {e:?}");
  211. exit(2);
  212. }
  213. };
  214. match pallas::Base::from_repr(bytes).into() {
  215. Some(v) => Some(v),
  216. None => {
  217. eprintln!("Invalid user data");
  218. exit(2);
  219. }
  220. }
  221. }
  222. None => None,
  223. };
  224. // Grab mint proving keys and zkbin
  225. let (pks, _) = vks::get_cached_pks_and_vks()?;
  226. let mut mint = None;
  227. for (bincode, namespace, pk) in pks {
  228. if namespace.as_str() != MONEY_CONTRACT_ZKAS_MINT_NS_V1 {
  229. continue
  230. }
  231. let mut reader = Cursor::new(pk);
  232. let zkbin = ZkBinary::decode(&bincode)?;
  233. let circuit = ZkCircuit::new(empty_witnesses(&zkbin)?, &zkbin);
  234. let proving_key = ProvingKey::read(&mut reader, circuit)?;
  235. mint = Some((proving_key, zkbin));
  236. }
  237. let Some((mint_pk, mint_zkbin)) = mint else {
  238. eprintln!("Mint proving keys not found.");
  239. exit(2);
  240. };
  241. // Build the contract call
  242. let builder = GenesisMintCallBuilder {
  243. signature_public: PublicKey::from_secret(signature_secret),
  244. amounts: coin_amounts,
  245. recipient,
  246. spend_hook,
  247. user_data,
  248. mint_zkbin,
  249. mint_pk,
  250. };
  251. let debris = builder.build()?;
  252. // Encode and build the transaction
  253. let mut data = vec![MoneyFunction::GenesisMintV1 as u8];
  254. debris.params.encode_async(&mut data).await?;
  255. let call = ContractCall { contract_id: *MONEY_CONTRACT_ID, data };
  256. let mut tx_builder = TransactionBuilder::new(
  257. ContractCallLeaf { call, proofs: debris.proofs },
  258. vec![],
  259. )?;
  260. let mut tx = tx_builder.build()?;
  261. let sigs = tx.create_sigs(&[signature_secret])?;
  262. tx.signatures = vec![sigs];
  263. println!("{}", base64::encode(&serialize_async(&tx).await));
  264. }
  265. }
  266. Ok(())
  267. }))
  268. }