main.rs 95 KB

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