main.rs 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875
  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. println!("{tx:#?}");
  1829. Ok(())
  1830. }
  1831. Subcmd::Broadcast => {
  1832. let tx = parse_tx_from_stdin().await?;
  1833. let drk = new_wallet(
  1834. network,
  1835. blockchain_config.cache_path,
  1836. blockchain_config.wallet_path,
  1837. blockchain_config.wallet_pass,
  1838. Some(blockchain_config.endpoint),
  1839. &ex,
  1840. args.fun,
  1841. )
  1842. .await;
  1843. if let Err(e) = drk.simulate_tx(&tx).await {
  1844. eprintln!("Failed to simulate tx: {e}");
  1845. exit(2);
  1846. };
  1847. let mut output = vec![];
  1848. if let Err(e) = drk.mark_tx_spend(&tx, &mut output).await {
  1849. print_output(&output);
  1850. eprintln!("Failed to mark transaction coins as spent: {e}");
  1851. exit(2);
  1852. };
  1853. let txid = match drk.broadcast_tx(&tx, &mut output).await {
  1854. Ok(t) => t,
  1855. Err(e) => {
  1856. print_output(&output);
  1857. eprintln!("Failed to broadcast transaction: {e}");
  1858. exit(2);
  1859. }
  1860. };
  1861. print_output(&output);
  1862. println!("Transaction ID: {txid}");
  1863. drk.stop_rpc_client().await
  1864. }
  1865. Subcmd::Scan { reset } => {
  1866. let drk = new_wallet(
  1867. network,
  1868. blockchain_config.cache_path,
  1869. blockchain_config.wallet_path,
  1870. blockchain_config.wallet_pass,
  1871. Some(blockchain_config.endpoint),
  1872. &ex,
  1873. args.fun,
  1874. )
  1875. .await;
  1876. if let Some(height) = reset {
  1877. let mut buf = vec![];
  1878. if let Err(e) = drk.reset_to_height(height, &mut buf).await {
  1879. print_output(&buf);
  1880. eprintln!("Failed during wallet reset: {e}");
  1881. exit(2);
  1882. }
  1883. print_output(&buf);
  1884. }
  1885. if let Err(e) = drk.scan_blocks(&mut vec![], None, &true).await {
  1886. eprintln!("Failed during scanning: {e}");
  1887. exit(2);
  1888. }
  1889. println!("Finished scanning blockchain");
  1890. drk.stop_rpc_client().await
  1891. }
  1892. Subcmd::Explorer { command } => match command {
  1893. ExplorerSubcmd::FetchTx { tx_hash, encode } => {
  1894. let tx_hash = TransactionHash(*blake3::Hash::from_hex(&tx_hash)?.as_bytes());
  1895. let drk = new_wallet(
  1896. network,
  1897. blockchain_config.cache_path,
  1898. blockchain_config.wallet_path,
  1899. blockchain_config.wallet_pass,
  1900. Some(blockchain_config.endpoint),
  1901. &ex,
  1902. args.fun,
  1903. )
  1904. .await;
  1905. let tx = match drk.get_tx(&tx_hash).await {
  1906. Ok(tx) => tx,
  1907. Err(e) => {
  1908. eprintln!("Failed to fetch transaction: {e}");
  1909. exit(2);
  1910. }
  1911. };
  1912. let Some(tx) = tx else {
  1913. println!("Transaction was not found");
  1914. exit(1);
  1915. };
  1916. // Make sure the tx is correct
  1917. assert_eq!(tx.hash(), tx_hash);
  1918. if encode {
  1919. println!("{}", base64::encode(&serialize_async(&tx).await));
  1920. exit(1)
  1921. }
  1922. println!("Transaction ID: {tx_hash}");
  1923. println!("{tx:?}");
  1924. drk.stop_rpc_client().await
  1925. }
  1926. ExplorerSubcmd::SimulateTx => {
  1927. let tx = parse_tx_from_stdin().await?;
  1928. let drk = new_wallet(
  1929. network,
  1930. blockchain_config.cache_path,
  1931. blockchain_config.wallet_path,
  1932. blockchain_config.wallet_pass,
  1933. Some(blockchain_config.endpoint),
  1934. &ex,
  1935. args.fun,
  1936. )
  1937. .await;
  1938. let is_valid = match drk.simulate_tx(&tx).await {
  1939. Ok(b) => b,
  1940. Err(e) => {
  1941. eprintln!("Failed to simulate tx: {e}");
  1942. exit(2);
  1943. }
  1944. };
  1945. println!("Transaction ID: {}", tx.hash());
  1946. println!("State: {}", if is_valid { "valid" } else { "invalid" });
  1947. drk.stop_rpc_client().await
  1948. }
  1949. ExplorerSubcmd::TxsHistory { tx_hash, encode } => {
  1950. let drk = new_wallet(
  1951. network,
  1952. blockchain_config.cache_path,
  1953. blockchain_config.wallet_path,
  1954. blockchain_config.wallet_pass,
  1955. None,
  1956. &ex,
  1957. args.fun,
  1958. )
  1959. .await;
  1960. if let Some(c) = tx_hash {
  1961. let (tx_hash, status, block_height, tx) = drk.get_tx_history_record(&c).await?;
  1962. if encode {
  1963. println!("{}", base64::encode(&serialize_async(&tx).await));
  1964. exit(1)
  1965. }
  1966. println!("Transaction ID: {tx_hash}");
  1967. println!("Status: {status}");
  1968. match block_height {
  1969. Some(block_height) => println!("Block height: {block_height}"),
  1970. None => println!("Block height: -"),
  1971. }
  1972. println!("{tx:?}");
  1973. return Ok(())
  1974. }
  1975. let map = match drk.get_txs_history() {
  1976. Ok(m) => m,
  1977. Err(e) => {
  1978. eprintln!("Failed to retrieve transactions history records: {e}");
  1979. exit(2);
  1980. }
  1981. };
  1982. // Create a prettytable with the new data:
  1983. let mut table = Table::new();
  1984. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  1985. table.set_titles(row!["Transaction Hash", "Status", "Block Height"]);
  1986. for (txs_hash, status, block_height) in map.iter() {
  1987. let block_height = match block_height {
  1988. Some(block_height) => block_height.to_string(),
  1989. None => String::from("-"),
  1990. };
  1991. table.add_row(row![txs_hash, status, block_height]);
  1992. }
  1993. if table.is_empty() {
  1994. println!("No transactions found");
  1995. } else {
  1996. println!("{table}");
  1997. }
  1998. Ok(())
  1999. }
  2000. ExplorerSubcmd::ClearReverted => {
  2001. let drk = new_wallet(
  2002. network,
  2003. blockchain_config.cache_path,
  2004. blockchain_config.wallet_path,
  2005. blockchain_config.wallet_pass,
  2006. None,
  2007. &ex,
  2008. args.fun,
  2009. )
  2010. .await;
  2011. let mut output = vec![];
  2012. if let Err(e) = drk.remove_reverted_txs(&mut output) {
  2013. print_output(&output);
  2014. eprintln!("Failed to remove reverted transactions: {e}");
  2015. exit(2);
  2016. };
  2017. print_output(&output);
  2018. Ok(())
  2019. }
  2020. ExplorerSubcmd::ScannedBlocks { height } => {
  2021. let drk = new_wallet(
  2022. network,
  2023. blockchain_config.cache_path,
  2024. blockchain_config.wallet_path,
  2025. blockchain_config.wallet_pass,
  2026. None,
  2027. &ex,
  2028. args.fun,
  2029. )
  2030. .await;
  2031. if let Some(height) = height {
  2032. let (hash, signing_key) = match drk.get_scanned_block(&height) {
  2033. Ok(p) => p,
  2034. Err(e) => {
  2035. eprintln!("Failed to retrieve scanned block record: {e}");
  2036. exit(2);
  2037. }
  2038. };
  2039. println!("Height: {height}");
  2040. println!("Hash: {hash}");
  2041. println!("Signing key: {signing_key}");
  2042. return Ok(())
  2043. }
  2044. let map = match drk.get_scanned_block_records() {
  2045. Ok(m) => m,
  2046. Err(e) => {
  2047. eprintln!("Failed to retrieve scanned blocks records: {e}");
  2048. exit(2);
  2049. }
  2050. };
  2051. let table = prettytable_scanned_blocks(&map);
  2052. if table.is_empty() {
  2053. println!("No scanned blocks records found");
  2054. } else {
  2055. println!("{table}");
  2056. }
  2057. Ok(())
  2058. }
  2059. ExplorerSubcmd::MiningConfig => {
  2060. let (config, recipient, spend_hook, user_data) =
  2061. parse_mining_config_from_stdin().await?;
  2062. let mut output = vec![];
  2063. display_mining_config(&config, &recipient, &spend_hook, &user_data, &mut output);
  2064. print_output(&output);
  2065. Ok(())
  2066. }
  2067. },
  2068. Subcmd::Alias { command } => match command {
  2069. AliasSubcmd::Add { alias, token } => {
  2070. if alias.chars().count() > 5 {
  2071. eprintln!("Error: Alias exceeds 5 characters");
  2072. exit(2);
  2073. }
  2074. let token_id = match TokenId::from_str(token.as_str()) {
  2075. Ok(t) => t,
  2076. Err(e) => {
  2077. eprintln!("Invalid Token ID: {e}");
  2078. exit(2);
  2079. }
  2080. };
  2081. let drk = new_wallet(
  2082. network,
  2083. blockchain_config.cache_path,
  2084. blockchain_config.wallet_path,
  2085. blockchain_config.wallet_pass,
  2086. None,
  2087. &ex,
  2088. args.fun,
  2089. )
  2090. .await;
  2091. let mut output = vec![];
  2092. if let Err(e) = drk.add_alias(alias, token_id, &mut output).await {
  2093. print_output(&output);
  2094. eprintln!("Failed to add alias: {e}");
  2095. exit(2);
  2096. }
  2097. print_output(&output);
  2098. Ok(())
  2099. }
  2100. AliasSubcmd::Show { alias, token } => {
  2101. let token_id = match token {
  2102. Some(t) => match TokenId::from_str(t.as_str()) {
  2103. Ok(t) => Some(t),
  2104. Err(e) => {
  2105. eprintln!("Invalid Token ID: {e}");
  2106. exit(2);
  2107. }
  2108. },
  2109. None => None,
  2110. };
  2111. let drk = new_wallet(
  2112. network,
  2113. blockchain_config.cache_path,
  2114. blockchain_config.wallet_path,
  2115. blockchain_config.wallet_pass,
  2116. None,
  2117. &ex,
  2118. args.fun,
  2119. )
  2120. .await;
  2121. let map = drk.get_aliases(alias, token_id).await?;
  2122. let table = prettytable_aliases(&map);
  2123. if table.is_empty() {
  2124. println!("No aliases found");
  2125. } else {
  2126. println!("{table}");
  2127. }
  2128. Ok(())
  2129. }
  2130. AliasSubcmd::Remove { alias } => {
  2131. let drk = new_wallet(
  2132. network,
  2133. blockchain_config.cache_path,
  2134. blockchain_config.wallet_path,
  2135. blockchain_config.wallet_pass,
  2136. None,
  2137. &ex,
  2138. args.fun,
  2139. )
  2140. .await;
  2141. let mut output = vec![];
  2142. if let Err(e) = drk.remove_alias(alias, &mut output).await {
  2143. print_output(&output);
  2144. eprintln!("Failed to remove alias: {e}");
  2145. exit(2);
  2146. }
  2147. print_output(&output);
  2148. Ok(())
  2149. }
  2150. },
  2151. Subcmd::Token { command } => match command {
  2152. TokenSubcmd::Import { secret_key, token_blind } => {
  2153. let mint_authority = match SecretKey::from_str(&secret_key) {
  2154. Ok(ma) => ma,
  2155. Err(e) => {
  2156. eprintln!("Invalid mint authority: {e}");
  2157. exit(2);
  2158. }
  2159. };
  2160. let token_blind = match BaseBlind::from_str(&token_blind) {
  2161. Ok(tb) => tb,
  2162. Err(e) => {
  2163. eprintln!("Invalid token blind: {e}");
  2164. exit(2);
  2165. }
  2166. };
  2167. let drk = new_wallet(
  2168. network,
  2169. blockchain_config.cache_path,
  2170. blockchain_config.wallet_path,
  2171. blockchain_config.wallet_pass,
  2172. None,
  2173. &ex,
  2174. args.fun,
  2175. )
  2176. .await;
  2177. let token_id = drk.import_mint_authority(mint_authority, token_blind).await?;
  2178. println!("Successfully imported mint authority for token ID: {token_id}");
  2179. Ok(())
  2180. }
  2181. TokenSubcmd::GenerateMint => {
  2182. let drk = new_wallet(
  2183. network,
  2184. blockchain_config.cache_path,
  2185. blockchain_config.wallet_path,
  2186. blockchain_config.wallet_pass,
  2187. None,
  2188. &ex,
  2189. args.fun,
  2190. )
  2191. .await;
  2192. let mint_authority = SecretKey::random(&mut OsRng);
  2193. let token_blind = BaseBlind::random(&mut OsRng);
  2194. let token_id = drk.import_mint_authority(mint_authority, token_blind).await?;
  2195. println!("Successfully imported mint authority for token ID: {token_id}");
  2196. Ok(())
  2197. }
  2198. TokenSubcmd::List => {
  2199. let drk = new_wallet(
  2200. network,
  2201. blockchain_config.cache_path,
  2202. blockchain_config.wallet_path,
  2203. blockchain_config.wallet_pass,
  2204. None,
  2205. &ex,
  2206. args.fun,
  2207. )
  2208. .await;
  2209. let tokens = drk.get_mint_authorities().await?;
  2210. let aliases_map = match drk.get_aliases_mapped_by_token().await {
  2211. Ok(map) => map,
  2212. Err(e) => {
  2213. eprintln!("Failed to fetch wallet aliases: {e}");
  2214. exit(2);
  2215. }
  2216. };
  2217. let table = prettytable_tokenlist(&tokens, &aliases_map);
  2218. if table.is_empty() {
  2219. println!("No tokens found");
  2220. } else {
  2221. println!("{table}");
  2222. }
  2223. Ok(())
  2224. }
  2225. TokenSubcmd::Mint { token, amount, recipient, spend_hook, user_data } => {
  2226. let drk = new_wallet(
  2227. network,
  2228. blockchain_config.cache_path,
  2229. blockchain_config.wallet_path,
  2230. blockchain_config.wallet_pass,
  2231. Some(blockchain_config.endpoint),
  2232. &ex,
  2233. args.fun,
  2234. )
  2235. .await;
  2236. if let Err(e) = f64::from_str(&amount) {
  2237. eprintln!("Invalid amount: {e}");
  2238. exit(2);
  2239. }
  2240. let rcpt = match Address::from_str(&recipient) {
  2241. Ok(r) => r,
  2242. Err(e) => {
  2243. eprintln!("Invalid recipient: {e}");
  2244. exit(2);
  2245. }
  2246. };
  2247. if rcpt.network() != drk.network {
  2248. eprintln!("Recipient address prefix mismatch");
  2249. exit(2);
  2250. }
  2251. let token_id = match drk.get_token(token).await {
  2252. Ok(t) => t,
  2253. Err(e) => {
  2254. eprintln!("Invalid Token ID: {e}");
  2255. exit(2);
  2256. }
  2257. };
  2258. let spend_hook = match spend_hook {
  2259. Some(s) => match FuncId::from_str(&s) {
  2260. Ok(s) => Some(s),
  2261. Err(e) => {
  2262. eprintln!("Invalid spend hook: {e}");
  2263. exit(2);
  2264. }
  2265. },
  2266. None => None,
  2267. };
  2268. let user_data = match user_data {
  2269. Some(u) => {
  2270. let bytes: [u8; 32] = match bs58::decode(&u).into_vec()?.try_into() {
  2271. Ok(b) => b,
  2272. Err(e) => {
  2273. eprintln!("Invalid user data: {e:?}");
  2274. exit(2);
  2275. }
  2276. };
  2277. match pallas::Base::from_repr(bytes).into() {
  2278. Some(v) => Some(v),
  2279. None => {
  2280. eprintln!("Invalid user data");
  2281. exit(2);
  2282. }
  2283. }
  2284. }
  2285. None => None,
  2286. };
  2287. let tx = match drk
  2288. .mint_token(&amount, *rcpt.public_key(), token_id, spend_hook, user_data)
  2289. .await
  2290. {
  2291. Ok(tx) => tx,
  2292. Err(e) => {
  2293. eprintln!("Failed to create token mint transaction: {e}");
  2294. exit(2);
  2295. }
  2296. };
  2297. println!("{}", base64::encode(&serialize_async(&tx).await));
  2298. drk.stop_rpc_client().await
  2299. }
  2300. TokenSubcmd::Freeze { token } => {
  2301. let drk = new_wallet(
  2302. network,
  2303. blockchain_config.cache_path,
  2304. blockchain_config.wallet_path,
  2305. blockchain_config.wallet_pass,
  2306. Some(blockchain_config.endpoint),
  2307. &ex,
  2308. args.fun,
  2309. )
  2310. .await;
  2311. let token_id = match drk.get_token(token).await {
  2312. Ok(t) => t,
  2313. Err(e) => {
  2314. eprintln!("Invalid Token ID: {e}");
  2315. exit(2);
  2316. }
  2317. };
  2318. let tx = match drk.freeze_token(token_id).await {
  2319. Ok(tx) => tx,
  2320. Err(e) => {
  2321. eprintln!("Failed to create token freeze transaction: {e}");
  2322. exit(2);
  2323. }
  2324. };
  2325. println!("{}", base64::encode(&serialize_async(&tx).await));
  2326. drk.stop_rpc_client().await
  2327. }
  2328. },
  2329. Subcmd::Contract { command } => match command {
  2330. ContractSubcmd::GenerateDeploy => {
  2331. let drk = new_wallet(
  2332. network,
  2333. blockchain_config.cache_path,
  2334. blockchain_config.wallet_path,
  2335. blockchain_config.wallet_pass,
  2336. None,
  2337. &ex,
  2338. args.fun,
  2339. )
  2340. .await;
  2341. let mut output = vec![];
  2342. if let Err(e) = drk.deploy_auth_keygen(&mut output).await {
  2343. print_output(&output);
  2344. eprintln!("Error creating deploy auth keypair: {e}");
  2345. exit(2);
  2346. }
  2347. print_output(&output);
  2348. Ok(())
  2349. }
  2350. ContractSubcmd::List { contract_id } => {
  2351. let drk = new_wallet(
  2352. network,
  2353. blockchain_config.cache_path,
  2354. blockchain_config.wallet_path,
  2355. blockchain_config.wallet_pass,
  2356. None,
  2357. &ex,
  2358. args.fun,
  2359. )
  2360. .await;
  2361. if let Some(contract_id) = contract_id {
  2362. let contract_id = match ContractId::from_str(&contract_id) {
  2363. Ok(d) => d,
  2364. Err(e) => {
  2365. eprintln!("Invalid contract id: {e}");
  2366. exit(2);
  2367. }
  2368. };
  2369. let history = drk.get_deploy_auth_history(&contract_id).await?;
  2370. let table = prettytable_contract_history(&history);
  2371. if table.is_empty() {
  2372. println!("No history records found");
  2373. } else {
  2374. println!("{table}");
  2375. }
  2376. return Ok(())
  2377. }
  2378. let auths = drk.list_deploy_auth().await?;
  2379. let table = prettytable_contract_auth(&auths);
  2380. if table.is_empty() {
  2381. println!("No deploy authorities found");
  2382. } else {
  2383. println!("{table}");
  2384. }
  2385. Ok(())
  2386. }
  2387. ContractSubcmd::ExportData { tx_hash } => {
  2388. let drk = new_wallet(
  2389. network,
  2390. blockchain_config.cache_path,
  2391. blockchain_config.wallet_path,
  2392. blockchain_config.wallet_pass,
  2393. None,
  2394. &ex,
  2395. args.fun,
  2396. )
  2397. .await;
  2398. let pair = drk.get_deploy_history_record_data(&tx_hash).await?;
  2399. println!("{}", base64::encode(&serialize_async(&pair).await));
  2400. Ok(())
  2401. }
  2402. ContractSubcmd::Deploy { deploy_auth, wasm_path, deploy_ix } => {
  2403. // Parse the deployment authority contract id
  2404. let deploy_auth = match ContractId::from_str(&deploy_auth) {
  2405. Ok(d) => d,
  2406. Err(e) => {
  2407. eprintln!("Invalid deploy authority: {e}");
  2408. exit(2);
  2409. }
  2410. };
  2411. // Read the wasm bincode and deploy instruction
  2412. let wasm_bin = smol::fs::read(expand_path(&wasm_path)?).await?;
  2413. let deploy_ix = match deploy_ix {
  2414. Some(p) => smol::fs::read(expand_path(&p)?).await?,
  2415. None => vec![],
  2416. };
  2417. let drk = new_wallet(
  2418. network,
  2419. blockchain_config.cache_path,
  2420. blockchain_config.wallet_path,
  2421. blockchain_config.wallet_pass,
  2422. Some(blockchain_config.endpoint),
  2423. &ex,
  2424. args.fun,
  2425. )
  2426. .await;
  2427. let tx = match drk.deploy_contract(&deploy_auth, wasm_bin, deploy_ix).await {
  2428. Ok(tx) => tx,
  2429. Err(e) => {
  2430. eprintln!("Error creating contract deployment tx: {e}");
  2431. exit(2);
  2432. }
  2433. };
  2434. println!("{}", base64::encode(&serialize_async(&tx).await));
  2435. drk.stop_rpc_client().await
  2436. }
  2437. ContractSubcmd::Lock { deploy_auth } => {
  2438. // Parse the deployment authority contract id
  2439. let deploy_auth = match ContractId::from_str(&deploy_auth) {
  2440. Ok(d) => d,
  2441. Err(e) => {
  2442. eprintln!("Invalid deploy authority: {e}");
  2443. exit(2);
  2444. }
  2445. };
  2446. let drk = new_wallet(
  2447. network,
  2448. blockchain_config.cache_path,
  2449. blockchain_config.wallet_path,
  2450. blockchain_config.wallet_pass,
  2451. Some(blockchain_config.endpoint),
  2452. &ex,
  2453. args.fun,
  2454. )
  2455. .await;
  2456. let tx = match drk.lock_contract(&deploy_auth).await {
  2457. Ok(tx) => tx,
  2458. Err(e) => {
  2459. eprintln!("Error creating contract lock tx: {e}");
  2460. exit(2);
  2461. }
  2462. };
  2463. println!("{}", base64::encode(&serialize_async(&tx).await));
  2464. drk.stop_rpc_client().await
  2465. }
  2466. },
  2467. }
  2468. }