main.rs 93 KB

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