cli_util.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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. io::{stdin, Cursor, Read},
  20. process::exit,
  21. str::FromStr,
  22. };
  23. use rodio::{source::Source, Decoder, OutputStream};
  24. use structopt_toml::clap::{App, Arg, Shell, SubCommand};
  25. use darkfi::{
  26. cli_desc,
  27. system::sleep,
  28. tx::Transaction,
  29. util::{encoding::base64, parse::decode_base10},
  30. Error, Result,
  31. };
  32. use darkfi_money_contract::model::TokenId;
  33. use darkfi_serial::deserialize_async;
  34. use crate::{money::BALANCE_BASE10_DECIMALS, Drk};
  35. /// Auxiliary function to parse a base64 encoded transaction from stdin.
  36. pub async fn parse_tx_from_stdin() -> Result<Transaction> {
  37. let mut buf = String::new();
  38. stdin().read_to_string(&mut buf)?;
  39. let Some(bytes) = base64::decode(buf.trim()) else {
  40. eprintln!("Failed to decode transaction");
  41. exit(2);
  42. };
  43. Ok(deserialize_async(&bytes).await?)
  44. }
  45. /// Auxiliary function to parse provided string into a values pair.
  46. pub fn parse_value_pair(s: &str) -> Result<(u64, u64)> {
  47. let v: Vec<&str> = s.split(':').collect();
  48. if v.len() != 2 {
  49. eprintln!("Invalid value pair. Use a pair such as 13.37:11.0");
  50. exit(2);
  51. }
  52. let val0 = decode_base10(v[0], BALANCE_BASE10_DECIMALS, true);
  53. let val1 = decode_base10(v[1], BALANCE_BASE10_DECIMALS, true);
  54. if val0.is_err() || val1.is_err() {
  55. eprintln!("Invalid value pair. Use a pair such as 13.37:11.0");
  56. exit(2);
  57. }
  58. Ok((val0.unwrap(), val1.unwrap()))
  59. }
  60. /// Auxiliary function to parse provided string into a tokens pair.
  61. pub async fn parse_token_pair(drk: &Drk, s: &str) -> Result<(TokenId, TokenId)> {
  62. let v: Vec<&str> = s.split(':').collect();
  63. if v.len() != 2 {
  64. eprintln!("Invalid token pair. Use a pair such as:");
  65. eprintln!("WCKD:MLDY");
  66. eprintln!("or");
  67. eprintln!("A7f1RKsCUUHrSXA7a9ogmwg8p3bs6F47ggsW826HD4yd:FCuoMii64H5Ee4eVWBjP18WTFS8iLUJmGi16Qti1xFQ2");
  68. exit(2);
  69. }
  70. let tok0 = drk.get_token(v[0].to_string()).await;
  71. let tok1 = drk.get_token(v[1].to_string()).await;
  72. if tok0.is_err() || tok1.is_err() {
  73. eprintln!("Invalid token pair. Use a pair such as:");
  74. eprintln!("WCKD:MLDY");
  75. eprintln!("or");
  76. eprintln!("A7f1RKsCUUHrSXA7a9ogmwg8p3bs6F47ggsW826HD4yd:FCuoMii64H5Ee4eVWBjP18WTFS8iLUJmGi16Qti1xFQ2");
  77. exit(2);
  78. }
  79. Ok((tok0.unwrap(), tok1.unwrap()))
  80. }
  81. /// Fun police go away
  82. pub async fn kaching() {
  83. const WALLET_MP3: &[u8] = include_bytes!("../wallet.mp3");
  84. let cursor = Cursor::new(WALLET_MP3);
  85. let Ok((_stream, stream_handle)) = OutputStream::try_default() else { return };
  86. let Ok(source) = Decoder::new(cursor) else { return };
  87. if stream_handle.play_raw(source.convert_samples()).is_err() {
  88. return
  89. }
  90. sleep(2).await;
  91. }
  92. /// Auxiliary function to generate provided shell completions.
  93. pub fn generate_completions(shell: &str) -> Result<()> {
  94. // Sub-commands
  95. // Interactive
  96. let interactive = SubCommand::with_name("interactive").about("Enter Drk interactive shell");
  97. // Kaching
  98. let kaching = SubCommand::with_name("kaching").about("Fun");
  99. // Ping
  100. let ping =
  101. SubCommand::with_name("ping").about("Send a ping request to the darkfid RPC endpoint");
  102. // Completions
  103. let shell_arg = Arg::with_name("shell").help("The Shell you want to generate script for");
  104. let completions = SubCommand::with_name("completions")
  105. .about("Generate a SHELL completion script and print to stdout")
  106. .arg(shell_arg);
  107. // Wallet
  108. let initialize =
  109. Arg::with_name("initialize").long("initialize").help("Initialize wallet database");
  110. let keygen =
  111. Arg::with_name("keygen").long("keygen").help("Generate a new keypair in the wallet");
  112. let balance =
  113. Arg::with_name("balance").long("balance").help("Query the wallet for known balances");
  114. let address =
  115. Arg::with_name("address").long("address").help("Get the default address in the wallet");
  116. let addresses =
  117. Arg::with_name("addresses").long("addresses").help("Print all the addresses in the wallet");
  118. let default_address = Arg::with_name("default-address")
  119. .long("default-address")
  120. .takes_value(true)
  121. .help("Set the default address in the wallet");
  122. let secrets =
  123. Arg::with_name("secrets").long("secrets").help("Print all the secret keys from the wallet");
  124. let import_secrets = Arg::with_name("import-secrets")
  125. .long("import-secrets")
  126. .help("Import secret keys from stdin into the wallet, separated by newlines");
  127. let tree = Arg::with_name("tree").long("tree").help("Print the Merkle tree in the wallet");
  128. let coins = Arg::with_name("coins").long("coins").help("Print all the coins in the wallet");
  129. let wallet = SubCommand::with_name("wallet").about("Wallet operations").args(&vec![
  130. initialize,
  131. keygen,
  132. balance,
  133. address,
  134. addresses,
  135. default_address,
  136. secrets,
  137. import_secrets,
  138. tree,
  139. coins,
  140. ]);
  141. // Spend
  142. let spend = SubCommand::with_name("spend")
  143. .about("Read a transaction from stdin and mark its input coins as spent");
  144. // Unspend
  145. let coin = Arg::with_name("coin").help("base58-encoded coin to mark as unspent");
  146. let unspend = SubCommand::with_name("unspend").about("Unspend a coin").arg(coin);
  147. // Transfer
  148. let amount = Arg::with_name("amount").help("Amount to send");
  149. let token = Arg::with_name("token").help("Token ID to send");
  150. let recipient = Arg::with_name("recipient").help("Recipient address");
  151. let spend_hook = Arg::with_name("spend-hook").help("Optional contract spend hook to use");
  152. let user_data = Arg::with_name("user-data").help("Optional user data to use");
  153. let half_split = Arg::with_name("half-split")
  154. .long("half-split")
  155. .help("Split the output coin into two equal halves");
  156. let transfer =
  157. SubCommand::with_name("transfer").about("Create a payment transaction").args(&vec![
  158. amount.clone(),
  159. token.clone(),
  160. recipient.clone(),
  161. spend_hook.clone(),
  162. user_data.clone(),
  163. half_split,
  164. ]);
  165. // Otc
  166. let value_pair = Arg::with_name("value-pair")
  167. .short("v")
  168. .long("value-pair")
  169. .takes_value(true)
  170. .help("Value pair to send:recv (11.55:99.42)");
  171. let token_pair = Arg::with_name("token-pair")
  172. .short("t")
  173. .long("token-pair")
  174. .takes_value(true)
  175. .help("Token pair to send:recv (f00:b4r)");
  176. let init = SubCommand::with_name("init")
  177. .about("Initialize the first half of the atomic swap")
  178. .args(&vec![value_pair, token_pair]);
  179. let join =
  180. SubCommand::with_name("join").about("Build entire swap tx given the first half from stdin");
  181. let inspect = SubCommand::with_name("inspect")
  182. .about("Inspect a swap half or the full swap tx from stdin");
  183. let sign = SubCommand::with_name("sign").about("Sign a swap transaction given from stdin");
  184. let otc = SubCommand::with_name("otc")
  185. .about("OTC atomic swap")
  186. .subcommands(vec![init, join, inspect, sign]);
  187. // AttachFee
  188. let attach_fee = SubCommand::with_name("attach-fee")
  189. .about("Attach the fee call to a transaction given from stdin");
  190. // Inspect
  191. let inspect = SubCommand::with_name("inspect").about("Inspect a transaction from stdin");
  192. // Broadcast
  193. let broadcast =
  194. SubCommand::with_name("broadcast").about("Read a transaction from stdin and broadcast it");
  195. // Subscribe
  196. let subscribe = SubCommand::with_name("subscribe").about(
  197. "This subscription will listen for incoming blocks from darkfid and look \
  198. through their transactions to see if there's any that interest us. \
  199. With `drk` we look at transactions calling the money contract so we can \
  200. find coins sent to us and fill our wallet with the necessary metadata.",
  201. );
  202. // DAO
  203. let proposer_limit = Arg::with_name("proposer-limit")
  204. .help("The minimum amount of governance tokens needed to open a proposal for this DAO");
  205. let quorum = Arg::with_name("quorum")
  206. .help("Minimal threshold of participating total tokens needed for a proposal to pass");
  207. let early_exec_quorum = Arg::with_name("early-exec-quorum")
  208. .help("Minimal threshold of participating total tokens needed for a proposal to be considered as strongly supported, enabling early execution. Must be greater or equal to normal quorum.");
  209. let approval_ratio = Arg::with_name("approval-ratio")
  210. .help("The ratio of winning votes/total votes needed for a proposal to pass (2 decimals)");
  211. let gov_token_id = Arg::with_name("gov-token-id").help("DAO's governance token ID");
  212. let create = SubCommand::with_name("create").about("Create DAO parameters").args(&vec![
  213. proposer_limit,
  214. quorum,
  215. early_exec_quorum,
  216. approval_ratio,
  217. gov_token_id,
  218. ]);
  219. let view = SubCommand::with_name("view").about("View DAO data from stdin");
  220. let name = Arg::with_name("name").help("Name identifier for the DAO");
  221. let import = SubCommand::with_name("import")
  222. .about("Import DAO data from stdin")
  223. .args(&vec![name.clone()]);
  224. let update_keys = SubCommand::with_name("update-keys").about("Update DAO keys from stdin");
  225. let opt_name = Arg::with_name("dao-alias").help("Name identifier for the DAO (optional)");
  226. let list = SubCommand::with_name("list")
  227. .about("List imported DAOs (or info about a specific one)")
  228. .args(&vec![opt_name]);
  229. let balance = SubCommand::with_name("balance")
  230. .about("Show the balance of a DAO")
  231. .args(&vec![name.clone()]);
  232. let mint = SubCommand::with_name("mint")
  233. .about("Mint an imported DAO on-chain")
  234. .args(&vec![name.clone()]);
  235. let duration = Arg::with_name("duration").help("Duration of the proposal, in block windows");
  236. let propose_transfer = SubCommand::with_name("propose-transfer")
  237. .about("Create a transfer proposal for a DAO")
  238. .args(&vec![
  239. name.clone(),
  240. duration.clone(),
  241. amount,
  242. token,
  243. recipient,
  244. spend_hook.clone(),
  245. user_data.clone(),
  246. ]);
  247. let propose_generic = SubCommand::with_name("propose-generic")
  248. .about("Create a generic proposal for a DAO")
  249. .args(&vec![name.clone(), duration, user_data.clone()]);
  250. let proposals =
  251. SubCommand::with_name("proposals").about("List DAO proposals").args(&vec![name]);
  252. let bulla = Arg::with_name("bulla").help("Bulla identifier for the proposal");
  253. let export = Arg::with_name("export").help("Encrypt the proposal and encode it to base64");
  254. let mint_proposal = Arg::with_name("mint-proposal").help("Create the proposal transaction");
  255. let proposal = SubCommand::with_name("proposal").about("View a DAO proposal data").args(&vec![
  256. bulla.clone(),
  257. export,
  258. mint_proposal,
  259. ]);
  260. let proposal_import = SubCommand::with_name("proposal-import")
  261. .about("Import a base64 encoded and encrypted proposal from stdin");
  262. let vote = Arg::with_name("vote").help("Vote (0 for NO, 1 for YES)");
  263. let vote_weight =
  264. Arg::with_name("vote-weight").help("Optional vote weight (amount of governance tokens)");
  265. let vote = SubCommand::with_name("vote").about("Vote on a given proposal").args(&vec![
  266. bulla.clone(),
  267. vote,
  268. vote_weight,
  269. ]);
  270. let early = Arg::with_name("early").long("early").help("Execute the proposal early");
  271. let exec =
  272. SubCommand::with_name("exec").about("Execute a DAO proposal").args(&vec![bulla, early]);
  273. let spend_hook_cmd = SubCommand::with_name("spend-hook")
  274. .about("Print the DAO contract base58-encoded spend hook");
  275. let dao = SubCommand::with_name("dao").about("DAO functionalities").subcommands(vec![
  276. create,
  277. view,
  278. import,
  279. update_keys,
  280. list,
  281. balance,
  282. mint,
  283. propose_transfer,
  284. propose_generic,
  285. proposals,
  286. proposal,
  287. proposal_import,
  288. vote,
  289. exec,
  290. spend_hook_cmd,
  291. ]);
  292. // Scan
  293. let reset = Arg::with_name("reset")
  294. .long("reset")
  295. .help("Reset wallet state to provided block height and start scanning");
  296. let scan = SubCommand::with_name("scan")
  297. .about("Scan the blockchain and parse relevant transactions")
  298. .args(&vec![reset]);
  299. // Explorer
  300. let tx_hash = Arg::with_name("tx-hash").help("Transaction hash");
  301. let full = Arg::with_name("full").long("full").help("Print the full transaction information");
  302. let encode = Arg::with_name("encode").long("encode").help("Encode transaction to base58");
  303. let fetch_tx = SubCommand::with_name("fetch-tx")
  304. .about("Fetch a blockchain transaction by hash")
  305. .args(&vec![tx_hash, full, encode]);
  306. let simulate_tx =
  307. SubCommand::with_name("simulate-tx").about("Read a transaction from stdin and simulate it");
  308. let tx_hash = Arg::with_name("tx-hash").help("Fetch specific history record (optional)");
  309. let encode = Arg::with_name("encode")
  310. .long("encode")
  311. .help("Encode specific history record transaction to base58");
  312. let txs_history = SubCommand::with_name("txs-history")
  313. .about("Fetch broadcasted transactions history")
  314. .args(&vec![tx_hash, encode]);
  315. let clear_reverted =
  316. SubCommand::with_name("clear-reverted").about("Remove reverted transactions from history");
  317. let height = Arg::with_name("height").help("Fetch specific height record (optional)");
  318. let scanned_blocks = SubCommand::with_name("scanned-blocks")
  319. .about("Fetch scanned blocks records")
  320. .args(&vec![height]);
  321. let explorer = SubCommand::with_name("explorer")
  322. .about("Explorer related subcommands")
  323. .subcommands(vec![fetch_tx, simulate_tx, txs_history, clear_reverted, scanned_blocks]);
  324. // Alias
  325. let alias = Arg::with_name("alias").help("Token alias");
  326. let token = Arg::with_name("token").help("Token to create alias for");
  327. let add = SubCommand::with_name("add").about("Create a Token alias").args(&vec![alias, token]);
  328. let alias = Arg::with_name("alias")
  329. .short("a")
  330. .long("alias")
  331. .takes_value(true)
  332. .help("Token alias to search for");
  333. let token = Arg::with_name("token")
  334. .short("t")
  335. .long("token")
  336. .takes_value(true)
  337. .help("Token to search alias for");
  338. let show = SubCommand::with_name("show")
  339. .about(
  340. "Print alias info of optional arguments. \
  341. If no argument is provided, list all the aliases in the wallet.",
  342. )
  343. .args(&vec![alias, token]);
  344. let alias = Arg::with_name("alias").help("Token alias to remove");
  345. let remove = SubCommand::with_name("remove").about("Remove a Token alias").arg(alias);
  346. let alias = SubCommand::with_name("alias")
  347. .about("Manage Token aliases")
  348. .subcommands(vec![add, show, remove]);
  349. // Token
  350. let secret_key = Arg::with_name("secret-key").help("Mint authority secret key");
  351. let token_blind = Arg::with_name("token-blind").help("Mint authority token blind");
  352. let import = SubCommand::with_name("import")
  353. .about("Import a mint authority")
  354. .args(&vec![secret_key, token_blind]);
  355. let generate_mint =
  356. SubCommand::with_name("generate-mint").about("Generate a new mint authority");
  357. let list =
  358. SubCommand::with_name("list").about("List token IDs with available mint authorities");
  359. let token = Arg::with_name("token").help("Token ID to mint");
  360. let amount = Arg::with_name("amount").help("Amount to mint");
  361. let recipient = Arg::with_name("recipient").help("Recipient of the minted tokens");
  362. let mint = SubCommand::with_name("mint")
  363. .about("Mint tokens")
  364. .args(&vec![token, amount, recipient, spend_hook, user_data]);
  365. let token = Arg::with_name("token").help("Token ID to freeze");
  366. let freeze = SubCommand::with_name("freeze").about("Freeze a token mint").arg(token);
  367. let token = SubCommand::with_name("token").about("Token functionalities").subcommands(vec![
  368. import,
  369. generate_mint,
  370. list,
  371. mint,
  372. freeze,
  373. ]);
  374. // Main arguments
  375. let config = Arg::with_name("config")
  376. .short("c")
  377. .long("config")
  378. .takes_value(true)
  379. .help("Configuration file to use");
  380. let network = Arg::with_name("network")
  381. .long("network")
  382. .takes_value(true)
  383. .help("Blockchain network to use");
  384. let command = vec![
  385. interactive,
  386. kaching,
  387. ping,
  388. completions,
  389. wallet,
  390. spend,
  391. unspend,
  392. transfer,
  393. otc,
  394. attach_fee,
  395. inspect,
  396. broadcast,
  397. subscribe,
  398. dao,
  399. scan,
  400. explorer,
  401. alias,
  402. token,
  403. ];
  404. let fun = Arg::with_name("fun")
  405. .short("f")
  406. .long("fun")
  407. .help("Flag indicating whether you want some fun in your life");
  408. let log = Arg::with_name("log")
  409. .short("l")
  410. .long("log")
  411. .takes_value(true)
  412. .help("Set log file to ouput into");
  413. let verbose = Arg::with_name("verbose")
  414. .short("v")
  415. .multiple(true)
  416. .help("Increase verbosity (-vvv supported)");
  417. let mut app = App::new("drk")
  418. .about(cli_desc!())
  419. .args(&vec![config, network, fun, log, verbose])
  420. .subcommands(command);
  421. let shell = match Shell::from_str(shell) {
  422. Ok(s) => s,
  423. Err(e) => return Err(Error::Custom(e)),
  424. };
  425. app.gen_completions_to("./drk", shell, &mut std::io::stdout());
  426. Ok(())
  427. }