main.rs 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772
  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, Read},
  20. process::exit,
  21. str::FromStr,
  22. };
  23. use prettytable::{format, row, Table};
  24. use rand::rngs::OsRng;
  25. use smol::{channel::unbounded, fs::read_to_string, stream::StreamExt};
  26. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  27. use tracing::info;
  28. use tracing_appender::non_blocking;
  29. use url::Url;
  30. use darkfi::{
  31. async_daemonize, cli_desc,
  32. system::ExecutorPtr,
  33. util::{
  34. encoding::base64,
  35. logger::{set_terminal_writer, ChannelWriter},
  36. parse::{decode_base10, encode_base10},
  37. path::{expand_path, get_config_path},
  38. },
  39. zk::halo2::Field,
  40. Error, Result,
  41. };
  42. use darkfi_dao_contract::{blockwindow, model::DaoProposalBulla, DaoFunction};
  43. use darkfi_money_contract::model::{Coin, CoinAttributes, TokenId};
  44. use darkfi_sdk::{
  45. crypto::{
  46. keypair::{Address, Keypair, Network, SecretKey, StandardAddress},
  47. note::AeadEncryptedNote,
  48. BaseBlind, ContractId, FuncId, FuncRef, DAO_CONTRACT_ID,
  49. },
  50. pasta::{group::ff::PrimeField, pallas},
  51. tx::TransactionHash,
  52. };
  53. use darkfi_serial::{deserialize_async, serialize_async};
  54. use drk::{
  55. cli_util::{
  56. display_mining_config, generate_completions, kaching, parse_mining_config_from_stdin,
  57. parse_token_pair, parse_tx_from_stdin, parse_value_pair, print_output,
  58. },
  59. common::*,
  60. dao::{DaoParams, ProposalRecord},
  61. interactive::interactive,
  62. money::BALANCE_BASE10_DECIMALS,
  63. swap::PartialSwapData,
  64. Drk,
  65. };
  66. const CONFIG_FILE: &str = "drk_config.toml";
  67. const CONFIG_FILE_CONTENTS: &str = include_str!("../drk_config.toml");
  68. // Dev Note: when adding/modifying args here,
  69. // don't forget to update cli_util::generate_completions()
  70. // and interactive::help().
  71. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  72. #[serde(default)]
  73. #[structopt(name = "drk", about = cli_desc!())]
  74. struct Args {
  75. #[structopt(short, long)]
  76. /// Configuration file to use
  77. config: Option<String>,
  78. #[structopt(short, long, default_value = "testnet")]
  79. /// Blockchain network to use
  80. network: String,
  81. #[structopt(subcommand)]
  82. /// Sub command to execute
  83. command: Subcmd,
  84. #[structopt(short, long)]
  85. /// Flag indicating whether you want some fun in your life
  86. fun: bool,
  87. #[structopt(short, long)]
  88. /// Set log file to ouput into
  89. log: Option<String>,
  90. #[structopt(short, parse(from_occurrences))]
  91. /// Increase verbosity (-vvv supported)
  92. verbose: u8,
  93. }
  94. // Dev Note: when adding/modifying commands here,
  95. // don't forget to update cli_util::generate_completions()
  96. #[derive(Clone, Debug, Deserialize, StructOpt)]
  97. enum Subcmd {
  98. /// Enter Drk interactive shell
  99. Interactive,
  100. /// Fun
  101. Kaching,
  102. /// Send a ping request to the darkfid RPC endpoint
  103. Ping,
  104. /// Generate a SHELL completion script and print to stdout
  105. Completions {
  106. /// The Shell you want to generate script for
  107. shell: String,
  108. },
  109. /// Wallet operations
  110. Wallet {
  111. #[structopt(subcommand)]
  112. /// Sub command to execute
  113. command: WalletSubcmd,
  114. },
  115. /// Read a transaction from stdin and mark its input coins as spent
  116. Spend,
  117. /// Unspend a coin
  118. Unspend {
  119. /// base64-encoded coin to mark as unspent
  120. coin: String,
  121. },
  122. /// Create a payment transaction
  123. Transfer {
  124. /// Amount to send
  125. amount: String,
  126. /// Token ID to send
  127. token: String,
  128. /// Recipient address
  129. recipient: String,
  130. /// Optional contract spend hook to use
  131. spend_hook: Option<String>,
  132. /// Optional user data to use
  133. user_data: Option<String>,
  134. #[structopt(long)]
  135. /// Split the output coin into two equal halves
  136. half_split: bool,
  137. },
  138. /// OTC atomic swap
  139. Otc {
  140. #[structopt(subcommand)]
  141. /// Sub command to execute
  142. command: OtcSubcmd,
  143. },
  144. /// DAO functionalities
  145. Dao {
  146. #[structopt(subcommand)]
  147. /// Sub command to execute
  148. command: DaoSubcmd,
  149. },
  150. /// Attach the fee call to a transaction given from stdin
  151. AttachFee,
  152. /// Inspect a transaction from stdin
  153. Inspect,
  154. /// Read a transaction from stdin and broadcast it
  155. Broadcast,
  156. /// Scan the blockchain and parse relevant transactions
  157. Scan {
  158. #[structopt(long)]
  159. /// Reset wallet state to provided block height and start scanning
  160. reset: Option<u32>,
  161. },
  162. /// Explorer related subcommands
  163. Explorer {
  164. #[structopt(subcommand)]
  165. /// Sub command to execute
  166. command: ExplorerSubcmd,
  167. },
  168. /// Manage Token aliases
  169. Alias {
  170. #[structopt(subcommand)]
  171. /// Sub command to execute
  172. command: AliasSubcmd,
  173. },
  174. /// Token functionalities
  175. Token {
  176. #[structopt(subcommand)]
  177. /// Sub command to execute
  178. command: TokenSubcmd,
  179. },
  180. /// Contract functionalities
  181. Contract {
  182. #[structopt(subcommand)]
  183. /// Sub command to execute
  184. command: ContractSubcmd,
  185. },
  186. }
  187. #[derive(Clone, Debug, Deserialize, StructOpt)]
  188. enum WalletSubcmd {
  189. /// Initialize wallet database
  190. Initialize,
  191. /// Generate a new keypair in the wallet
  192. Keygen,
  193. /// Query the wallet for known balances
  194. Balance,
  195. /// Get the default address in the wallet
  196. Address,
  197. /// Print all the addresses in the wallet
  198. Addresses,
  199. /// Set the default address in the wallet
  200. DefaultAddress {
  201. /// Identifier of the address
  202. index: usize,
  203. },
  204. /// Print all the secret keys from the wallet
  205. Secrets,
  206. /// Import secret keys from stdin into the wallet, separated by newlines
  207. ImportSecrets,
  208. /// Print the Merkle tree in the wallet
  209. Tree,
  210. /// Print all the coins in the wallet
  211. Coins,
  212. /// Print a wallet address mining configuration
  213. MiningConfig {
  214. /// Identifier of the address
  215. index: usize,
  216. /// Optional contract spend hook to use
  217. spend_hook: Option<String>,
  218. /// Optional user data to use
  219. user_data: Option<String>,
  220. },
  221. }
  222. #[derive(Clone, Debug, Deserialize, StructOpt)]
  223. enum OtcSubcmd {
  224. /// Initialize the first half of the atomic swap
  225. Init {
  226. /// Value pair to send:recv (11.55:99.42)
  227. #[structopt(short, long)]
  228. value_pair: String,
  229. /// Token pair to send:recv (f00:b4r)
  230. #[structopt(short, long)]
  231. token_pair: String,
  232. },
  233. /// Build entire swap tx given the first half from stdin
  234. Join,
  235. /// Inspect a swap half or the full swap tx from stdin
  236. Inspect,
  237. /// Sign a swap transaction given from stdin
  238. Sign,
  239. }
  240. #[derive(Clone, Debug, Deserialize, StructOpt)]
  241. enum DaoSubcmd {
  242. /// Create DAO parameters
  243. Create {
  244. /// The minimum amount of governance tokens needed to open a proposal for this DAO
  245. proposer_limit: String,
  246. /// Minimal threshold of participating total tokens needed for a proposal to pass
  247. quorum: String,
  248. /// Minimal threshold of participating total tokens needed for a proposal to
  249. /// be considered as strongly supported, enabling early execution.
  250. /// Must be greater or equal to normal quorum.
  251. early_exec_quorum: String,
  252. /// The ratio of winning votes/total votes needed for a proposal to pass (2 decimals)
  253. approval_ratio: f64,
  254. /// DAO's governance token ID
  255. gov_token_id: String,
  256. },
  257. /// View DAO data from stdin
  258. View,
  259. /// Import DAO data from stdin
  260. Import {
  261. /// Name identifier for the DAO
  262. name: String,
  263. },
  264. /// List imported DAOs (or info about a specific one)
  265. List {
  266. /// Name identifier for the DAO (optional)
  267. name: Option<String>,
  268. },
  269. /// Show the balance of a DAO
  270. Balance {
  271. /// Name identifier for the DAO
  272. name: String,
  273. },
  274. /// Mint an imported DAO on-chain
  275. Mint {
  276. /// Name identifier for the DAO
  277. name: String,
  278. },
  279. /// Create a transfer proposal for a DAO
  280. ProposeTransfer {
  281. /// Name identifier for the DAO
  282. name: String,
  283. /// Duration of the proposal, in block windows
  284. duration: u64,
  285. /// Amount to send
  286. amount: String,
  287. /// Token ID to send
  288. token: String,
  289. /// Recipient address
  290. recipient: String,
  291. /// Optional contract spend hook to use
  292. spend_hook: Option<String>,
  293. /// Optional user data to use
  294. user_data: Option<String>,
  295. },
  296. /// Create a generic proposal for a DAO
  297. ProposeGeneric {
  298. /// Name identifier for the DAO
  299. name: String,
  300. /// Duration of the proposal, in block windows
  301. duration: u64,
  302. /// Optional user data to use
  303. user_data: Option<String>,
  304. },
  305. /// List DAO proposals
  306. Proposals {
  307. /// Name identifier for the DAO
  308. name: String,
  309. },
  310. /// View a DAO proposal data
  311. Proposal {
  312. /// Bulla identifier for the proposal
  313. bulla: String,
  314. #[structopt(long)]
  315. /// Encrypt the proposal and encode it to base64
  316. export: bool,
  317. #[structopt(long)]
  318. /// Create the proposal transaction
  319. mint_proposal: bool,
  320. },
  321. /// Import a base64 encoded and encrypted proposal from stdin
  322. ProposalImport,
  323. /// Vote on a given proposal
  324. Vote {
  325. /// Bulla identifier for the proposal
  326. bulla: String,
  327. /// Vote (0 for NO, 1 for YES)
  328. vote: u8,
  329. /// Optional vote weight (amount of governance tokens)
  330. vote_weight: Option<String>,
  331. },
  332. /// Execute a DAO proposal
  333. Exec {
  334. /// Bulla identifier for the proposal
  335. bulla: String,
  336. #[structopt(long)]
  337. /// Execute the proposal early
  338. early: bool,
  339. },
  340. /// Print the DAO contract base64-encoded spend hook
  341. SpendHook,
  342. /// Print a DAO mining configuration
  343. MiningConfig {
  344. /// Name identifier for the DAO
  345. name: String,
  346. },
  347. }
  348. #[derive(Clone, Debug, Deserialize, StructOpt)]
  349. enum ExplorerSubcmd {
  350. /// Fetch a blockchain transaction by hash
  351. FetchTx {
  352. /// Transaction hash
  353. tx_hash: String,
  354. #[structopt(long)]
  355. /// Encode transaction to base64
  356. encode: bool,
  357. },
  358. /// Read a transaction from stdin and simulate it
  359. SimulateTx,
  360. /// Fetch broadcasted transactions history
  361. TxsHistory {
  362. /// Fetch specific history record (optional)
  363. tx_hash: Option<String>,
  364. #[structopt(long)]
  365. /// Encode specific history record transaction to base64
  366. encode: bool,
  367. },
  368. /// Remove reverted transactions from history
  369. ClearReverted,
  370. /// Fetch scanned blocks records
  371. ScannedBlocks {
  372. /// Fetch specific height record (optional)
  373. height: Option<u32>,
  374. },
  375. /// Read a mining configuration from stdin and display its parts
  376. MiningConfig,
  377. }
  378. #[derive(Clone, Debug, Deserialize, StructOpt)]
  379. enum AliasSubcmd {
  380. /// Create a Token alias
  381. Add {
  382. /// Token alias
  383. alias: String,
  384. /// Token to create alias for
  385. token: String,
  386. },
  387. /// Print alias info of optional arguments.
  388. /// If no argument is provided, list all the aliases in the wallet.
  389. Show {
  390. /// Token alias to search for
  391. #[structopt(short, long)]
  392. alias: Option<String>,
  393. /// Token to search alias for
  394. #[structopt(short, long)]
  395. token: Option<String>,
  396. },
  397. /// Remove a Token alias
  398. Remove {
  399. /// Token alias to remove
  400. alias: String,
  401. },
  402. }
  403. #[derive(Clone, Debug, Deserialize, StructOpt)]
  404. enum TokenSubcmd {
  405. /// Import a mint authority
  406. Import {
  407. /// Mint authority secret key
  408. secret_key: String,
  409. /// Mint authority token blind
  410. token_blind: String,
  411. },
  412. /// Generate a new mint authority
  413. GenerateMint,
  414. /// List token IDs with available mint authorities
  415. List,
  416. /// Mint tokens
  417. Mint {
  418. /// Token ID to mint
  419. token: String,
  420. /// Amount to mint
  421. amount: String,
  422. /// Recipient of the minted tokens
  423. recipient: String,
  424. /// Optional contract spend hook to use
  425. spend_hook: Option<String>,
  426. /// Optional user data to use
  427. user_data: Option<String>,
  428. },
  429. /// Freeze a token mint
  430. Freeze {
  431. /// Token ID to freeze
  432. token: String,
  433. },
  434. }
  435. #[derive(Clone, Debug, Deserialize, StructOpt)]
  436. enum ContractSubcmd {
  437. /// Generate a new deploy authority
  438. GenerateDeploy,
  439. /// List deploy authorities in the wallet (or a specific one)
  440. List {
  441. /// Contract ID (optional)
  442. contract_id: Option<String>,
  443. },
  444. /// Export a contract history record wasm bincode and deployment instruction, encoded to base64
  445. ExportData {
  446. /// Record transaction hash
  447. tx_hash: String,
  448. },
  449. /// Deploy a smart contract
  450. Deploy {
  451. /// Contract ID (deploy authority)
  452. deploy_auth: String,
  453. /// Path to contract wasm bincode
  454. wasm_path: String,
  455. /// Optional path to serialized deploy instruction
  456. deploy_ix: Option<String>,
  457. },
  458. /// Lock a smart contract
  459. Lock {
  460. /// Contract ID (deploy authority)
  461. deploy_auth: String,
  462. },
  463. }
  464. /// Defines a blockchain network configuration.
  465. /// Default values correspond to a local network.
  466. #[derive(Clone, Debug, serde::Deserialize, structopt::StructOpt, structopt_toml::StructOptToml)]
  467. #[structopt()]
  468. struct BlockchainNetwork {
  469. #[structopt(long, default_value = "~/.local/share/darkfi/drk/localnet/cache")]
  470. /// Path to blockchain cache database
  471. cache_path: String,
  472. #[structopt(long, default_value = "~/.local/share/darkfi/drk/localnet/wallet.db")]
  473. /// Path to wallet database
  474. wallet_path: String,
  475. #[structopt(long, default_value = "changeme")]
  476. /// Password for the wallet database
  477. wallet_pass: String,
  478. #[structopt(short, long, default_value = "tcp://127.0.0.1:8240")]
  479. /// darkfid JSON-RPC endpoint
  480. endpoint: Url,
  481. #[structopt(long, default_value = "~/.local/share/darkfi/drk/localnet/history.txt")]
  482. /// Path to interactive shell history file
  483. history_path: String,
  484. }
  485. /// Auxiliary function to parse darkfid configuration file and extract requested
  486. /// blockchain network config.
  487. async fn parse_blockchain_config(
  488. config: Option<String>,
  489. network: &str,
  490. ) -> Result<(Network, BlockchainNetwork)> {
  491. // Grab network
  492. let used_net = match network {
  493. "mainnet" | "localnet" => Network::Mainnet,
  494. "testnet" => Network::Testnet,
  495. _ => return Err(Error::ParseFailed("Invalid blockchain network")),
  496. };
  497. // Grab config path
  498. let config_path = get_config_path(config, CONFIG_FILE)?;
  499. // Parse TOML file contents
  500. let contents = read_to_string(&config_path).await?;
  501. let contents: toml::Value = match toml::from_str(&contents) {
  502. Ok(v) => v,
  503. Err(e) => {
  504. eprintln!("Failed parsing TOML config: {e}");
  505. return Err(Error::ParseFailed("Failed parsing TOML config"))
  506. }
  507. };
  508. // Grab requested network config
  509. let Some(table) = contents.as_table() else { return Err(Error::ParseFailed("TOML not a map")) };
  510. let Some(network_configs) = table.get("network_config") else {
  511. return Err(Error::ParseFailed("TOML does not contain network configurations"))
  512. };
  513. let Some(network_configs) = network_configs.as_table() else {
  514. return Err(Error::ParseFailed("`network_config` not a map"))
  515. };
  516. let Some(network_config) = network_configs.get(network) else {
  517. return Err(Error::ParseFailed("TOML does not contain requested network configuration"))
  518. };
  519. let network_config = toml::to_string(&network_config).unwrap();
  520. let network_config =
  521. match BlockchainNetwork::from_iter_with_toml::<Vec<String>>(&network_config, vec![]) {
  522. Ok(v) => v,
  523. Err(e) => {
  524. eprintln!("Failed parsing requested network configuration: {e}");
  525. return Err(Error::ParseFailed("Failed parsing requested network configuration"))
  526. }
  527. };
  528. Ok((used_net, network_config))
  529. }
  530. /// Auxiliary function to create a `Drk` wallet for provided configuration.
  531. async fn new_wallet(
  532. network: Network,
  533. cache_path: String,
  534. wallet_path: String,
  535. wallet_pass: String,
  536. endpoint: Option<Url>,
  537. ex: &ExecutorPtr,
  538. fun: bool,
  539. ) -> Drk {
  540. // Script kiddies protection
  541. if wallet_pass == "changeme" {
  542. eprintln!("Please don't use default wallet password...");
  543. exit(2);
  544. }
  545. match Drk::new(network, cache_path, wallet_path, wallet_pass, endpoint, ex, fun).await {
  546. Ok(wallet) => wallet,
  547. Err(e) => {
  548. eprintln!("Error initializing wallet: {e}");
  549. exit(2);
  550. }
  551. }
  552. }
  553. async_daemonize!(realmain);
  554. async fn realmain(args: Args, ex: ExecutorPtr) -> Result<()> {
  555. // Grab blockchain network configuration
  556. let (network, blockchain_config) = match args.network.as_str() {
  557. "localnet" => parse_blockchain_config(args.config, "localnet").await?,
  558. "testnet" => parse_blockchain_config(args.config, "testnet").await?,
  559. "mainnet" => parse_blockchain_config(args.config, "mainnet").await?,
  560. _ => {
  561. eprintln!("Unsupported chain `{}`", args.network);
  562. return Err(Error::UnsupportedChain)
  563. }
  564. };
  565. match args.command {
  566. Subcmd::Interactive => {
  567. // Create an unbounded smol channel, so we can have a
  568. // printing queue the background logger and tasks can
  569. // submit messages to so the shell prints them.
  570. let (shell_sender, shell_receiver) = unbounded();
  571. // Set the logging writer
  572. let (non_blocking, _guard) =
  573. non_blocking(ChannelWriter { sender: shell_sender.clone() });
  574. set_terminal_writer(args.verbose, non_blocking)?;
  575. let drk = new_wallet(
  576. network,
  577. blockchain_config.cache_path,
  578. blockchain_config.wallet_path,
  579. blockchain_config.wallet_pass,
  580. Some(blockchain_config.endpoint.clone()),
  581. &ex,
  582. args.fun,
  583. )
  584. .await
  585. .into_ptr();
  586. interactive(
  587. &drk,
  588. &blockchain_config.endpoint,
  589. &blockchain_config.history_path,
  590. &shell_sender,
  591. &shell_receiver,
  592. &ex,
  593. )
  594. .await;
  595. drk.read().await.stop_rpc_client().await?;
  596. Ok(())
  597. }
  598. Subcmd::Kaching => {
  599. if !args.fun {
  600. println!("Apparently you don't like fun...");
  601. return Ok(())
  602. }
  603. kaching().await;
  604. Ok(())
  605. }
  606. Subcmd::Ping => {
  607. let drk = new_wallet(
  608. network,
  609. blockchain_config.cache_path,
  610. blockchain_config.wallet_path,
  611. blockchain_config.wallet_pass,
  612. Some(blockchain_config.endpoint),
  613. &ex,
  614. args.fun,
  615. )
  616. .await;
  617. let mut output = vec![];
  618. if let Err(e) = drk.ping(&mut output).await {
  619. print_output(&output);
  620. return Err(e)
  621. };
  622. print_output(&output);
  623. drk.stop_rpc_client().await
  624. }
  625. Subcmd::Completions { shell } => {
  626. println!("{}", generate_completions(&shell)?);
  627. Ok(())
  628. }
  629. Subcmd::Wallet { command } => {
  630. let drk = new_wallet(
  631. network,
  632. blockchain_config.cache_path,
  633. blockchain_config.wallet_path,
  634. blockchain_config.wallet_pass,
  635. None,
  636. &ex,
  637. args.fun,
  638. )
  639. .await;
  640. match command {
  641. WalletSubcmd::Initialize => {
  642. if let Err(e) = drk.initialize_wallet().await {
  643. eprintln!("Error initializing wallet: {e}");
  644. exit(2);
  645. }
  646. let mut output = vec![];
  647. if let Err(e) = drk.initialize_money(&mut output).await {
  648. print_output(&output);
  649. eprintln!("Failed to initialize Money: {e}");
  650. exit(2);
  651. }
  652. print_output(&output);
  653. if let Err(e) = drk.initialize_dao().await {
  654. eprintln!("Failed to initialize DAO: {e}");
  655. exit(2);
  656. }
  657. if let Err(e) = drk.initialize_deployooor() {
  658. eprintln!("Failed to initialize Deployooor: {e}");
  659. exit(2);
  660. }
  661. }
  662. WalletSubcmd::Keygen => {
  663. let mut output = vec![];
  664. if let Err(e) = drk.money_keygen(&mut output).await {
  665. print_output(&output);
  666. eprintln!("Failed to generate keypair: {e}");
  667. exit(2);
  668. }
  669. print_output(&output);
  670. }
  671. WalletSubcmd::Balance => {
  672. let balmap = drk.money_balance().await?;
  673. let aliases_map = drk.get_aliases_mapped_by_token().await?;
  674. // Create a prettytable with the new data:
  675. let mut table = Table::new();
  676. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  677. table.set_titles(row!["Token ID", "Aliases", "Balance"]);
  678. for (token_id, balance) in balmap.iter() {
  679. let aliases = match aliases_map.get(token_id) {
  680. Some(a) => a,
  681. None => "-",
  682. };
  683. table.add_row(row![
  684. token_id,
  685. aliases,
  686. encode_base10(*balance, BALANCE_BASE10_DECIMALS)
  687. ]);
  688. }
  689. if table.is_empty() {
  690. println!("No unspent balances found");
  691. } else {
  692. println!("{table}");
  693. }
  694. }
  695. WalletSubcmd::Address => match drk.default_address().await {
  696. Ok(public_key) => {
  697. let address: Address =
  698. StandardAddress::from_public(drk.network, public_key).into();
  699. println!("{address}");
  700. }
  701. Err(e) => {
  702. eprintln!("Failed to fetch default address: {e}");
  703. exit(2);
  704. }
  705. },
  706. WalletSubcmd::Addresses => {
  707. let addresses = drk.addresses().await?;
  708. let table = prettytable_addrs(drk.network, &addresses);
  709. if table.is_empty() {
  710. println!("No addresses found");
  711. } else {
  712. println!("{table}");
  713. }
  714. }
  715. WalletSubcmd::DefaultAddress { index } => {
  716. if let Err(e) = drk.set_default_address(index) {
  717. eprintln!("Failed to set default address: {e}");
  718. exit(2);
  719. }
  720. }
  721. WalletSubcmd::Secrets => {
  722. for secret in drk.get_money_secrets().await? {
  723. println!("{secret}");
  724. }
  725. }
  726. WalletSubcmd::ImportSecrets => {
  727. let mut secrets = vec![];
  728. let lines = stdin().lines();
  729. for (i, line) in lines.enumerate() {
  730. if let Ok(line) = line {
  731. let bytes = bs58::decode(&line.trim()).into_vec()?;
  732. let Ok(secret) = deserialize_async(&bytes).await else {
  733. println!("Warning: Failed to deserialize secret on line {i}");
  734. continue
  735. };
  736. secrets.push(secret);
  737. }
  738. }
  739. let mut output = vec![];
  740. let pubkeys = match drk.import_money_secrets(secrets, &mut output).await {
  741. Ok(p) => {
  742. print_output(&output);
  743. p
  744. }
  745. Err(e) => {
  746. print_output(&output);
  747. eprintln!("Failed to import secret keys into wallet: {e}");
  748. exit(2);
  749. }
  750. };
  751. for key in pubkeys {
  752. println!("{key}");
  753. }
  754. }
  755. WalletSubcmd::Tree => {
  756. println!("{:#?}", drk.get_money_tree().await?);
  757. }
  758. WalletSubcmd::Coins => {
  759. let coins = drk.get_coins(true).await?;
  760. if coins.is_empty() {
  761. return Ok(())
  762. }
  763. let aliases_map = drk.get_aliases_mapped_by_token().await?;
  764. let table = prettytable_coins(&coins, &aliases_map);
  765. println!("{table}");
  766. }
  767. WalletSubcmd::MiningConfig { index, spend_hook, user_data } => {
  768. let spend_hook = match spend_hook {
  769. Some(s) => match FuncId::from_str(&s) {
  770. Ok(s) => Some(s),
  771. Err(e) => {
  772. eprintln!("Invalid spend hook: {e}");
  773. exit(2);
  774. }
  775. },
  776. None => None,
  777. };
  778. let user_data = match user_data {
  779. Some(u) => {
  780. let bytes: [u8; 32] = match bs58::decode(&u).into_vec()?.try_into() {
  781. Ok(b) => b,
  782. Err(e) => {
  783. eprintln!("Invalid user data: {e:?}");
  784. exit(2);
  785. }
  786. };
  787. match pallas::Base::from_repr(bytes).into() {
  788. Some(v) => Some(v),
  789. None => {
  790. eprintln!("Invalid user data");
  791. exit(2);
  792. }
  793. }
  794. }
  795. None => None,
  796. };
  797. let mut output = vec![];
  798. if let Err(e) =
  799. drk.mining_config(index, spend_hook, user_data, &mut output).await
  800. {
  801. print_output(&output);
  802. eprintln!("Failed to generate wallet mining configuration: {e}");
  803. exit(2);
  804. }
  805. print_output(&output);
  806. }
  807. }
  808. Ok(())
  809. }
  810. Subcmd::Spend => {
  811. let tx = parse_tx_from_stdin().await?;
  812. let drk = new_wallet(
  813. network,
  814. blockchain_config.cache_path,
  815. blockchain_config.wallet_path,
  816. blockchain_config.wallet_pass,
  817. None,
  818. &ex,
  819. args.fun,
  820. )
  821. .await;
  822. let mut output = vec![];
  823. if let Err(e) = drk.mark_tx_spend(&tx, &mut output).await {
  824. print_output(&output);
  825. eprintln!("Failed to mark transaction coins as spent: {e}");
  826. exit(2);
  827. };
  828. print_output(&output);
  829. Ok(())
  830. }
  831. Subcmd::Unspend { coin } => {
  832. let bytes: [u8; 32] = match bs58::decode(&coin).into_vec()?.try_into() {
  833. Ok(b) => b,
  834. Err(e) => {
  835. eprintln!("Invalid coin: {e:?}");
  836. exit(2);
  837. }
  838. };
  839. let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
  840. Some(v) => v,
  841. None => {
  842. eprintln!("Invalid coin");
  843. exit(2);
  844. }
  845. };
  846. let coin = Coin::from(elem);
  847. let drk = new_wallet(
  848. network,
  849. blockchain_config.cache_path,
  850. blockchain_config.wallet_path,
  851. blockchain_config.wallet_pass,
  852. None,
  853. &ex,
  854. args.fun,
  855. )
  856. .await;
  857. if let Err(e) = drk.unspend_coin(&coin).await {
  858. eprintln!("Failed to mark coin as unspent: {e}");
  859. exit(2);
  860. }
  861. Ok(())
  862. }
  863. Subcmd::Transfer { amount, token, recipient, spend_hook, user_data, half_split } => {
  864. let drk = new_wallet(
  865. network,
  866. blockchain_config.cache_path,
  867. blockchain_config.wallet_path,
  868. blockchain_config.wallet_pass,
  869. Some(blockchain_config.endpoint),
  870. &ex,
  871. args.fun,
  872. )
  873. .await;
  874. if let Err(e) = f64::from_str(&amount) {
  875. eprintln!("Invalid amount: {e}");
  876. exit(2);
  877. }
  878. let rcpt = match Address::from_str(&recipient) {
  879. Ok(r) => r,
  880. Err(e) => {
  881. eprintln!("Invalid recipient: {e}");
  882. exit(2);
  883. }
  884. };
  885. if rcpt.network() != drk.network {
  886. eprintln!("Recipient address prefix mismatch");
  887. exit(2);
  888. }
  889. let token_id = match drk.get_token(token).await {
  890. Ok(t) => t,
  891. Err(e) => {
  892. eprintln!("Invalid token alias: {e}");
  893. exit(2);
  894. }
  895. };
  896. let spend_hook = match spend_hook {
  897. Some(s) => match FuncId::from_str(&s) {
  898. Ok(s) => Some(s),
  899. Err(e) => {
  900. eprintln!("Invalid spend hook: {e}");
  901. exit(2);
  902. }
  903. },
  904. None => None,
  905. };
  906. let user_data = match user_data {
  907. Some(u) => {
  908. let bytes: [u8; 32] = match bs58::decode(&u).into_vec()?.try_into() {
  909. Ok(b) => b,
  910. Err(e) => {
  911. eprintln!("Invalid user data: {e:?}");
  912. exit(2);
  913. }
  914. };
  915. match pallas::Base::from_repr(bytes).into() {
  916. Some(v) => Some(v),
  917. None => {
  918. eprintln!("Invalid user data");
  919. exit(2);
  920. }
  921. }
  922. }
  923. None => None,
  924. };
  925. let tx = match drk
  926. .transfer(&amount, token_id, *rcpt.public_key(), spend_hook, user_data, half_split)
  927. .await
  928. {
  929. Ok(t) => t,
  930. Err(e) => {
  931. eprintln!("Failed to create payment transaction: {e}");
  932. exit(2);
  933. }
  934. };
  935. println!("{}", base64::encode(&serialize_async(&tx).await));
  936. drk.stop_rpc_client().await
  937. }
  938. Subcmd::Otc { command } => match command {
  939. OtcSubcmd::Init { value_pair, token_pair } => {
  940. let drk = new_wallet(
  941. network,
  942. blockchain_config.cache_path,
  943. blockchain_config.wallet_path,
  944. blockchain_config.wallet_pass,
  945. Some(blockchain_config.endpoint),
  946. &ex,
  947. args.fun,
  948. )
  949. .await;
  950. let value_pair = parse_value_pair(&value_pair)?;
  951. let token_pair = parse_token_pair(&drk, &token_pair).await?;
  952. let half = match drk.init_swap(value_pair, token_pair, None, None, None).await {
  953. Ok(h) => h,
  954. Err(e) => {
  955. eprintln!("Failed to create swap transaction half: {e}");
  956. exit(2);
  957. }
  958. };
  959. println!("{}", base64::encode(&serialize_async(&half).await));
  960. drk.stop_rpc_client().await
  961. }
  962. OtcSubcmd::Join => {
  963. let mut buf = String::new();
  964. stdin().read_to_string(&mut buf)?;
  965. let Some(bytes) = base64::decode(buf.trim()) else {
  966. eprintln!("Failed to decode partial swap data");
  967. exit(2);
  968. };
  969. let partial: PartialSwapData = deserialize_async(&bytes).await?;
  970. let drk = new_wallet(
  971. network,
  972. blockchain_config.cache_path,
  973. blockchain_config.wallet_path,
  974. blockchain_config.wallet_pass,
  975. Some(blockchain_config.endpoint),
  976. &ex,
  977. args.fun,
  978. )
  979. .await;
  980. let tx = match drk.join_swap(partial, None, None, None).await {
  981. Ok(tx) => tx,
  982. Err(e) => {
  983. eprintln!("Failed to create a join swap transaction: {e}");
  984. exit(2);
  985. }
  986. };
  987. println!("{}", base64::encode(&serialize_async(&tx).await));
  988. drk.stop_rpc_client().await
  989. }
  990. OtcSubcmd::Inspect => {
  991. let mut buf = String::new();
  992. stdin().read_to_string(&mut buf)?;
  993. let Some(bytes) = base64::decode(buf.trim()) else {
  994. eprintln!("Failed to decode swap transaction");
  995. exit(2);
  996. };
  997. let drk = new_wallet(
  998. network,
  999. blockchain_config.cache_path,
  1000. blockchain_config.wallet_path,
  1001. blockchain_config.wallet_pass,
  1002. None,
  1003. &ex,
  1004. args.fun,
  1005. )
  1006. .await;
  1007. let mut output = vec![];
  1008. if let Err(e) = drk.inspect_swap(bytes, &mut output).await {
  1009. print_output(&output);
  1010. eprintln!("Failed to inspect swap: {e}");
  1011. exit(2);
  1012. };
  1013. print_output(&output);
  1014. Ok(())
  1015. }
  1016. OtcSubcmd::Sign => {
  1017. let mut tx = parse_tx_from_stdin().await?;
  1018. let drk = new_wallet(
  1019. network,
  1020. blockchain_config.cache_path,
  1021. blockchain_config.wallet_path,
  1022. blockchain_config.wallet_pass,
  1023. None,
  1024. &ex,
  1025. args.fun,
  1026. )
  1027. .await;
  1028. if let Err(e) = drk.sign_swap(&mut tx).await {
  1029. eprintln!("Failed to sign joined swap transaction: {e}");
  1030. exit(2);
  1031. };
  1032. println!("{}", base64::encode(&serialize_async(&tx).await));
  1033. Ok(())
  1034. }
  1035. },
  1036. Subcmd::Dao { command } => match command {
  1037. DaoSubcmd::Create {
  1038. proposer_limit,
  1039. quorum,
  1040. early_exec_quorum,
  1041. approval_ratio,
  1042. gov_token_id,
  1043. } => {
  1044. if let Err(e) = f64::from_str(&proposer_limit) {
  1045. eprintln!("Invalid proposer limit: {e}");
  1046. exit(2);
  1047. }
  1048. if let Err(e) = f64::from_str(&quorum) {
  1049. eprintln!("Invalid quorum: {e}");
  1050. exit(2);
  1051. }
  1052. if let Err(e) = f64::from_str(&early_exec_quorum) {
  1053. eprintln!("Invalid early exec quorum: {e}");
  1054. exit(2);
  1055. }
  1056. let proposer_limit = decode_base10(&proposer_limit, BALANCE_BASE10_DECIMALS, true)?;
  1057. let quorum = decode_base10(&quorum, BALANCE_BASE10_DECIMALS, true)?;
  1058. let early_exec_quorum =
  1059. decode_base10(&early_exec_quorum, BALANCE_BASE10_DECIMALS, true)?;
  1060. if approval_ratio > 1.0 {
  1061. eprintln!("Error: Approval ratio cannot be >1.0");
  1062. exit(2);
  1063. }
  1064. let approval_ratio_base = 100_u64;
  1065. let approval_ratio_quot = (approval_ratio * approval_ratio_base as f64) as u64;
  1066. let drk = new_wallet(
  1067. network,
  1068. blockchain_config.cache_path,
  1069. blockchain_config.wallet_path,
  1070. blockchain_config.wallet_pass,
  1071. None,
  1072. &ex,
  1073. args.fun,
  1074. )
  1075. .await;
  1076. let gov_token_id = match drk.get_token(gov_token_id).await {
  1077. Ok(g) => g,
  1078. Err(e) => {
  1079. eprintln!("Invalid Token ID: {e}");
  1080. exit(2);
  1081. }
  1082. };
  1083. let notes_keypair = Keypair::random(&mut OsRng);
  1084. let proposer_keypair = Keypair::random(&mut OsRng);
  1085. let proposals_keypair = Keypair::random(&mut OsRng);
  1086. let votes_keypair = Keypair::random(&mut OsRng);
  1087. let exec_keypair = Keypair::random(&mut OsRng);
  1088. let early_exec_keypair = Keypair::random(&mut OsRng);
  1089. let bulla_blind = BaseBlind::random(&mut OsRng);
  1090. let params = DaoParams::new(
  1091. proposer_limit,
  1092. quorum,
  1093. early_exec_quorum,
  1094. approval_ratio_base,
  1095. approval_ratio_quot,
  1096. gov_token_id,
  1097. Some(notes_keypair.secret),
  1098. notes_keypair.public,
  1099. Some(proposer_keypair.secret),
  1100. proposer_keypair.public,
  1101. Some(proposals_keypair.secret),
  1102. proposals_keypair.public,
  1103. Some(votes_keypair.secret),
  1104. votes_keypair.public,
  1105. Some(exec_keypair.secret),
  1106. exec_keypair.public,
  1107. Some(early_exec_keypair.secret),
  1108. early_exec_keypair.public,
  1109. bulla_blind,
  1110. );
  1111. println!("{}", params.toml_str());
  1112. Ok(())
  1113. }
  1114. DaoSubcmd::View => {
  1115. let mut buf = String::new();
  1116. stdin().read_to_string(&mut buf)?;
  1117. let params = DaoParams::from_toml_str(&buf)?;
  1118. println!("{params}");
  1119. Ok(())
  1120. }
  1121. DaoSubcmd::Import { name } => {
  1122. let mut buf = String::new();
  1123. stdin().read_to_string(&mut buf)?;
  1124. let params = DaoParams::from_toml_str(&buf)?;
  1125. let drk = new_wallet(
  1126. network,
  1127. blockchain_config.cache_path,
  1128. blockchain_config.wallet_path,
  1129. blockchain_config.wallet_pass,
  1130. None,
  1131. &ex,
  1132. args.fun,
  1133. )
  1134. .await;
  1135. let mut output = vec![];
  1136. if let Err(e) = drk.import_dao(&name, &params, &mut output).await {
  1137. print_output(&output);
  1138. eprintln!("Failed to import DAO: {e}");
  1139. exit(2);
  1140. }
  1141. print_output(&output);
  1142. Ok(())
  1143. }
  1144. DaoSubcmd::List { name } => {
  1145. let drk = new_wallet(
  1146. network,
  1147. blockchain_config.cache_path,
  1148. blockchain_config.wallet_path,
  1149. blockchain_config.wallet_pass,
  1150. None,
  1151. &ex,
  1152. args.fun,
  1153. )
  1154. .await;
  1155. let mut output = vec![];
  1156. if let Err(e) = drk.dao_list(&name, &mut output).await {
  1157. print_output(&output);
  1158. eprintln!("Failed to list DAO: {e}");
  1159. exit(2);
  1160. }
  1161. print_output(&output);
  1162. Ok(())
  1163. }
  1164. DaoSubcmd::Balance { name } => {
  1165. let drk = new_wallet(
  1166. network,
  1167. blockchain_config.cache_path,
  1168. blockchain_config.wallet_path,
  1169. blockchain_config.wallet_pass,
  1170. None,
  1171. &ex,
  1172. args.fun,
  1173. )
  1174. .await;
  1175. let balmap = match drk.dao_balance(&name).await {
  1176. Ok(b) => b,
  1177. Err(e) => {
  1178. eprintln!("Failed to fetch DAO balance: {e}");
  1179. exit(2);
  1180. }
  1181. };
  1182. let aliases_map = match drk.get_aliases_mapped_by_token().await {
  1183. Ok(a) => a,
  1184. Err(e) => {
  1185. eprintln!("Failed to fetch wallet aliases: {e}");
  1186. exit(2);
  1187. }
  1188. };
  1189. let table = prettytable_balance(&balmap, &aliases_map);
  1190. if table.is_empty() {
  1191. println!("No unspent balances found");
  1192. } else {
  1193. println!("{table}");
  1194. }
  1195. Ok(())
  1196. }
  1197. DaoSubcmd::Mint { name } => {
  1198. let drk = new_wallet(
  1199. network,
  1200. blockchain_config.cache_path,
  1201. blockchain_config.wallet_path,
  1202. blockchain_config.wallet_pass,
  1203. Some(blockchain_config.endpoint),
  1204. &ex,
  1205. args.fun,
  1206. )
  1207. .await;
  1208. let tx = match drk.dao_mint(&name).await {
  1209. Ok(tx) => tx,
  1210. Err(e) => {
  1211. eprintln!("Failed to mint DAO: {e}");
  1212. exit(2);
  1213. }
  1214. };
  1215. println!("{}", base64::encode(&serialize_async(&tx).await));
  1216. drk.stop_rpc_client().await
  1217. }
  1218. DaoSubcmd::ProposeTransfer {
  1219. name,
  1220. duration,
  1221. amount,
  1222. token,
  1223. recipient,
  1224. spend_hook,
  1225. user_data,
  1226. } => {
  1227. let drk = new_wallet(
  1228. network,
  1229. blockchain_config.cache_path,
  1230. blockchain_config.wallet_path,
  1231. blockchain_config.wallet_pass,
  1232. Some(blockchain_config.endpoint),
  1233. &ex,
  1234. args.fun,
  1235. )
  1236. .await;
  1237. if let Err(e) = f64::from_str(&amount) {
  1238. eprintln!("Invalid amount: {e}");
  1239. exit(2);
  1240. }
  1241. let rcpt = match Address::from_str(&recipient) {
  1242. Ok(r) => r,
  1243. Err(e) => {
  1244. eprintln!("Invalid recipient: {e}");
  1245. exit(2);
  1246. }
  1247. };
  1248. if rcpt.network() != drk.network {
  1249. eprintln!("Recipient address prefix mismatch");
  1250. exit(2);
  1251. }
  1252. let token_id = match drk.get_token(token).await {
  1253. Ok(t) => t,
  1254. Err(e) => {
  1255. eprintln!("Invalid token alias: {e}");
  1256. exit(2);
  1257. }
  1258. };
  1259. let spend_hook = match spend_hook {
  1260. Some(s) => match FuncId::from_str(&s) {
  1261. Ok(s) => Some(s),
  1262. Err(e) => {
  1263. eprintln!("Invalid spend hook: {e}");
  1264. exit(2);
  1265. }
  1266. },
  1267. None => None,
  1268. };
  1269. let user_data = match user_data {
  1270. Some(u) => {
  1271. let bytes: [u8; 32] = match bs58::decode(&u).into_vec()?.try_into() {
  1272. Ok(b) => b,
  1273. Err(e) => {
  1274. eprintln!("Invalid user data: {e:?}");
  1275. exit(2);
  1276. }
  1277. };
  1278. match pallas::Base::from_repr(bytes).into() {
  1279. Some(v) => Some(v),
  1280. None => {
  1281. eprintln!("Invalid user data");
  1282. exit(2);
  1283. }
  1284. }
  1285. }
  1286. None => None,
  1287. };
  1288. let proposal = match drk
  1289. .dao_propose_transfer(
  1290. &name,
  1291. duration,
  1292. &amount,
  1293. token_id,
  1294. *rcpt.public_key(),
  1295. spend_hook,
  1296. user_data,
  1297. )
  1298. .await
  1299. {
  1300. Ok(p) => p,
  1301. Err(e) => {
  1302. eprintln!("Failed to create DAO transfer proposal: {e}");
  1303. exit(2);
  1304. }
  1305. };
  1306. println!("Generated proposal: {}", proposal.bulla());
  1307. drk.stop_rpc_client().await
  1308. }
  1309. DaoSubcmd::ProposeGeneric { name, duration, user_data } => {
  1310. let drk = new_wallet(
  1311. network,
  1312. blockchain_config.cache_path,
  1313. blockchain_config.wallet_path,
  1314. blockchain_config.wallet_pass,
  1315. Some(blockchain_config.endpoint),
  1316. &ex,
  1317. args.fun,
  1318. )
  1319. .await;
  1320. let user_data = match user_data {
  1321. Some(u) => {
  1322. let bytes: [u8; 32] = match bs58::decode(&u).into_vec()?.try_into() {
  1323. Ok(b) => b,
  1324. Err(e) => {
  1325. eprintln!("Invalid user data: {e:?}");
  1326. exit(2);
  1327. }
  1328. };
  1329. match pallas::Base::from_repr(bytes).into() {
  1330. Some(v) => Some(v),
  1331. None => {
  1332. eprintln!("Invalid user data");
  1333. exit(2);
  1334. }
  1335. }
  1336. }
  1337. None => None,
  1338. };
  1339. let proposal = match drk.dao_propose_generic(&name, duration, user_data).await {
  1340. Ok(p) => p,
  1341. Err(e) => {
  1342. eprintln!("Failed to create DAO generic proposal: {e}");
  1343. exit(2);
  1344. }
  1345. };
  1346. println!("Generated proposal: {}", proposal.bulla());
  1347. drk.stop_rpc_client().await
  1348. }
  1349. DaoSubcmd::Proposals { name } => {
  1350. let drk = new_wallet(
  1351. network,
  1352. blockchain_config.cache_path,
  1353. blockchain_config.wallet_path,
  1354. blockchain_config.wallet_pass,
  1355. None,
  1356. &ex,
  1357. args.fun,
  1358. )
  1359. .await;
  1360. let proposals = drk.get_dao_proposals(&name).await?;
  1361. for (i, proposal) in proposals.iter().enumerate() {
  1362. println!("{i}. {}", proposal.bulla());
  1363. }
  1364. Ok(())
  1365. }
  1366. DaoSubcmd::Proposal { bulla, export, mint_proposal } => {
  1367. let bulla = match DaoProposalBulla::from_str(&bulla) {
  1368. Ok(b) => b,
  1369. Err(e) => {
  1370. eprintln!("Invalid proposal bulla: {e}");
  1371. exit(2);
  1372. }
  1373. };
  1374. let drk = new_wallet(
  1375. network,
  1376. blockchain_config.cache_path,
  1377. blockchain_config.wallet_path,
  1378. blockchain_config.wallet_pass,
  1379. Some(blockchain_config.endpoint),
  1380. &ex,
  1381. args.fun,
  1382. )
  1383. .await;
  1384. let proposal = drk.get_dao_proposal_by_bulla(&bulla).await?;
  1385. if export {
  1386. // Retrieve the DAO
  1387. let dao = drk.get_dao_by_bulla(&proposal.proposal.dao_bulla).await?;
  1388. // Encypt the proposal
  1389. let enc_note = AeadEncryptedNote::encrypt(
  1390. &proposal,
  1391. &dao.params.dao.proposals_public_key,
  1392. &mut OsRng,
  1393. )
  1394. .unwrap();
  1395. // Export it to base64
  1396. println!("{}", base64::encode(&serialize_async(&enc_note).await));
  1397. return drk.stop_rpc_client().await
  1398. }
  1399. if mint_proposal {
  1400. // Identify proposal type by its auth calls
  1401. for call in &proposal.proposal.auth_calls {
  1402. // We only support transfer right now
  1403. if call.function_code == DaoFunction::AuthMoneyTransfer as u8 {
  1404. let tx = match drk.dao_transfer_proposal_tx(&proposal).await {
  1405. Ok(tx) => tx,
  1406. Err(e) => {
  1407. eprintln!("Failed to create DAO transfer proposal: {e}");
  1408. exit(2);
  1409. }
  1410. };
  1411. println!("{}", base64::encode(&serialize_async(&tx).await));
  1412. return drk.stop_rpc_client().await
  1413. }
  1414. }
  1415. // If proposal has no auth calls, we consider it a generic one
  1416. if proposal.proposal.auth_calls.is_empty() {
  1417. let tx = match drk.dao_generic_proposal_tx(&proposal).await {
  1418. Ok(tx) => tx,
  1419. Err(e) => {
  1420. eprintln!("Failed to create DAO generic proposal: {e}");
  1421. exit(2);
  1422. }
  1423. };
  1424. println!("{}", base64::encode(&serialize_async(&tx).await));
  1425. return drk.stop_rpc_client().await
  1426. }
  1427. eprintln!("Unsuported DAO proposal");
  1428. exit(2);
  1429. }
  1430. println!("{proposal}");
  1431. let mut contract_calls = "\nInvoked contracts:\n".to_string();
  1432. for call in proposal.proposal.auth_calls {
  1433. contract_calls.push_str(&format!(
  1434. "\tContract: {}\n\tFunction: {}\n\tData: ",
  1435. call.contract_id, call.function_code
  1436. ));
  1437. if call.auth_data.is_empty() {
  1438. contract_calls.push_str("-\n");
  1439. continue;
  1440. }
  1441. if call.function_code == DaoFunction::AuthMoneyTransfer as u8 {
  1442. // We know that the plaintext data live in the data plaintext vec
  1443. if proposal.data.is_none() {
  1444. contract_calls.push_str("-\n");
  1445. continue;
  1446. }
  1447. let coin: CoinAttributes =
  1448. deserialize_async(proposal.data.as_ref().unwrap()).await?;
  1449. let recipient: Address =
  1450. StandardAddress::from_public(drk.network, coin.public_key).into();
  1451. let spend_hook = if coin.spend_hook == FuncId::none() {
  1452. "-".to_string()
  1453. } else {
  1454. format!("{}", coin.spend_hook)
  1455. };
  1456. let user_data = if coin.user_data == pallas::Base::ZERO {
  1457. "-".to_string()
  1458. } else {
  1459. format!("{:?}", coin.user_data)
  1460. };
  1461. contract_calls.push_str(&format!("\n\t\t{}: {}\n\t\t{}: {} ({})\n\t\t{}: {}\n\t\t{}: {}\n\t\t{}: {}\n\t\t{}: {}\n\n",
  1462. "Recipient",
  1463. recipient,
  1464. "Amount",
  1465. coin.value,
  1466. encode_base10(coin.value, BALANCE_BASE10_DECIMALS),
  1467. "Token",
  1468. coin.token_id,
  1469. "Spend hook",
  1470. spend_hook,
  1471. "User data",
  1472. user_data,
  1473. "Blind",
  1474. coin.blind));
  1475. }
  1476. }
  1477. println!("{contract_calls}");
  1478. let votes = drk.get_dao_proposal_votes(&bulla).await?;
  1479. let mut total_yes_vote_value = 0;
  1480. let mut total_no_vote_value = 0;
  1481. let mut total_all_vote_value = 0;
  1482. let mut table = Table::new();
  1483. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  1484. table.set_titles(row!["Transaction", "Tokens", "Vote"]);
  1485. for vote in votes {
  1486. let vote_option = if vote.vote_option {
  1487. total_yes_vote_value += vote.all_vote_value;
  1488. "Yes"
  1489. } else {
  1490. total_no_vote_value += vote.all_vote_value;
  1491. "No"
  1492. };
  1493. total_all_vote_value += vote.all_vote_value;
  1494. table.add_row(row![
  1495. vote.tx_hash,
  1496. encode_base10(vote.all_vote_value, BALANCE_BASE10_DECIMALS),
  1497. vote_option
  1498. ]);
  1499. }
  1500. let outcome = if table.is_empty() {
  1501. println!("Votes: No votes found");
  1502. "Unknown"
  1503. } else {
  1504. println!("Votes:");
  1505. println!("{table}");
  1506. println!(
  1507. "Total tokens votes: {}",
  1508. encode_base10(total_all_vote_value, BALANCE_BASE10_DECIMALS)
  1509. );
  1510. let approval_ratio =
  1511. (total_yes_vote_value as f64 * 100.0) / total_all_vote_value as f64;
  1512. println!(
  1513. "Total tokens Yes votes: {} ({approval_ratio:.2}%)",
  1514. encode_base10(total_yes_vote_value, BALANCE_BASE10_DECIMALS)
  1515. );
  1516. println!(
  1517. "Total tokens No votes: {} ({:.2}%)",
  1518. encode_base10(total_no_vote_value, BALANCE_BASE10_DECIMALS),
  1519. (total_no_vote_value as f64 * 100.0) / total_all_vote_value as f64
  1520. );
  1521. let dao = drk.get_dao_by_bulla(&proposal.proposal.dao_bulla).await?;
  1522. if total_all_vote_value >= dao.params.dao.quorum &&
  1523. approval_ratio >=
  1524. (dao.params.dao.approval_ratio_quot /
  1525. dao.params.dao.approval_ratio_base)
  1526. as f64
  1527. {
  1528. "Approved"
  1529. } else {
  1530. "Rejected"
  1531. }
  1532. };
  1533. if let Some(exec_tx_hash) = proposal.exec_tx_hash {
  1534. println!("Proposal was executed on transaction: {exec_tx_hash}");
  1535. return drk.stop_rpc_client().await
  1536. }
  1537. // Retrieve next block height and current block time target,
  1538. // to compute their window.
  1539. let next_block_height = drk.get_next_block_height().await?;
  1540. let block_target = drk.get_block_target().await?;
  1541. let current_window = blockwindow(next_block_height, block_target);
  1542. let end_time = proposal.proposal.creation_blockwindow +
  1543. proposal.proposal.duration_blockwindows;
  1544. let (voting_status, proposal_status_message) = if current_window < end_time {
  1545. ("Ongoing", format!("Current proposal outcome: {outcome}"))
  1546. } else {
  1547. ("Concluded", format!("Proposal outcome: {outcome}"))
  1548. };
  1549. println!("Voting status: {voting_status}");
  1550. println!("{proposal_status_message}");
  1551. drk.stop_rpc_client().await
  1552. }
  1553. DaoSubcmd::ProposalImport => {
  1554. let mut buf = String::new();
  1555. stdin().read_to_string(&mut buf)?;
  1556. let Some(bytes) = base64::decode(buf.trim()) else {
  1557. eprintln!("Failed to decode encrypted proposal data");
  1558. exit(2);
  1559. };
  1560. let encrypted_proposal: AeadEncryptedNote = deserialize_async(&bytes).await?;
  1561. let drk = new_wallet(
  1562. network,
  1563. blockchain_config.cache_path,
  1564. blockchain_config.wallet_path,
  1565. blockchain_config.wallet_pass,
  1566. None,
  1567. &ex,
  1568. args.fun,
  1569. )
  1570. .await;
  1571. // Retrieve all DAOs to try to decrypt the proposal
  1572. let daos = drk.get_daos().await?;
  1573. for dao in &daos {
  1574. // Check if we have the proposals key
  1575. let Some(proposals_secret_key) = dao.params.proposals_secret_key else {
  1576. continue
  1577. };
  1578. // Try to decrypt the proposal
  1579. let Ok(proposal) =
  1580. encrypted_proposal.decrypt::<ProposalRecord>(&proposals_secret_key)
  1581. else {
  1582. continue
  1583. };
  1584. let proposal = match drk.get_dao_proposal_by_bulla(&proposal.bulla()).await {
  1585. Ok(p) => {
  1586. let mut our_proposal = p;
  1587. our_proposal.data = proposal.data;
  1588. our_proposal
  1589. }
  1590. Err(_) => proposal,
  1591. };
  1592. return drk.put_dao_proposal(&proposal).await
  1593. }
  1594. eprintln!("Couldn't decrypt the proposal with out DAO keys");
  1595. exit(2);
  1596. }
  1597. DaoSubcmd::Vote { bulla, vote, vote_weight } => {
  1598. let bulla = match DaoProposalBulla::from_str(&bulla) {
  1599. Ok(b) => b,
  1600. Err(e) => {
  1601. eprintln!("Invalid proposal bulla: {e}");
  1602. exit(2);
  1603. }
  1604. };
  1605. if vote > 1 {
  1606. eprintln!("Vote can be either 0 (NO) or 1 (YES)");
  1607. exit(2);
  1608. }
  1609. let vote = vote != 0;
  1610. let weight = match vote_weight {
  1611. Some(w) => {
  1612. if let Err(e) = f64::from_str(&w) {
  1613. eprintln!("Invalid vote weight: {e}");
  1614. exit(2);
  1615. }
  1616. Some(decode_base10(&w, BALANCE_BASE10_DECIMALS, true)?)
  1617. }
  1618. None => None,
  1619. };
  1620. let drk = new_wallet(
  1621. network,
  1622. blockchain_config.cache_path,
  1623. blockchain_config.wallet_path,
  1624. blockchain_config.wallet_pass,
  1625. Some(blockchain_config.endpoint),
  1626. &ex,
  1627. args.fun,
  1628. )
  1629. .await;
  1630. let tx = match drk.dao_vote(&bulla, vote, weight).await {
  1631. Ok(tx) => tx,
  1632. Err(e) => {
  1633. eprintln!("Failed to create DAO Vote transaction: {e}");
  1634. exit(2);
  1635. }
  1636. };
  1637. println!("{}", base64::encode(&serialize_async(&tx).await));
  1638. drk.stop_rpc_client().await
  1639. }
  1640. DaoSubcmd::Exec { bulla, early } => {
  1641. let bulla = match DaoProposalBulla::from_str(&bulla) {
  1642. Ok(b) => b,
  1643. Err(e) => {
  1644. eprintln!("Invalid proposal bulla: {e}");
  1645. exit(2);
  1646. }
  1647. };
  1648. let drk = new_wallet(
  1649. network,
  1650. blockchain_config.cache_path,
  1651. blockchain_config.wallet_path,
  1652. blockchain_config.wallet_pass,
  1653. Some(blockchain_config.endpoint),
  1654. &ex,
  1655. args.fun,
  1656. )
  1657. .await;
  1658. let proposal = drk.get_dao_proposal_by_bulla(&bulla).await?;
  1659. // Identify proposal type by its auth calls
  1660. for call in &proposal.proposal.auth_calls {
  1661. // We only support transfer right now
  1662. if call.function_code == DaoFunction::AuthMoneyTransfer as u8 {
  1663. let tx = match drk.dao_exec_transfer(&proposal, early).await {
  1664. Ok(tx) => tx,
  1665. Err(e) => {
  1666. eprintln!("Failed to execute DAO transfer proposal: {e}");
  1667. exit(2);
  1668. }
  1669. };
  1670. println!("{}", base64::encode(&serialize_async(&tx).await));
  1671. return drk.stop_rpc_client().await
  1672. }
  1673. }
  1674. // If proposal has no auth calls, we consider it a generic one
  1675. if proposal.proposal.auth_calls.is_empty() {
  1676. let tx = match drk.dao_exec_generic(&proposal, early).await {
  1677. Ok(tx) => tx,
  1678. Err(e) => {
  1679. eprintln!("Failed to execute DAO generic proposal: {e}");
  1680. exit(2);
  1681. }
  1682. };
  1683. println!("{}", base64::encode(&serialize_async(&tx).await));
  1684. return drk.stop_rpc_client().await
  1685. }
  1686. eprintln!("Unsuported DAO proposal");
  1687. exit(2);
  1688. }
  1689. DaoSubcmd::SpendHook => {
  1690. let spend_hook =
  1691. FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }
  1692. .to_func_id();
  1693. println!("{spend_hook}");
  1694. Ok(())
  1695. }
  1696. DaoSubcmd::MiningConfig { name } => {
  1697. let drk = new_wallet(
  1698. network,
  1699. blockchain_config.cache_path,
  1700. blockchain_config.wallet_path,
  1701. blockchain_config.wallet_pass,
  1702. None,
  1703. &ex,
  1704. args.fun,
  1705. )
  1706. .await;
  1707. let mut output = vec![];
  1708. if let Err(e) = drk.dao_mining_config(&name, &mut output).await {
  1709. print_output(&output);
  1710. eprintln!("Failed to generate DAO mining configuration: {e}");
  1711. exit(2);
  1712. }
  1713. print_output(&output);
  1714. Ok(())
  1715. }
  1716. },
  1717. Subcmd::AttachFee => {
  1718. let mut tx = parse_tx_from_stdin().await?;
  1719. let drk = new_wallet(
  1720. network,
  1721. blockchain_config.cache_path,
  1722. blockchain_config.wallet_path,
  1723. blockchain_config.wallet_pass,
  1724. Some(blockchain_config.endpoint),
  1725. &ex,
  1726. args.fun,
  1727. )
  1728. .await;
  1729. if let Err(e) = drk.attach_fee(&mut tx).await {
  1730. eprintln!("Failed to attach the fee call to the transaction: {e}");
  1731. exit(2);
  1732. };
  1733. println!("{}", base64::encode(&serialize_async(&tx).await));
  1734. drk.stop_rpc_client().await
  1735. }
  1736. Subcmd::Inspect => {
  1737. let tx = parse_tx_from_stdin().await?;
  1738. println!("{tx:#?}");
  1739. Ok(())
  1740. }
  1741. Subcmd::Broadcast => {
  1742. let tx = parse_tx_from_stdin().await?;
  1743. let drk = new_wallet(
  1744. network,
  1745. blockchain_config.cache_path,
  1746. blockchain_config.wallet_path,
  1747. blockchain_config.wallet_pass,
  1748. Some(blockchain_config.endpoint),
  1749. &ex,
  1750. args.fun,
  1751. )
  1752. .await;
  1753. if let Err(e) = drk.simulate_tx(&tx).await {
  1754. eprintln!("Failed to simulate tx: {e}");
  1755. exit(2);
  1756. };
  1757. let mut output = vec![];
  1758. if let Err(e) = drk.mark_tx_spend(&tx, &mut output).await {
  1759. print_output(&output);
  1760. eprintln!("Failed to mark transaction coins as spent: {e}");
  1761. exit(2);
  1762. };
  1763. let txid = match drk.broadcast_tx(&tx, &mut output).await {
  1764. Ok(t) => t,
  1765. Err(e) => {
  1766. print_output(&output);
  1767. eprintln!("Failed to broadcast transaction: {e}");
  1768. exit(2);
  1769. }
  1770. };
  1771. print_output(&output);
  1772. println!("Transaction ID: {txid}");
  1773. drk.stop_rpc_client().await
  1774. }
  1775. Subcmd::Scan { reset } => {
  1776. let drk = new_wallet(
  1777. network,
  1778. blockchain_config.cache_path,
  1779. blockchain_config.wallet_path,
  1780. blockchain_config.wallet_pass,
  1781. Some(blockchain_config.endpoint),
  1782. &ex,
  1783. args.fun,
  1784. )
  1785. .await;
  1786. if let Some(height) = reset {
  1787. let mut buf = vec![];
  1788. if let Err(e) = drk.reset_to_height(height, &mut buf).await {
  1789. print_output(&buf);
  1790. eprintln!("Failed during wallet reset: {e}");
  1791. exit(2);
  1792. }
  1793. print_output(&buf);
  1794. }
  1795. if let Err(e) = drk.scan_blocks(&mut vec![], None, &true).await {
  1796. eprintln!("Failed during scanning: {e}");
  1797. exit(2);
  1798. }
  1799. println!("Finished scanning blockchain");
  1800. drk.stop_rpc_client().await
  1801. }
  1802. Subcmd::Explorer { command } => match command {
  1803. ExplorerSubcmd::FetchTx { tx_hash, encode } => {
  1804. let tx_hash = TransactionHash(*blake3::Hash::from_hex(&tx_hash)?.as_bytes());
  1805. let drk = new_wallet(
  1806. network,
  1807. blockchain_config.cache_path,
  1808. blockchain_config.wallet_path,
  1809. blockchain_config.wallet_pass,
  1810. Some(blockchain_config.endpoint),
  1811. &ex,
  1812. args.fun,
  1813. )
  1814. .await;
  1815. let tx = match drk.get_tx(&tx_hash).await {
  1816. Ok(tx) => tx,
  1817. Err(e) => {
  1818. eprintln!("Failed to fetch transaction: {e}");
  1819. exit(2);
  1820. }
  1821. };
  1822. let Some(tx) = tx else {
  1823. println!("Transaction was not found");
  1824. exit(1);
  1825. };
  1826. // Make sure the tx is correct
  1827. assert_eq!(tx.hash(), tx_hash);
  1828. if encode {
  1829. println!("{}", base64::encode(&serialize_async(&tx).await));
  1830. exit(1)
  1831. }
  1832. println!("Transaction ID: {tx_hash}");
  1833. println!("{tx:?}");
  1834. drk.stop_rpc_client().await
  1835. }
  1836. ExplorerSubcmd::SimulateTx => {
  1837. let tx = parse_tx_from_stdin().await?;
  1838. let drk = new_wallet(
  1839. network,
  1840. blockchain_config.cache_path,
  1841. blockchain_config.wallet_path,
  1842. blockchain_config.wallet_pass,
  1843. Some(blockchain_config.endpoint),
  1844. &ex,
  1845. args.fun,
  1846. )
  1847. .await;
  1848. let is_valid = match drk.simulate_tx(&tx).await {
  1849. Ok(b) => b,
  1850. Err(e) => {
  1851. eprintln!("Failed to simulate tx: {e}");
  1852. exit(2);
  1853. }
  1854. };
  1855. println!("Transaction ID: {}", tx.hash());
  1856. println!("State: {}", if is_valid { "valid" } else { "invalid" });
  1857. drk.stop_rpc_client().await
  1858. }
  1859. ExplorerSubcmd::TxsHistory { tx_hash, encode } => {
  1860. let drk = new_wallet(
  1861. network,
  1862. blockchain_config.cache_path,
  1863. blockchain_config.wallet_path,
  1864. blockchain_config.wallet_pass,
  1865. None,
  1866. &ex,
  1867. args.fun,
  1868. )
  1869. .await;
  1870. if let Some(c) = tx_hash {
  1871. let (tx_hash, status, block_height, tx) = drk.get_tx_history_record(&c).await?;
  1872. if encode {
  1873. println!("{}", base64::encode(&serialize_async(&tx).await));
  1874. exit(1)
  1875. }
  1876. println!("Transaction ID: {tx_hash}");
  1877. println!("Status: {status}");
  1878. match block_height {
  1879. Some(block_height) => println!("Block height: {block_height}"),
  1880. None => println!("Block height: -"),
  1881. }
  1882. println!("{tx:?}");
  1883. return Ok(())
  1884. }
  1885. let map = match drk.get_txs_history() {
  1886. Ok(m) => m,
  1887. Err(e) => {
  1888. eprintln!("Failed to retrieve transactions history records: {e}");
  1889. exit(2);
  1890. }
  1891. };
  1892. // Create a prettytable with the new data:
  1893. let mut table = Table::new();
  1894. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  1895. table.set_titles(row!["Transaction Hash", "Status", "Block Height"]);
  1896. for (txs_hash, status, block_height) in map.iter() {
  1897. let block_height = match block_height {
  1898. Some(block_height) => block_height.to_string(),
  1899. None => String::from("-"),
  1900. };
  1901. table.add_row(row![txs_hash, status, block_height]);
  1902. }
  1903. if table.is_empty() {
  1904. println!("No transactions found");
  1905. } else {
  1906. println!("{table}");
  1907. }
  1908. Ok(())
  1909. }
  1910. ExplorerSubcmd::ClearReverted => {
  1911. let drk = new_wallet(
  1912. network,
  1913. blockchain_config.cache_path,
  1914. blockchain_config.wallet_path,
  1915. blockchain_config.wallet_pass,
  1916. None,
  1917. &ex,
  1918. args.fun,
  1919. )
  1920. .await;
  1921. let mut output = vec![];
  1922. if let Err(e) = drk.remove_reverted_txs(&mut output) {
  1923. print_output(&output);
  1924. eprintln!("Failed to remove reverted transactions: {e}");
  1925. exit(2);
  1926. };
  1927. print_output(&output);
  1928. Ok(())
  1929. }
  1930. ExplorerSubcmd::ScannedBlocks { height } => {
  1931. let drk = new_wallet(
  1932. network,
  1933. blockchain_config.cache_path,
  1934. blockchain_config.wallet_path,
  1935. blockchain_config.wallet_pass,
  1936. None,
  1937. &ex,
  1938. args.fun,
  1939. )
  1940. .await;
  1941. if let Some(height) = height {
  1942. let (hash, signing_key) = match drk.get_scanned_block(&height) {
  1943. Ok(p) => p,
  1944. Err(e) => {
  1945. eprintln!("Failed to retrieve scanned block record: {e}");
  1946. exit(2);
  1947. }
  1948. };
  1949. println!("Height: {height}");
  1950. println!("Hash: {hash}");
  1951. println!("Signing key: {signing_key}");
  1952. return Ok(())
  1953. }
  1954. let map = match drk.get_scanned_block_records() {
  1955. Ok(m) => m,
  1956. Err(e) => {
  1957. eprintln!("Failed to retrieve scanned blocks records: {e}");
  1958. exit(2);
  1959. }
  1960. };
  1961. let table = prettytable_scanned_blocks(&map);
  1962. if table.is_empty() {
  1963. println!("No scanned blocks records found");
  1964. } else {
  1965. println!("{table}");
  1966. }
  1967. Ok(())
  1968. }
  1969. ExplorerSubcmd::MiningConfig => {
  1970. let (config, recipient, spend_hook, user_data) =
  1971. parse_mining_config_from_stdin().await?;
  1972. let mut output = vec![];
  1973. display_mining_config(&config, &recipient, &spend_hook, &user_data, &mut output);
  1974. print_output(&output);
  1975. Ok(())
  1976. }
  1977. },
  1978. Subcmd::Alias { command } => match command {
  1979. AliasSubcmd::Add { alias, token } => {
  1980. if alias.chars().count() > 5 {
  1981. eprintln!("Error: Alias exceeds 5 characters");
  1982. exit(2);
  1983. }
  1984. let token_id = match TokenId::from_str(token.as_str()) {
  1985. Ok(t) => t,
  1986. Err(e) => {
  1987. eprintln!("Invalid Token ID: {e}");
  1988. exit(2);
  1989. }
  1990. };
  1991. let drk = new_wallet(
  1992. network,
  1993. blockchain_config.cache_path,
  1994. blockchain_config.wallet_path,
  1995. blockchain_config.wallet_pass,
  1996. None,
  1997. &ex,
  1998. args.fun,
  1999. )
  2000. .await;
  2001. let mut output = vec![];
  2002. if let Err(e) = drk.add_alias(alias, token_id, &mut output).await {
  2003. print_output(&output);
  2004. eprintln!("Failed to add alias: {e}");
  2005. exit(2);
  2006. }
  2007. print_output(&output);
  2008. Ok(())
  2009. }
  2010. AliasSubcmd::Show { alias, token } => {
  2011. let token_id = match token {
  2012. Some(t) => match TokenId::from_str(t.as_str()) {
  2013. Ok(t) => Some(t),
  2014. Err(e) => {
  2015. eprintln!("Invalid Token ID: {e}");
  2016. exit(2);
  2017. }
  2018. },
  2019. None => None,
  2020. };
  2021. let drk = new_wallet(
  2022. network,
  2023. blockchain_config.cache_path,
  2024. blockchain_config.wallet_path,
  2025. blockchain_config.wallet_pass,
  2026. None,
  2027. &ex,
  2028. args.fun,
  2029. )
  2030. .await;
  2031. let map = drk.get_aliases(alias, token_id).await?;
  2032. let table = prettytable_aliases(&map);
  2033. if table.is_empty() {
  2034. println!("No aliases found");
  2035. } else {
  2036. println!("{table}");
  2037. }
  2038. Ok(())
  2039. }
  2040. AliasSubcmd::Remove { alias } => {
  2041. let drk = new_wallet(
  2042. network,
  2043. blockchain_config.cache_path,
  2044. blockchain_config.wallet_path,
  2045. blockchain_config.wallet_pass,
  2046. None,
  2047. &ex,
  2048. args.fun,
  2049. )
  2050. .await;
  2051. let mut output = vec![];
  2052. if let Err(e) = drk.remove_alias(alias, &mut output).await {
  2053. print_output(&output);
  2054. eprintln!("Failed to remove alias: {e}");
  2055. exit(2);
  2056. }
  2057. print_output(&output);
  2058. Ok(())
  2059. }
  2060. },
  2061. Subcmd::Token { command } => match command {
  2062. TokenSubcmd::Import { secret_key, token_blind } => {
  2063. let mint_authority = match SecretKey::from_str(&secret_key) {
  2064. Ok(ma) => ma,
  2065. Err(e) => {
  2066. eprintln!("Invalid mint authority: {e}");
  2067. exit(2);
  2068. }
  2069. };
  2070. let token_blind = match BaseBlind::from_str(&token_blind) {
  2071. Ok(tb) => tb,
  2072. Err(e) => {
  2073. eprintln!("Invalid token blind: {e}");
  2074. exit(2);
  2075. }
  2076. };
  2077. let drk = new_wallet(
  2078. network,
  2079. blockchain_config.cache_path,
  2080. blockchain_config.wallet_path,
  2081. blockchain_config.wallet_pass,
  2082. None,
  2083. &ex,
  2084. args.fun,
  2085. )
  2086. .await;
  2087. let token_id = drk.import_mint_authority(mint_authority, token_blind).await?;
  2088. println!("Successfully imported mint authority for token ID: {token_id}");
  2089. Ok(())
  2090. }
  2091. TokenSubcmd::GenerateMint => {
  2092. let drk = new_wallet(
  2093. network,
  2094. blockchain_config.cache_path,
  2095. blockchain_config.wallet_path,
  2096. blockchain_config.wallet_pass,
  2097. None,
  2098. &ex,
  2099. args.fun,
  2100. )
  2101. .await;
  2102. let mint_authority = SecretKey::random(&mut OsRng);
  2103. let token_blind = BaseBlind::random(&mut OsRng);
  2104. let token_id = drk.import_mint_authority(mint_authority, token_blind).await?;
  2105. println!("Successfully imported mint authority for token ID: {token_id}");
  2106. Ok(())
  2107. }
  2108. TokenSubcmd::List => {
  2109. let drk = new_wallet(
  2110. network,
  2111. blockchain_config.cache_path,
  2112. blockchain_config.wallet_path,
  2113. blockchain_config.wallet_pass,
  2114. None,
  2115. &ex,
  2116. args.fun,
  2117. )
  2118. .await;
  2119. let tokens = drk.get_mint_authorities().await?;
  2120. let aliases_map = match drk.get_aliases_mapped_by_token().await {
  2121. Ok(map) => map,
  2122. Err(e) => {
  2123. eprintln!("Failed to fetch wallet aliases: {e}");
  2124. exit(2);
  2125. }
  2126. };
  2127. let table = prettytable_tokenlist(&tokens, &aliases_map);
  2128. if table.is_empty() {
  2129. println!("No tokens found");
  2130. } else {
  2131. println!("{table}");
  2132. }
  2133. Ok(())
  2134. }
  2135. TokenSubcmd::Mint { token, amount, recipient, spend_hook, user_data } => {
  2136. let drk = new_wallet(
  2137. network,
  2138. blockchain_config.cache_path,
  2139. blockchain_config.wallet_path,
  2140. blockchain_config.wallet_pass,
  2141. Some(blockchain_config.endpoint),
  2142. &ex,
  2143. args.fun,
  2144. )
  2145. .await;
  2146. if let Err(e) = f64::from_str(&amount) {
  2147. eprintln!("Invalid amount: {e}");
  2148. exit(2);
  2149. }
  2150. let rcpt = match Address::from_str(&recipient) {
  2151. Ok(r) => r,
  2152. Err(e) => {
  2153. eprintln!("Invalid recipient: {e}");
  2154. exit(2);
  2155. }
  2156. };
  2157. if rcpt.network() != drk.network {
  2158. eprintln!("Recipient address prefix mismatch");
  2159. exit(2);
  2160. }
  2161. let token_id = match drk.get_token(token).await {
  2162. Ok(t) => t,
  2163. Err(e) => {
  2164. eprintln!("Invalid Token ID: {e}");
  2165. exit(2);
  2166. }
  2167. };
  2168. let spend_hook = match spend_hook {
  2169. Some(s) => match FuncId::from_str(&s) {
  2170. Ok(s) => Some(s),
  2171. Err(e) => {
  2172. eprintln!("Invalid spend hook: {e}");
  2173. exit(2);
  2174. }
  2175. },
  2176. None => None,
  2177. };
  2178. let user_data = match user_data {
  2179. Some(u) => {
  2180. let bytes: [u8; 32] = match bs58::decode(&u).into_vec()?.try_into() {
  2181. Ok(b) => b,
  2182. Err(e) => {
  2183. eprintln!("Invalid user data: {e:?}");
  2184. exit(2);
  2185. }
  2186. };
  2187. match pallas::Base::from_repr(bytes).into() {
  2188. Some(v) => Some(v),
  2189. None => {
  2190. eprintln!("Invalid user data");
  2191. exit(2);
  2192. }
  2193. }
  2194. }
  2195. None => None,
  2196. };
  2197. let tx = match drk
  2198. .mint_token(&amount, *rcpt.public_key(), token_id, spend_hook, user_data)
  2199. .await
  2200. {
  2201. Ok(tx) => tx,
  2202. Err(e) => {
  2203. eprintln!("Failed to create token mint transaction: {e}");
  2204. exit(2);
  2205. }
  2206. };
  2207. println!("{}", base64::encode(&serialize_async(&tx).await));
  2208. drk.stop_rpc_client().await
  2209. }
  2210. TokenSubcmd::Freeze { token } => {
  2211. let drk = new_wallet(
  2212. network,
  2213. blockchain_config.cache_path,
  2214. blockchain_config.wallet_path,
  2215. blockchain_config.wallet_pass,
  2216. Some(blockchain_config.endpoint),
  2217. &ex,
  2218. args.fun,
  2219. )
  2220. .await;
  2221. let token_id = match drk.get_token(token).await {
  2222. Ok(t) => t,
  2223. Err(e) => {
  2224. eprintln!("Invalid Token ID: {e}");
  2225. exit(2);
  2226. }
  2227. };
  2228. let tx = match drk.freeze_token(token_id).await {
  2229. Ok(tx) => tx,
  2230. Err(e) => {
  2231. eprintln!("Failed to create token freeze transaction: {e}");
  2232. exit(2);
  2233. }
  2234. };
  2235. println!("{}", base64::encode(&serialize_async(&tx).await));
  2236. drk.stop_rpc_client().await
  2237. }
  2238. },
  2239. Subcmd::Contract { command } => match command {
  2240. ContractSubcmd::GenerateDeploy => {
  2241. let drk = new_wallet(
  2242. network,
  2243. blockchain_config.cache_path,
  2244. blockchain_config.wallet_path,
  2245. blockchain_config.wallet_pass,
  2246. None,
  2247. &ex,
  2248. args.fun,
  2249. )
  2250. .await;
  2251. let mut output = vec![];
  2252. if let Err(e) = drk.deploy_auth_keygen(&mut output).await {
  2253. print_output(&output);
  2254. eprintln!("Error creating deploy auth keypair: {e}");
  2255. exit(2);
  2256. }
  2257. print_output(&output);
  2258. Ok(())
  2259. }
  2260. ContractSubcmd::List { contract_id } => {
  2261. let drk = new_wallet(
  2262. network,
  2263. blockchain_config.cache_path,
  2264. blockchain_config.wallet_path,
  2265. blockchain_config.wallet_pass,
  2266. None,
  2267. &ex,
  2268. args.fun,
  2269. )
  2270. .await;
  2271. if let Some(contract_id) = contract_id {
  2272. let contract_id = match ContractId::from_str(&contract_id) {
  2273. Ok(d) => d,
  2274. Err(e) => {
  2275. eprintln!("Invalid contract id: {e}");
  2276. exit(2);
  2277. }
  2278. };
  2279. let history = drk.get_deploy_auth_history(&contract_id).await?;
  2280. let table = prettytable_contract_history(&history);
  2281. if table.is_empty() {
  2282. println!("No history records found");
  2283. } else {
  2284. println!("{table}");
  2285. }
  2286. return Ok(())
  2287. }
  2288. let auths = drk.list_deploy_auth().await?;
  2289. let table = prettytable_contract_auth(&auths);
  2290. if table.is_empty() {
  2291. println!("No deploy authorities found");
  2292. } else {
  2293. println!("{table}");
  2294. }
  2295. Ok(())
  2296. }
  2297. ContractSubcmd::ExportData { tx_hash } => {
  2298. let drk = new_wallet(
  2299. network,
  2300. blockchain_config.cache_path,
  2301. blockchain_config.wallet_path,
  2302. blockchain_config.wallet_pass,
  2303. None,
  2304. &ex,
  2305. args.fun,
  2306. )
  2307. .await;
  2308. let pair = drk.get_deploy_history_record_data(&tx_hash).await?;
  2309. println!("{}", base64::encode(&serialize_async(&pair).await));
  2310. Ok(())
  2311. }
  2312. ContractSubcmd::Deploy { deploy_auth, wasm_path, deploy_ix } => {
  2313. // Parse the deployment authority contract id
  2314. let deploy_auth = match ContractId::from_str(&deploy_auth) {
  2315. Ok(d) => d,
  2316. Err(e) => {
  2317. eprintln!("Invalid deploy authority: {e}");
  2318. exit(2);
  2319. }
  2320. };
  2321. // Read the wasm bincode and deploy instruction
  2322. let wasm_bin = smol::fs::read(expand_path(&wasm_path)?).await?;
  2323. let deploy_ix = match deploy_ix {
  2324. Some(p) => smol::fs::read(expand_path(&p)?).await?,
  2325. None => vec![],
  2326. };
  2327. let drk = new_wallet(
  2328. network,
  2329. blockchain_config.cache_path,
  2330. blockchain_config.wallet_path,
  2331. blockchain_config.wallet_pass,
  2332. Some(blockchain_config.endpoint),
  2333. &ex,
  2334. args.fun,
  2335. )
  2336. .await;
  2337. let tx = match drk.deploy_contract(&deploy_auth, wasm_bin, deploy_ix).await {
  2338. Ok(tx) => tx,
  2339. Err(e) => {
  2340. eprintln!("Error creating contract deployment tx: {e}");
  2341. exit(2);
  2342. }
  2343. };
  2344. println!("{}", base64::encode(&serialize_async(&tx).await));
  2345. drk.stop_rpc_client().await
  2346. }
  2347. ContractSubcmd::Lock { deploy_auth } => {
  2348. // Parse the deployment authority contract id
  2349. let deploy_auth = match ContractId::from_str(&deploy_auth) {
  2350. Ok(d) => d,
  2351. Err(e) => {
  2352. eprintln!("Invalid deploy authority: {e}");
  2353. exit(2);
  2354. }
  2355. };
  2356. let drk = new_wallet(
  2357. network,
  2358. blockchain_config.cache_path,
  2359. blockchain_config.wallet_path,
  2360. blockchain_config.wallet_pass,
  2361. Some(blockchain_config.endpoint),
  2362. &ex,
  2363. args.fun,
  2364. )
  2365. .await;
  2366. let tx = match drk.lock_contract(&deploy_auth).await {
  2367. Ok(tx) => tx,
  2368. Err(e) => {
  2369. eprintln!("Error creating contract lock tx: {e}");
  2370. exit(2);
  2371. }
  2372. };
  2373. println!("{}", base64::encode(&serialize_async(&tx).await));
  2374. drk.stop_rpc_client().await
  2375. }
  2376. },
  2377. }
  2378. }