main.rs 12 KB

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