interactive.rs 113 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349
  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. fs::{File, OpenOptions},
  20. io::{stdin, BufRead, BufReader, ErrorKind, Read, Seek, SeekFrom, Write},
  21. str::FromStr,
  22. };
  23. use futures::{select, FutureExt};
  24. use libc::{fcntl, F_GETFL, F_SETFL, O_NONBLOCK};
  25. use linenoise_rs::{
  26. linenoise_history_add, linenoise_history_load, linenoise_history_save,
  27. linenoise_set_completion_callback, linenoise_set_hints_callback, LinenoiseState,
  28. };
  29. use prettytable::{format, row, Table};
  30. use rand::rngs::OsRng;
  31. use smol::channel::{Receiver, Sender};
  32. use url::Url;
  33. use darkfi::{
  34. cli_desc,
  35. system::{msleep, ExecutorPtr, StoppableTask, StoppableTaskPtr},
  36. util::{
  37. encoding::base64,
  38. parse::{decode_base10, encode_base10},
  39. path::expand_path,
  40. },
  41. zk::halo2::Field,
  42. Error,
  43. };
  44. use darkfi_dao_contract::{blockwindow, model::DaoProposalBulla, DaoFunction};
  45. use darkfi_money_contract::model::{Coin, CoinAttributes, TokenId};
  46. use darkfi_sdk::{
  47. crypto::{
  48. keypair::{Address, StandardAddress},
  49. note::AeadEncryptedNote,
  50. BaseBlind, ContractId, FuncId, FuncRef, Keypair, SecretKey, DAO_CONTRACT_ID,
  51. },
  52. pasta::{group::ff::PrimeField, pallas},
  53. tx::TransactionHash,
  54. };
  55. use darkfi_serial::{deserialize_async, serialize_async};
  56. use crate::{
  57. cli_util::{
  58. append_or_print, display_mining_config, generate_completions, kaching,
  59. parse_calls_from_input, parse_mining_config_from_input, parse_token_pair, parse_tree,
  60. parse_tx_from_input, parse_value_pair, print_output, tx_from_calls_mapped,
  61. },
  62. common::*,
  63. dao::{DaoParams, ProposalRecord},
  64. money::BALANCE_BASE10_DECIMALS,
  65. rpc::subscribe_blocks,
  66. swap::PartialSwapData,
  67. DrkPtr,
  68. };
  69. // TODO:
  70. // 1. Create a transactions cache in the wallet db, so you can use it to handle them.
  71. /// Auxiliary function to print the help message.
  72. fn help(output: &mut Vec<String>) {
  73. output.push(String::from(cli_desc!()));
  74. output.push(String::from("Commands:"));
  75. output.push(String::from("\thelp: Prints the help message"));
  76. output.push(String::from("\tkaching: Fun"));
  77. output.push(String::from("\tping: Send a ping request to the darkfid RPC endpoint"));
  78. output.push(String::from(
  79. "\tcompletions: Generate a SHELL completion script and print to stdout",
  80. ));
  81. output.push(String::from("\twallet: Wallet operations"));
  82. output.push(String::from(
  83. "\tspend: Read a transaction from stdin and mark its input coins as spent",
  84. ));
  85. output.push(String::from("\tunspend: Unspend a coin"));
  86. output.push(String::from("\ttransfer: Create a payment transaction"));
  87. output.push(String::from("\totc: OTC atomic swap"));
  88. output.push(String::from("\tdao: DAO functionalities"));
  89. output
  90. .push(String::from("\tattach-fee: Attach the fee call to a transaction given from stdin"));
  91. output.push(String::from(
  92. "\ttx-from-calls: Create a transaction from newline-separated calls from stdin",
  93. ));
  94. output.push(String::from("\tinspect: Inspect a transaction from stdin"));
  95. output.push(String::from("\tbroadcast: Read a transaction from stdin and broadcast it"));
  96. output.push(String::from(
  97. "\tsubscribe: Perform a scan and then subscribe to darkfid to listen for incoming blocks",
  98. ));
  99. output.push(String::from("\tunsubscribe: Stops the background subscription, if its active"));
  100. output.push(String::from("\tsnooze: Disables the background subscription messages printing"));
  101. output.push(String::from("\tunsnooze: Enables the background subscription messages printing"));
  102. output.push(String::from("\tscan: Scan the blockchain and parse relevant transactions"));
  103. output.push(String::from("\texplorer: Explorer related subcommands"));
  104. output.push(String::from("\talias: Token alias"));
  105. output.push(String::from("\ttoken: Token functionalities"));
  106. output.push(String::from("\tcontract: Contract functionalities"));
  107. }
  108. /// Auxiliary function to define the interactive shell completions.
  109. fn completion(buffer: &str, lc: &mut Vec<String>) {
  110. // Split commands so we always process the last one
  111. let commands: Vec<&str> = buffer.split('|').collect();
  112. // Grab the prefix
  113. let prefix = if commands.len() > 1 {
  114. commands[..commands.len() - 1].join("|") + "| "
  115. } else {
  116. String::from("")
  117. };
  118. let last = commands.last().unwrap().trim_start();
  119. // First we define the specific commands prefixes
  120. if last.starts_with("h") {
  121. lc.push(prefix + "help");
  122. return
  123. }
  124. if last.starts_with("k") {
  125. lc.push(prefix + "kaching");
  126. return
  127. }
  128. if last.starts_with("p") {
  129. lc.push(prefix + "ping");
  130. return
  131. }
  132. if last.starts_with("com") {
  133. lc.push(prefix + "completions");
  134. return
  135. }
  136. if last.starts_with("w") {
  137. lc.push(prefix.clone() + "wallet");
  138. lc.push(prefix.clone() + "wallet initialize");
  139. lc.push(prefix.clone() + "wallet keygen");
  140. lc.push(prefix.clone() + "wallet balance");
  141. lc.push(prefix.clone() + "wallet address");
  142. lc.push(prefix.clone() + "wallet addresses");
  143. lc.push(prefix.clone() + "wallet default-address");
  144. lc.push(prefix.clone() + "wallet secrets");
  145. lc.push(prefix.clone() + "wallet import-secrets");
  146. lc.push(prefix.clone() + "wallet tree");
  147. lc.push(prefix.clone() + "wallet coins");
  148. lc.push(prefix + "wallet mining-config");
  149. return
  150. }
  151. if last.starts_with("sp") {
  152. lc.push(prefix + "spend");
  153. return
  154. }
  155. if last.starts_with("unsp") {
  156. lc.push(prefix + "unspend");
  157. return
  158. }
  159. if last.starts_with("tr") {
  160. lc.push(prefix + "transfer");
  161. return
  162. }
  163. if last.starts_with("o") {
  164. lc.push(prefix.clone() + "otc");
  165. lc.push(prefix.clone() + "otc init");
  166. lc.push(prefix.clone() + "otc join");
  167. lc.push(prefix.clone() + "otc inspect");
  168. lc.push(prefix + "otc sign");
  169. return
  170. }
  171. if last.starts_with("d") {
  172. lc.push(prefix.clone() + "dao");
  173. lc.push(prefix.clone() + "dao create");
  174. lc.push(prefix.clone() + "dao view");
  175. lc.push(prefix.clone() + "dao import");
  176. lc.push(prefix.clone() + "dao list");
  177. lc.push(prefix.clone() + "dao balance");
  178. lc.push(prefix.clone() + "dao mint");
  179. lc.push(prefix.clone() + "dao propose-transfer");
  180. lc.push(prefix.clone() + "dao propose-generic");
  181. lc.push(prefix.clone() + "dao proposals");
  182. lc.push(prefix.clone() + "dao proposal");
  183. lc.push(prefix.clone() + "dao proposal-import");
  184. lc.push(prefix.clone() + "dao vote");
  185. lc.push(prefix.clone() + "dao exec");
  186. lc.push(prefix.clone() + "dao spend-hook");
  187. lc.push(prefix + "dao mining-config");
  188. return
  189. }
  190. if last.starts_with("at") {
  191. lc.push(prefix + "attach-fee");
  192. return
  193. }
  194. if last.starts_with("tx") {
  195. lc.push(prefix + "tx-from-calls");
  196. return
  197. }
  198. if last.starts_with("i") {
  199. lc.push(prefix + "inspect");
  200. return
  201. }
  202. if last.starts_with("b") {
  203. lc.push(prefix + "broadcast");
  204. return
  205. }
  206. if last.starts_with("su") {
  207. lc.push(prefix + "subscribe");
  208. return
  209. }
  210. if last.starts_with("unsu") {
  211. lc.push(prefix + "unsubscribe");
  212. return
  213. }
  214. if last.starts_with("sn") {
  215. lc.push(prefix + "snooze");
  216. return
  217. }
  218. if last.starts_with("unsn") {
  219. lc.push(prefix + "unsnooze");
  220. return
  221. }
  222. if last.starts_with("sc") {
  223. lc.push(prefix.clone() + "scan");
  224. lc.push(prefix + "scan --reset");
  225. return
  226. }
  227. if last.starts_with("e") {
  228. lc.push(prefix.clone() + "explorer");
  229. lc.push(prefix.clone() + "explorer fetch-tx");
  230. lc.push(prefix.clone() + "explorer simulate-tx");
  231. lc.push(prefix.clone() + "explorer txs-history");
  232. lc.push(prefix.clone() + "explorer clear-reverted");
  233. lc.push(prefix.clone() + "explorer scanned-blocks");
  234. lc.push(prefix + "explorer mining-config");
  235. return
  236. }
  237. if last.starts_with("al") {
  238. lc.push(prefix.clone() + "alias");
  239. lc.push(prefix.clone() + "alias add");
  240. lc.push(prefix.clone() + "alias show");
  241. lc.push(prefix + "alias remove");
  242. return
  243. }
  244. if last.starts_with("to") {
  245. lc.push(prefix.clone() + "token");
  246. lc.push(prefix.clone() + "token import");
  247. lc.push(prefix.clone() + "token generate-mint");
  248. lc.push(prefix.clone() + "token list");
  249. lc.push(prefix.clone() + "token mint");
  250. lc.push(prefix + "token freeze");
  251. return
  252. }
  253. if last.starts_with("con") {
  254. lc.push(prefix.clone() + "contract");
  255. lc.push(prefix.clone() + "contract generate-deploy");
  256. lc.push(prefix.clone() + "contract list");
  257. lc.push(prefix.clone() + "contract export-data");
  258. lc.push(prefix.clone() + "contract deploy");
  259. lc.push(prefix + "contract lock");
  260. return
  261. }
  262. // Now the catch alls
  263. if last.starts_with("a") {
  264. lc.push(prefix.clone() + "attach-fee");
  265. lc.push(prefix.clone() + "alias");
  266. lc.push(prefix.clone() + "alias add");
  267. lc.push(prefix.clone() + "alias show");
  268. lc.push(prefix + "alias remove");
  269. return
  270. }
  271. if last.starts_with("c") {
  272. lc.push(prefix.clone() + "completions");
  273. lc.push(prefix.clone() + "contract");
  274. lc.push(prefix.clone() + "contract generate-deploy");
  275. lc.push(prefix.clone() + "contract list");
  276. lc.push(prefix.clone() + "contract export-data");
  277. lc.push(prefix.clone() + "contract deploy");
  278. lc.push(prefix + "contract lock");
  279. return
  280. }
  281. if last.starts_with("s") {
  282. lc.push(prefix.clone() + "spend");
  283. lc.push(prefix.clone() + "subscribe");
  284. lc.push(prefix.clone() + "snooze");
  285. lc.push(prefix.clone() + "scan");
  286. lc.push(prefix + "scan --reset");
  287. return
  288. }
  289. if last.starts_with("t") {
  290. lc.push(prefix.clone() + "transfer");
  291. lc.push(prefix.clone() + "token");
  292. lc.push(prefix.clone() + "token import");
  293. lc.push(prefix.clone() + "token generate-mint");
  294. lc.push(prefix.clone() + "token list");
  295. lc.push(prefix.clone() + "token mint");
  296. lc.push(prefix + "token freeze");
  297. return
  298. }
  299. if last.starts_with("u") {
  300. lc.push(prefix.clone() + "unspend");
  301. lc.push(prefix.clone() + "unsubscribe");
  302. lc.push(prefix + "unsnooze");
  303. }
  304. }
  305. /// Auxiliary function to define the interactive shell hints.
  306. fn hints(buffer: &str) -> Option<(String, i32, bool)> {
  307. // Split commands so we always process the last one
  308. let commands: Vec<&str> = buffer.split('|').collect();
  309. let last = commands.last().unwrap().trim_start();
  310. let color = 35; // magenta
  311. let bold = false;
  312. match last {
  313. "completions " => Some(("<shell>".to_string(), color, bold)),
  314. "wallet " => Some(("(initialize|keygen|balance|address|addresses|default-address|secrets|import-secrets|tree|coins|mining-config)".to_string(), color, bold)),
  315. "wallet default-address " => Some(("<index>".to_string(), color, bold)),
  316. "wallet mining-config " => Some(("<index> [spend_hook] [user_data]".to_string(), color, bold)),
  317. "unspend " => Some(("<coin>".to_string(), color, bold)),
  318. "transfer " => Some(("[--half-split] <amount> <token> <recipient> [spend_hook] [user_data]".to_string(), color, bold)),
  319. "otc " => Some(("(init|join|inspect|sign)".to_string(), color, bold)),
  320. "otc init " => Some(("<value_pair> <token_pair>".to_string(), color, bold)),
  321. "dao " => Some(("(create|view|import|list|balance|mint|propose-transfer|propose-generic|proposals|proposal|proposal-import|vote|exec|spend-hook|mining-config)".to_string(), color, bold)),
  322. "dao create " => Some(("<proposer-limit> <quorum> <early-exec-quorum> <approval-ratio> <gov-token-id>".to_string(), color, bold)),
  323. "dao import " => Some(("<name>".to_string(), color, bold)),
  324. "dao list " => Some(("[name]".to_string(), color, bold)),
  325. "dao balance " => Some(("<name>".to_string(), color, bold)),
  326. "dao mint " => Some(("<name>".to_string(), color, bold)),
  327. "dao propose-transfer " => Some(("<name> <duration> <amount> <token> <recipient> [spend-hook] [user-data]".to_string(), color, bold)),
  328. "dao propose-generic" => Some(("<name> <duration> [user-data]".to_string(), color, bold)),
  329. "dao proposals " => Some(("<name>".to_string(), color, bold)),
  330. "dao proposal " => Some(("[--(export|mint-proposal)] <bulla>".to_string(), color, bold)),
  331. "dao vote " => Some(("<bulla> <vote> [vote-weight]".to_string(), color, bold)),
  332. "dao exec " => Some(("[--early] <bulla>".to_string(), color, bold)),
  333. "dao mining-config " => Some(("<name>".to_string(), color, bold)),
  334. "scan " => Some(("[--reset]".to_string(), color, bold)),
  335. "scan --reset " => Some(("<height>".to_string(), color, bold)),
  336. "explorer " => Some(("(fetch-tx|simulate-tx|txs-history|clear-reverted|scanned-blocks|mining-config)".to_string(), color, bold)),
  337. "explorer fetch-tx " => Some(("[--encode] <tx-hash>".to_string(), color, bold)),
  338. "explorer txs-history " => Some(("[--encode] [tx-hash]".to_string(), color, bold)),
  339. "explorer scanned-blocks " => Some(("[height]".to_string(), color, bold)),
  340. "alias " => Some(("(add|show|remove)".to_string(), color, bold)),
  341. "alias add " => Some(("<alias> <token>".to_string(), color, bold)),
  342. "alias show " => Some(("[-a, --alias <alias>] [-t, --token <token>]".to_string(), color, bold)),
  343. "alias remove " => Some(("<alias>".to_string(), color, bold)),
  344. "token " => Some(("(import|generate-mint|list|mint|freeze)".to_string(), color, bold)),
  345. "token import " => Some(("<secret-key> <token-blind>".to_string(), color, bold)),
  346. "token mint " => Some(("<token> <amount> <recipient> [spend-hook] [user-data]".to_string(), color, bold)),
  347. "token freeze " => Some(("<token>".to_string(), color, bold)),
  348. "contract " => Some(("(generate-deploy|list|export-data|deploy|lock)".to_string(), color, bold)),
  349. "contract list " => Some(("[contract-id]".to_string(), color, bold)),
  350. "contract export-data " => Some(("<tx-hash>".to_string(), color, bold)),
  351. "contract deploy " => Some(("<deploy-auth> <wasm-path> [deploy-ix]".to_string(), color, bold)),
  352. "contract lock " => Some(("<deploy-auth>".to_string(), color, bold)),
  353. "tx-from-calls " => Some(("[calls-map]".to_string(), color, bold)),
  354. _ => None,
  355. }
  356. }
  357. /// Auxiliary function to start provided Drk as an interactive shell.
  358. /// Only sane/linenoise terminals are suported.
  359. pub async fn interactive(
  360. drk: &DrkPtr,
  361. endpoint: &Url,
  362. history_path: &str,
  363. shell_sender: &Sender<Vec<String>>,
  364. shell_receiver: &Receiver<Vec<String>>,
  365. ex: &ExecutorPtr,
  366. ) {
  367. // Expand the history file path
  368. let history_path = match expand_path(history_path) {
  369. Ok(p) => p,
  370. Err(e) => {
  371. eprintln!("Error while expanding history file path: {e}");
  372. return
  373. }
  374. };
  375. let history_path = history_path.into_os_string();
  376. let history_file = history_path.to_str().unwrap();
  377. // Set the completion callback. This will be called every time the
  378. // user uses the <tab> key.
  379. linenoise_set_completion_callback(completion);
  380. // Set the shell hints
  381. linenoise_set_hints_callback(hints);
  382. // Load history from file.The history file is just a plain text file
  383. // where entries are separated by newlines.
  384. let _ = linenoise_history_load(history_file);
  385. // Create two detached tasks to use for block subscription
  386. let mut subscription_active = false;
  387. let mut snooze_active = false;
  388. let subscription_tasks = [StoppableTask::new(), StoppableTask::new()];
  389. // Start the interactive shell
  390. loop {
  391. // Wait for next line to process
  392. let line = listen_for_line(&snooze_active, shell_receiver).await;
  393. // Grab input or end if Ctrl-D or Ctrl-C was pressed
  394. let Some(line) = line else { break };
  395. // Check if line is empty
  396. if line.is_empty() {
  397. continue
  398. }
  399. // Add line to history
  400. linenoise_history_add(&line);
  401. // Split commands
  402. let commands: Vec<&str> = line.split('|').collect();
  403. // Process each command
  404. let mut output = vec![];
  405. 'commands_loop: for (command_index, command) in commands.iter().enumerate() {
  406. let mut input = output;
  407. output = vec![];
  408. // Check if we have to output to a file
  409. let (mut command, file, append) = if command.contains('>') {
  410. // Check if we write or append to the file
  411. let mut split = ">";
  412. let mut append = false;
  413. if command.contains(">>") {
  414. split = ">>";
  415. append = true;
  416. }
  417. // Parse command parts
  418. let parts: Vec<&str> = command.split(split).collect();
  419. if parts.len() == 1 || parts[0].contains('>') {
  420. output.push(format!("Malformed command output file definition: {command}"));
  421. continue
  422. }
  423. let file = String::from(parts[1..].join("").trim());
  424. if file.is_empty() || file.contains('>') {
  425. output.push(format!("Malformed command output file definition: {command}"));
  426. continue
  427. }
  428. (parts[0], Some(file), append)
  429. } else {
  430. (*command, None, false)
  431. };
  432. // Check if we have to use a file as input
  433. if command.contains('<') {
  434. // Parse command parts
  435. let parts: Vec<&str> = command.split('<').collect();
  436. if parts.len() == 1 {
  437. output.push(format!("Malformed command input file definition: {command}"));
  438. continue
  439. }
  440. // Read the input file name
  441. let file = String::from(parts[1..].join("").trim());
  442. if file.is_empty() {
  443. output.push(format!("Malformed command input file definition: {command}"));
  444. continue
  445. }
  446. // Expand the input file path
  447. let file_path = match expand_path(&file) {
  448. Ok(p) => p,
  449. Err(e) => {
  450. output.push(format!("Error while expanding input file path: {e}"));
  451. continue
  452. }
  453. };
  454. // Read the file lines
  455. let file = match File::open(file_path) {
  456. Ok(f) => f,
  457. Err(e) => {
  458. output.push(format!("Error while openning input file: {e}"));
  459. continue
  460. }
  461. };
  462. input = vec![];
  463. for (index, line) in BufReader::new(file).lines().enumerate() {
  464. match line {
  465. Ok(l) => input.push(l),
  466. Err(e) => {
  467. output
  468. .push(format!("Error while reading input file line {index}: {e}"));
  469. continue 'commands_loop
  470. }
  471. }
  472. }
  473. command = parts[0];
  474. }
  475. // Parse command parts
  476. let parts: Vec<&str> = command.split_whitespace().collect();
  477. if parts.is_empty() {
  478. continue
  479. }
  480. // Handle command
  481. match parts[0] {
  482. "help" => help(&mut output),
  483. "kaching" => kaching().await,
  484. "ping" => handle_ping(drk, &mut output).await,
  485. "completions" => handle_completions(&parts, &mut output),
  486. "wallet" => handle_wallet(drk, &parts, &input, &mut output).await,
  487. "spend" => handle_spend(drk, &input, &mut output).await,
  488. "unspend" => handle_unspend(drk, &parts, &mut output).await,
  489. "transfer" => handle_transfer(drk, &parts, &mut output).await,
  490. "otc" => handle_otc(drk, &parts, &input, &mut output).await,
  491. "dao" => handle_dao(drk, &parts, &input, &mut output).await,
  492. "attach-fee" => handle_attach_fee(drk, &input, &mut output).await,
  493. "tx-from-calls" => handle_tx_from_calls(&parts, &input, &mut output).await,
  494. "inspect" => handle_inspect(&input, &mut output).await,
  495. "broadcast" => handle_broadcast(drk, &input, &mut output).await,
  496. "subscribe" => {
  497. handle_subscribe(
  498. drk,
  499. endpoint,
  500. &mut subscription_active,
  501. &subscription_tasks,
  502. shell_sender,
  503. ex,
  504. )
  505. .await
  506. }
  507. "unsubscribe" => {
  508. handle_unsubscribe(&mut subscription_active, &subscription_tasks).await
  509. }
  510. "snooze" => snooze_active = true,
  511. "unsnooze" => snooze_active = false,
  512. "scan" => {
  513. handle_scan(
  514. drk,
  515. &subscription_active,
  516. &parts,
  517. &mut output,
  518. &(command_index + 1 == commands.len() && file.is_none()),
  519. )
  520. .await
  521. }
  522. "explorer" => handle_explorer(drk, &parts, &input, &mut output).await,
  523. "alias" => handle_alias(drk, &parts, &mut output).await,
  524. "token" => handle_token(drk, &parts, &mut output).await,
  525. "contract" => handle_contract(drk, &parts, &mut output).await,
  526. _ => output.push(format!("Unrecognized command: {}", parts[0])),
  527. }
  528. // Write output to file, if requested
  529. if let Some(file) = file {
  530. // Expand the output file path
  531. let file_path = match expand_path(&file) {
  532. Ok(p) => p,
  533. Err(e) => {
  534. output.push(format!("Error while expanding output file path: {e}"));
  535. continue
  536. }
  537. };
  538. // Open the file
  539. let file = if append {
  540. OpenOptions::new().create(true).append(true).open(&file_path)
  541. } else {
  542. File::create(file_path)
  543. };
  544. let mut file = match file {
  545. Ok(f) => f,
  546. Err(e) => {
  547. output.push(format!("Error while openning output file: {e}"));
  548. continue
  549. }
  550. };
  551. // Seek end if we append to it
  552. if append {
  553. if let Err(e) = file.seek(SeekFrom::End(0)) {
  554. output.push(format!("Error while seeking end of output file: {e}"));
  555. continue
  556. }
  557. }
  558. // Write the output
  559. if let Err(e) = file.write_all((output.join("\n") + "\n").as_bytes()) {
  560. output.push(format!("Error while writing output file: {e}"));
  561. continue
  562. }
  563. output = vec![];
  564. }
  565. }
  566. // Handle last command output
  567. print_output(&output);
  568. }
  569. // Stop the subscription tasks if they are active
  570. subscription_tasks[0].stop_nowait();
  571. subscription_tasks[1].stop_nowait();
  572. // Write history file
  573. let _ = linenoise_history_save(history_file);
  574. }
  575. /// Auxiliary function to listen for linenoise input line and handle
  576. /// background task messages.
  577. async fn listen_for_line(
  578. snooze_active: &bool,
  579. shell_receiver: &Receiver<Vec<String>>,
  580. ) -> Option<String> {
  581. // Generate the linoise state structure
  582. let mut state = match LinenoiseState::edit_start(-1, -1, "drk> ") {
  583. Ok(s) => s,
  584. Err(e) => {
  585. eprintln!("Error while generating linenoise state: {e}");
  586. return None
  587. }
  588. };
  589. // Set stdin to non-blocking mode
  590. let fd = state.get_fd();
  591. unsafe {
  592. let flags = fcntl(fd, F_GETFL, 0);
  593. fcntl(fd, F_SETFL, flags | O_NONBLOCK);
  594. }
  595. // Read until we get a line to process
  596. let mut line = None;
  597. loop {
  598. // Future that polls stdin for input
  599. let input_future = async {
  600. loop {
  601. match state.edit_feed() {
  602. Ok(Some(l)) => {
  603. line = Some(l);
  604. break
  605. }
  606. Ok(None) => break,
  607. Err(e) if e.kind() == ErrorKind::Interrupted => break,
  608. Err(e) if e.kind() == ErrorKind::WouldBlock => {
  609. // No data available, yield and retry
  610. msleep(10).await;
  611. continue
  612. }
  613. Err(e) => {
  614. eprintln!("Error while reading linenoise feed: {e}");
  615. break
  616. }
  617. }
  618. }
  619. };
  620. // Future that polls the channel
  621. let channel_future = async {
  622. loop {
  623. if !shell_receiver.is_empty() {
  624. break
  625. }
  626. msleep(1000).await;
  627. }
  628. };
  629. // Manage the futures
  630. select! {
  631. // When input is ready we break out the loop
  632. _ = input_future.fuse() => break,
  633. // Manage filled channel
  634. _ = channel_future.fuse() => {
  635. // We only print if snooze is inactive,
  636. // but have to consume the message regardless,
  637. // so the queue gets empty.
  638. if *snooze_active {
  639. while !shell_receiver.is_empty() {
  640. if let Err(e) = shell_receiver.recv().await {
  641. eprintln!("Error while reading shell receiver channel: {e}");
  642. break
  643. }
  644. }
  645. } else {
  646. // Hide prompt
  647. if let Err(e) = state.hide() {
  648. eprintln!("Error while hiding linenoise state: {e}");
  649. break
  650. };
  651. // Restore blocking mode
  652. unsafe {
  653. let flags = fcntl(fd, F_GETFL, 0);
  654. fcntl(fd, F_SETFL, flags & !O_NONBLOCK);
  655. }
  656. // Print output
  657. while !shell_receiver.is_empty() {
  658. match shell_receiver.recv().await {
  659. Ok(msg) => {
  660. for line in msg {
  661. println!("{}\r", line.replace("\n", "\n\r"));
  662. }
  663. }
  664. Err(e) => {
  665. eprintln!("Error while reading shell receiver channel: {e}");
  666. break
  667. }
  668. }
  669. }
  670. // Set stdin to non-blocking mode
  671. unsafe {
  672. let flags = fcntl(fd, F_GETFL, 0);
  673. fcntl(fd, F_SETFL, flags | O_NONBLOCK);
  674. }
  675. // Show prompt again
  676. if let Err(e) = state.show() {
  677. eprintln!("Error while showing linenoise state: {e}");
  678. break
  679. };
  680. }
  681. }
  682. }
  683. }
  684. // Restore blocking mode
  685. unsafe {
  686. let flags = fcntl(fd, F_GETFL, 0);
  687. fcntl(fd, F_SETFL, flags & !O_NONBLOCK);
  688. }
  689. if let Err(e) = state.edit_stop() {
  690. eprintln!("Error while stopping linenoise state: {e}");
  691. };
  692. line
  693. }
  694. /// Auxiliary function to define the ping command handling.
  695. async fn handle_ping(drk: &DrkPtr, output: &mut Vec<String>) {
  696. if let Err(e) = drk.read().await.ping(output).await {
  697. output.push(format!("Error while executing ping command: {e}"))
  698. }
  699. }
  700. /// Auxiliary function to define the completions command handling.
  701. fn handle_completions(parts: &[&str], output: &mut Vec<String>) {
  702. // Check correct command structure
  703. if parts.len() != 2 {
  704. output.push(String::from("Malformed `completions` command"));
  705. output.push(String::from("Usage: completions <shell>"));
  706. return
  707. }
  708. match generate_completions(parts[1]) {
  709. Ok(completions) => output.push(completions),
  710. Err(e) => output.push(format!("Error while executing completions command: {e}")),
  711. }
  712. }
  713. /// Auxiliary function to define the wallet command handling.
  714. async fn handle_wallet(drk: &DrkPtr, parts: &[&str], input: &[String], output: &mut Vec<String>) {
  715. // Check correct command structure
  716. if parts.len() < 2 {
  717. output.push(String::from("Malformed `wallet` command"));
  718. output.push(String::from("Usage: wallet (initialize|keygen|balance|address|addresses|default-address|secrets|import-secrets|tree|coins|mining-config)"));
  719. return
  720. }
  721. // Handle subcommand
  722. match parts[1] {
  723. "initialize" => handle_wallet_initialize(drk, output).await,
  724. "keygen" => handle_wallet_keygen(drk, output).await,
  725. "balance" => handle_wallet_balance(drk, output).await,
  726. "address" => handle_wallet_address(drk, output).await,
  727. "addresses" => handle_wallet_addresses(drk, output).await,
  728. "default-address" => handle_wallet_default_address(drk, parts, output).await,
  729. "secrets" => handle_wallet_secrets(drk, output).await,
  730. "import-secrets" => handle_wallet_import_secrets(drk, input, output).await,
  731. "tree" => handle_wallet_tree(drk, output).await,
  732. "coins" => handle_wallet_coins(drk, output).await,
  733. "mining-config" => handle_wallet_mining_config(drk, parts, output).await,
  734. _ => {
  735. output.push(format!("Unrecognized wallet subcommand: {}", parts[1]));
  736. output.push(String::from("Usage: wallet (initialize|keygen|balance|address|addresses|default-address|secrets|import-secrets|tree|coins|mining-config)"));
  737. }
  738. }
  739. }
  740. /// Auxiliary function to define the wallet initialize subcommand handling.
  741. async fn handle_wallet_initialize(drk: &DrkPtr, output: &mut Vec<String>) {
  742. let lock = drk.read().await;
  743. if let Err(e) = lock.initialize_wallet().await {
  744. output.push(format!("Error initializing wallet: {e}"));
  745. return
  746. }
  747. if let Err(e) = lock.initialize_money(output).await {
  748. output.push(format!("Failed to initialize Money: {e}"));
  749. return
  750. }
  751. if let Err(e) = lock.initialize_dao().await {
  752. output.push(format!("Failed to initialize DAO: {e}"));
  753. return
  754. }
  755. if let Err(e) = lock.initialize_deployooor() {
  756. output.push(format!("Failed to initialize Deployooor: {e}"));
  757. }
  758. }
  759. /// Auxiliary function to define the wallet keygen subcommand handling.
  760. async fn handle_wallet_keygen(drk: &DrkPtr, output: &mut Vec<String>) {
  761. if let Err(e) = drk.read().await.money_keygen(output).await {
  762. output.push(format!("Failed to generate keypair: {e}"));
  763. }
  764. }
  765. /// Auxiliary function to define the wallet balance subcommand handling.
  766. async fn handle_wallet_balance(drk: &DrkPtr, output: &mut Vec<String>) {
  767. let drk = drk.read().await;
  768. let balmap = match drk.money_balance().await {
  769. Ok(m) => m,
  770. Err(e) => {
  771. output.push(format!("Failed to fetch balances map: {e}"));
  772. return
  773. }
  774. };
  775. let alimap = match drk.get_aliases_mapped_by_token().await {
  776. Ok(m) => m,
  777. Err(e) => {
  778. output.push(format!("Failed to fetch aliases map: {e}"));
  779. return
  780. }
  781. };
  782. let table = prettytable_balance(&balmap, &alimap);
  783. if table.is_empty() {
  784. output.push(String::from("No unspent balances found"));
  785. } else {
  786. output.push(format!("{table}"));
  787. }
  788. }
  789. /// Auxiliary function to define the wallet address subcommand handling.
  790. async fn handle_wallet_address(drk: &DrkPtr, output: &mut Vec<String>) {
  791. let drk = drk.read().await;
  792. let public_key = match drk.default_address().await {
  793. Ok(v) => v,
  794. Err(e) => {
  795. output.push(format!("Failed to fetch default address: {e}"));
  796. return
  797. }
  798. };
  799. let addr: Address = StandardAddress::from_public(drk.network, public_key).into();
  800. output.push(format!("{addr}"));
  801. }
  802. /// Auxiliary function to define the wallet addresses subcommand handling.
  803. async fn handle_wallet_addresses(drk: &DrkPtr, output: &mut Vec<String>) {
  804. let drk = drk.read().await;
  805. let network = drk.network;
  806. let addresses = match drk.addresses().await {
  807. Ok(v) => v,
  808. Err(e) => {
  809. output.push(format!("Failed to fetch addresses: {e}"));
  810. return
  811. }
  812. };
  813. let table = prettytable_addrs(network, &addresses);
  814. if table.is_empty() {
  815. output.push(String::from("No addresses found"));
  816. } else {
  817. output.push(format!("{table}"));
  818. }
  819. }
  820. /// Auxiliary function to define the wallet default address subcommand handling.
  821. async fn handle_wallet_default_address(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  822. if parts.len() != 3 {
  823. output.push(String::from("Malformed `wallet default-address` subcommand"));
  824. output.push(String::from("Usage: wallet default-address <index>"));
  825. return
  826. }
  827. let index = match usize::from_str(parts[2]) {
  828. Ok(i) => i,
  829. Err(e) => {
  830. output.push(format!("Invalid address id: {e}"));
  831. return
  832. }
  833. };
  834. if let Err(e) = drk.read().await.set_default_address(index) {
  835. output.push(format!("Failed to set default address: {e}"));
  836. }
  837. }
  838. /// Auxiliary function to define the wallet secrets subcommand handling.
  839. async fn handle_wallet_secrets(drk: &DrkPtr, output: &mut Vec<String>) {
  840. match drk.read().await.get_money_secrets().await {
  841. Ok(secrets) => {
  842. for secret in secrets {
  843. output.push(format!("{secret}"));
  844. }
  845. }
  846. Err(e) => output.push(format!("Failed to fetch secrets: {e}")),
  847. }
  848. }
  849. /// Auxiliary function to define the wallet import secrets subcommand handling.
  850. async fn handle_wallet_import_secrets(drk: &DrkPtr, input: &[String], output: &mut Vec<String>) {
  851. let mut secrets = vec![];
  852. // Parse input or read from stdin
  853. if input.is_empty() {
  854. for (i, line) in stdin().lines().enumerate() {
  855. let Ok(line) = line else { continue };
  856. let Ok(bytes) = bs58::decode(&line.trim()).into_vec() else {
  857. output.push(format!("Warning: Failed to decode secret on line {i}"));
  858. continue
  859. };
  860. let Ok(secret) = deserialize_async(&bytes).await else {
  861. output.push(format!("Warning: Failed to deserialize secret on line {i}"));
  862. continue
  863. };
  864. secrets.push(secret);
  865. }
  866. } else {
  867. for (i, line) in input.iter().enumerate() {
  868. let Ok(bytes) = bs58::decode(&line.trim()).into_vec() else {
  869. output.push(format!("Warning: Failed to decode secret on line {i}"));
  870. continue
  871. };
  872. let Ok(secret) = deserialize_async(&bytes).await else {
  873. output.push(format!("Warning: Failed to deserialize secret on line {i}"));
  874. continue
  875. };
  876. secrets.push(secret);
  877. }
  878. }
  879. match drk.read().await.import_money_secrets(secrets, output).await {
  880. Ok(pubkeys) => {
  881. for key in pubkeys {
  882. output.push(format!("{key}"));
  883. }
  884. }
  885. Err(e) => output.push(format!("Failed to import secrets: {e}")),
  886. }
  887. }
  888. /// Auxiliary function to define the wallet tree subcommand handling.
  889. async fn handle_wallet_tree(drk: &DrkPtr, output: &mut Vec<String>) {
  890. match drk.read().await.get_money_tree().await {
  891. Ok(tree) => output.push(format!("{tree:#?}")),
  892. Err(e) => output.push(format!("Failed to fetch tree: {e}")),
  893. }
  894. }
  895. /// Auxiliary function to define the wallet coins subcommand handling.
  896. async fn handle_wallet_coins(drk: &DrkPtr, output: &mut Vec<String>) {
  897. let lock = drk.read().await;
  898. let coins = match lock.get_coins(true).await {
  899. Ok(c) => c,
  900. Err(e) => {
  901. output.push(format!("Failed to fetch coins: {e}"));
  902. return
  903. }
  904. };
  905. if coins.is_empty() {
  906. return
  907. }
  908. let aliases_map = match lock.get_aliases_mapped_by_token().await {
  909. Ok(m) => m,
  910. Err(e) => {
  911. output.push(format!("Failed to fetch aliases map: {e}"));
  912. return
  913. }
  914. };
  915. let table = prettytable_coins(&coins, &aliases_map);
  916. output.push(format!("{table}"));
  917. }
  918. /// Auxiliary function to define the wallet mining config subcommand handling.
  919. async fn handle_wallet_mining_config(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  920. // Check correct command structure
  921. if parts.len() < 3 || parts.len() > 5 {
  922. output.push(String::from("Malformed `wallet mining-address` subcommand"));
  923. output.push(String::from("Usage: wallet mining-config <index> [spend_hook] [user_data]"));
  924. return
  925. }
  926. // Parse command
  927. let mut index = 2;
  928. let wallet_index = match usize::from_str(parts[index]) {
  929. Ok(i) => i,
  930. Err(e) => {
  931. output.push(format!("Invalid address id: {e}"));
  932. return
  933. }
  934. };
  935. index += 1;
  936. let spend_hook = if index < parts.len() {
  937. match FuncId::from_str(parts[index]) {
  938. Ok(s) => Some(s),
  939. Err(e) => {
  940. output.push(format!("Invalid spend hook: {e}"));
  941. return
  942. }
  943. }
  944. } else {
  945. None
  946. };
  947. index += 1;
  948. let user_data = if index < parts.len() {
  949. let bytes = match bs58::decode(&parts[index]).into_vec() {
  950. Ok(b) => b,
  951. Err(e) => {
  952. output.push(format!("Invalid user data: {e}"));
  953. return
  954. }
  955. };
  956. let bytes: [u8; 32] = match bytes.try_into() {
  957. Ok(b) => b,
  958. Err(e) => {
  959. output.push(format!("Invalid user data: {e:?}"));
  960. return
  961. }
  962. };
  963. let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
  964. Some(v) => v,
  965. None => {
  966. output.push(String::from("Invalid user data"));
  967. return
  968. }
  969. };
  970. Some(elem)
  971. } else {
  972. None
  973. };
  974. if let Err(e) =
  975. drk.read().await.mining_config(wallet_index, spend_hook, user_data, output).await
  976. {
  977. output.push(format!("Failed to generate wallet mining configuration: {e}"));
  978. }
  979. }
  980. /// Auxiliary function to define the spend command handling.
  981. async fn handle_spend(drk: &DrkPtr, input: &[String], output: &mut Vec<String>) {
  982. let tx = match parse_tx_from_input(input).await {
  983. Ok(t) => t,
  984. Err(e) => {
  985. output.push(format!("Error while parsing transaction: {e}"));
  986. return
  987. }
  988. };
  989. if let Err(e) = drk.read().await.mark_tx_spend(&tx, output).await {
  990. output.push(format!("Failed to mark transaction coins as spent: {e}"))
  991. }
  992. }
  993. /// Auxiliary function to define the unspend command handling.
  994. async fn handle_unspend(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  995. // Check correct command structure
  996. if parts.len() != 2 {
  997. output.push(String::from("Malformed `unspend` command"));
  998. output.push(String::from("Usage: unspend <coin>"));
  999. return
  1000. }
  1001. let bytes = match bs58::decode(&parts[1]).into_vec() {
  1002. Ok(b) => b,
  1003. Err(e) => {
  1004. output.push(format!("Invalid coin: {e}"));
  1005. return
  1006. }
  1007. };
  1008. let bytes: [u8; 32] = match bytes.try_into() {
  1009. Ok(b) => b,
  1010. Err(e) => {
  1011. output.push(format!("Invalid coin: {e:?}"));
  1012. return
  1013. }
  1014. };
  1015. let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
  1016. Some(v) => v,
  1017. None => {
  1018. output.push(String::from("Invalid coin"));
  1019. return
  1020. }
  1021. };
  1022. if let Err(e) = drk.read().await.unspend_coin(&Coin::from(elem)).await {
  1023. output.push(format!("Failed to mark coin as unspent: {e}"))
  1024. }
  1025. }
  1026. /// Auxiliary function to define the transfer command handling.
  1027. async fn handle_transfer(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1028. // Check correct command structure
  1029. if parts.len() < 4 || parts.len() > 7 {
  1030. output.push(String::from("Malformed `transfer` command"));
  1031. output.push(String::from(
  1032. "Usage: transfer [--half-split] <amount> <token> <recipient> [spend_hook] [user_data]",
  1033. ));
  1034. return
  1035. }
  1036. // Parse command
  1037. let mut index = 1;
  1038. let mut half_split = false;
  1039. if parts[index] == "--half-split" {
  1040. half_split = true;
  1041. index += 1;
  1042. }
  1043. let amount = String::from(parts[index]);
  1044. if let Err(e) = f64::from_str(&amount) {
  1045. output.push(format!("Invalid amount: {e}"));
  1046. return
  1047. }
  1048. index += 1;
  1049. let lock = drk.read().await;
  1050. let token_id = match lock.get_token(String::from(parts[index])).await {
  1051. Ok(t) => t,
  1052. Err(e) => {
  1053. output.push(format!("Invalid token ID: {e}"));
  1054. return
  1055. }
  1056. };
  1057. index += 1;
  1058. let rcpt = match Address::from_str(parts[index]) {
  1059. Ok(r) => r,
  1060. Err(e) => {
  1061. output.push(format!("Invalid recipient: {e}"));
  1062. return
  1063. }
  1064. };
  1065. if rcpt.network() != lock.network {
  1066. output.push("Mismatched recipient address prefix".to_string());
  1067. return
  1068. }
  1069. index += 1;
  1070. let spend_hook = if index < parts.len() {
  1071. match FuncId::from_str(parts[index]) {
  1072. Ok(s) => Some(s),
  1073. Err(e) => {
  1074. output.push(format!("Invalid spend hook: {e}"));
  1075. return
  1076. }
  1077. }
  1078. } else {
  1079. None
  1080. };
  1081. index += 1;
  1082. let user_data = if index < parts.len() {
  1083. let bytes = match bs58::decode(&parts[index]).into_vec() {
  1084. Ok(b) => b,
  1085. Err(e) => {
  1086. output.push(format!("Invalid user data: {e}"));
  1087. return
  1088. }
  1089. };
  1090. let bytes: [u8; 32] = match bytes.try_into() {
  1091. Ok(b) => b,
  1092. Err(e) => {
  1093. output.push(format!("Invalid user data: {e:?}"));
  1094. return
  1095. }
  1096. };
  1097. let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
  1098. Some(v) => v,
  1099. None => {
  1100. output.push(String::from("Invalid user data"));
  1101. return
  1102. }
  1103. };
  1104. Some(elem)
  1105. } else {
  1106. None
  1107. };
  1108. match lock
  1109. .transfer(&amount, token_id, *rcpt.public_key(), spend_hook, user_data, half_split)
  1110. .await
  1111. {
  1112. Ok(t) => output.push(base64::encode(&serialize_async(&t).await)),
  1113. Err(e) => output.push(format!("Failed to create payment transaction: {e}")),
  1114. }
  1115. }
  1116. /// Auxiliary function to define the otc command handling.
  1117. async fn handle_otc(drk: &DrkPtr, parts: &[&str], input: &[String], output: &mut Vec<String>) {
  1118. // Check correct command structure
  1119. if parts.len() < 2 {
  1120. output.push(String::from("Malformed `otc` command"));
  1121. output.push(String::from("Usage: otc (init|join|inspect|sign)"));
  1122. return
  1123. }
  1124. // Handle subcommand
  1125. match parts[1] {
  1126. "init" => handle_otc_init(drk, parts, output).await,
  1127. "join" => handle_otc_join(drk, parts, input, output).await,
  1128. "inspect" => handle_otc_inspect(drk, parts, input, output).await,
  1129. "sign" => handle_otc_sign(drk, parts, input, output).await,
  1130. _ => {
  1131. output.push(format!("Unrecognized OTC subcommand: {}", parts[1]));
  1132. output.push(String::from("Usage: otc (init|join|inspect|sign)"));
  1133. }
  1134. }
  1135. }
  1136. /// Auxiliary function to define the otc init subcommand handling.
  1137. async fn handle_otc_init(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1138. // Check correct subcommand structure
  1139. if parts.len() != 4 {
  1140. output.push(String::from("Malformed `otc init` subcommand"));
  1141. output.push(String::from("Usage: otc init <value_pair> <token_pair>"));
  1142. return
  1143. }
  1144. let value_pair = match parse_value_pair(parts[2]) {
  1145. Ok(v) => v,
  1146. Err(e) => {
  1147. output.push(format!("Invalid value pair: {e}"));
  1148. return
  1149. }
  1150. };
  1151. let lock = drk.read().await;
  1152. let token_pair = match parse_token_pair(&lock, parts[3]).await {
  1153. Ok(t) => t,
  1154. Err(e) => {
  1155. output.push(format!("Invalid token pair: {e}"));
  1156. return
  1157. }
  1158. };
  1159. match lock.init_swap(value_pair, token_pair, None, None, None).await {
  1160. Ok(half) => output.push(base64::encode(&serialize_async(&half).await)),
  1161. Err(e) => output.push(format!("Failed to create swap transaction half: {e}")),
  1162. }
  1163. }
  1164. /// Auxiliary function to define the otc join subcommand handling.
  1165. async fn handle_otc_join(drk: &DrkPtr, parts: &[&str], input: &[String], output: &mut Vec<String>) {
  1166. // Check correct subcommand structure
  1167. if parts.len() != 2 {
  1168. output.push(String::from("Malformed `otc join` subcommand"));
  1169. output.push(String::from("Usage: otc join"));
  1170. return
  1171. }
  1172. // Parse line from input or fallback to stdin if its empty
  1173. let buf = match input.len() {
  1174. 0 => {
  1175. let mut buf = String::new();
  1176. if let Err(e) = stdin().read_to_string(&mut buf) {
  1177. output.push(format!("Failed to read from stdin: {e}"));
  1178. return
  1179. };
  1180. buf
  1181. }
  1182. 1 => input[0].clone(),
  1183. _ => {
  1184. output.push(String::from("Multiline input provided"));
  1185. return
  1186. }
  1187. };
  1188. let Some(bytes) = base64::decode(buf.trim()) else {
  1189. output.push(String::from("Failed to decode partial swap data"));
  1190. return
  1191. };
  1192. let partial: PartialSwapData = match deserialize_async(&bytes).await {
  1193. Ok(p) => p,
  1194. Err(e) => {
  1195. output.push(format!("Failed to deserialize partial swap data: {e}"));
  1196. return
  1197. }
  1198. };
  1199. match drk.read().await.join_swap(partial, None, None, None).await {
  1200. Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
  1201. Err(e) => output.push(format!("Failed to create a join swap transaction: {e}")),
  1202. }
  1203. }
  1204. /// Auxiliary function to define the otc inspect subcommand handling.
  1205. async fn handle_otc_inspect(
  1206. drk: &DrkPtr,
  1207. parts: &[&str],
  1208. input: &[String],
  1209. output: &mut Vec<String>,
  1210. ) {
  1211. // Check correct subcommand structure
  1212. if parts.len() != 2 {
  1213. output.push(String::from("Malformed `otc inspect` subcommand"));
  1214. output.push(String::from("Usage: otc inspect"));
  1215. return
  1216. }
  1217. // Parse line from input or fallback to stdin if its empty
  1218. let buf = match input.len() {
  1219. 0 => {
  1220. let mut buf = String::new();
  1221. if let Err(e) = stdin().read_to_string(&mut buf) {
  1222. output.push(format!("Failed to read from stdin: {e}"));
  1223. return
  1224. };
  1225. buf
  1226. }
  1227. 1 => input[0].clone(),
  1228. _ => {
  1229. output.push(String::from("Multiline input provided"));
  1230. return
  1231. }
  1232. };
  1233. let Some(bytes) = base64::decode(buf.trim()) else {
  1234. output.push(String::from("Failed to decode swap transaction"));
  1235. return
  1236. };
  1237. if let Err(e) = drk.read().await.inspect_swap(bytes, output).await {
  1238. output.push(format!("Failed to inspect swap: {e}"));
  1239. }
  1240. }
  1241. /// Auxiliary function to define the otc sign subcommand handling.
  1242. async fn handle_otc_sign(drk: &DrkPtr, parts: &[&str], input: &[String], output: &mut Vec<String>) {
  1243. // Check correct subcommand structure
  1244. if parts.len() != 2 {
  1245. output.push(String::from("Malformed `otc sign` subcommand"));
  1246. output.push(String::from("Usage: otc sign"));
  1247. return
  1248. }
  1249. let mut tx = match parse_tx_from_input(input).await {
  1250. Ok(t) => t,
  1251. Err(e) => {
  1252. output.push(format!("Error while parsing transaction: {e}"));
  1253. return
  1254. }
  1255. };
  1256. match drk.read().await.sign_swap(&mut tx).await {
  1257. Ok(_) => output.push(base64::encode(&serialize_async(&tx).await)),
  1258. Err(e) => output.push(format!("Failed to sign joined swap transaction: {e}")),
  1259. }
  1260. }
  1261. /// Auxiliary function to define the dao command handling.
  1262. async fn handle_dao(drk: &DrkPtr, parts: &[&str], input: &[String], output: &mut Vec<String>) {
  1263. // Check correct command structure
  1264. if parts.len() < 2 {
  1265. output.push(String::from("Malformed `dao` command"));
  1266. output.push(String::from("Usage: dao (create|view|import|list|balance|mint|propose-transfer|propose-generic|proposals|proposal|proposal-import|vote|exec|spend-hook|mining-config)"));
  1267. return
  1268. }
  1269. // Handle subcommand
  1270. match parts[1] {
  1271. "create" => handle_dao_create(drk, parts, output).await,
  1272. "view" => handle_dao_view(parts, input, output).await,
  1273. "import" => handle_dao_import(drk, parts, input, output).await,
  1274. "list" => handle_dao_list(drk, parts, output).await,
  1275. "balance" => handle_dao_balance(drk, parts, output).await,
  1276. "mint" => handle_dao_mint(drk, parts, output).await,
  1277. "propose-transfer" => handle_dao_propose_transfer(drk, parts, output).await,
  1278. "propose-generic" => handle_dao_propose_generic(drk, parts, output).await,
  1279. "proposals" => handle_dao_proposals(drk, parts, output).await,
  1280. "proposal" => handle_dao_proposal(drk, parts, output).await,
  1281. "proposal-import" => handle_dao_proposal_import(drk, parts, input, output).await,
  1282. "vote" => handle_dao_vote(drk, parts, output).await,
  1283. "exec" => handle_dao_exec(drk, parts, output).await,
  1284. "spend-hook" => handle_dao_spend_hook(parts, output).await,
  1285. "mining-config" => handle_dao_mining_config(drk, parts, output).await,
  1286. _ => {
  1287. output.push(format!("Unrecognized DAO subcommand: {}", parts[1]));
  1288. output.push(String::from("Usage: dao (create|view|import|list|balance|mint|propose-transfer|propose-generic|proposals|proposal|proposal-import|vote|exec|spend-hook|mining-config)"));
  1289. }
  1290. }
  1291. }
  1292. /// Auxiliary function to define the dao create subcommand handling.
  1293. async fn handle_dao_create(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1294. // Check correct subcommand structure
  1295. if parts.len() != 7 {
  1296. output.push(String::from("Malformed `dao create` subcommand"));
  1297. output.push(String::from("Usage: dao create <proposer-limit> <quorum> <early-exec-quorum> <approval-ratio> <gov-token-id>"));
  1298. return
  1299. }
  1300. if let Err(e) = f64::from_str(parts[2]) {
  1301. output.push(format!("Invalid proposer limit: {e}"));
  1302. return
  1303. }
  1304. let proposer_limit = match decode_base10(parts[2], BALANCE_BASE10_DECIMALS, true) {
  1305. Ok(p) => p,
  1306. Err(e) => {
  1307. output.push(format!("Error while parsing proposer limit: {e}"));
  1308. return
  1309. }
  1310. };
  1311. if let Err(e) = f64::from_str(parts[3]) {
  1312. output.push(format!("Invalid quorum: {e}"));
  1313. return
  1314. }
  1315. let quorum = match decode_base10(parts[3], BALANCE_BASE10_DECIMALS, true) {
  1316. Ok(q) => q,
  1317. Err(e) => {
  1318. output.push(format!("Error while parsing quorum: {e}"));
  1319. return
  1320. }
  1321. };
  1322. if let Err(e) = f64::from_str(parts[4]) {
  1323. output.push(format!("Invalid early exec quorum: {e}"));
  1324. return
  1325. }
  1326. let early_exec_quorum = match decode_base10(parts[4], BALANCE_BASE10_DECIMALS, true) {
  1327. Ok(e) => e,
  1328. Err(e) => {
  1329. output.push(format!("Error while parsing early exec quorum: {e}"));
  1330. return
  1331. }
  1332. };
  1333. let approval_ratio = match f64::from_str(parts[5]) {
  1334. Ok(a) => {
  1335. if a > 1.0 {
  1336. output.push(String::from("Error: Approval ratio cannot be >1.0"));
  1337. return
  1338. }
  1339. a
  1340. }
  1341. Err(e) => {
  1342. output.push(format!("Invalid approval ratio: {e}"));
  1343. return
  1344. }
  1345. };
  1346. let approval_ratio_base = 100_u64;
  1347. let approval_ratio_quot = (approval_ratio * approval_ratio_base as f64) as u64;
  1348. let gov_token_id = match drk.read().await.get_token(String::from(parts[6])).await {
  1349. Ok(g) => g,
  1350. Err(e) => {
  1351. output.push(format!("Invalid Token ID: {e}"));
  1352. return
  1353. }
  1354. };
  1355. let notes_keypair = Keypair::random(&mut OsRng);
  1356. let proposer_keypair = Keypair::random(&mut OsRng);
  1357. let proposals_keypair = Keypair::random(&mut OsRng);
  1358. let votes_keypair = Keypair::random(&mut OsRng);
  1359. let exec_keypair = Keypair::random(&mut OsRng);
  1360. let early_exec_keypair = Keypair::random(&mut OsRng);
  1361. let bulla_blind = BaseBlind::random(&mut OsRng);
  1362. let params = DaoParams::new(
  1363. proposer_limit,
  1364. quorum,
  1365. early_exec_quorum,
  1366. approval_ratio_base,
  1367. approval_ratio_quot,
  1368. gov_token_id,
  1369. Some(notes_keypair.secret),
  1370. notes_keypair.public,
  1371. Some(proposer_keypair.secret),
  1372. proposer_keypair.public,
  1373. Some(proposals_keypair.secret),
  1374. proposals_keypair.public,
  1375. Some(votes_keypair.secret),
  1376. votes_keypair.public,
  1377. Some(exec_keypair.secret),
  1378. exec_keypair.public,
  1379. Some(early_exec_keypair.secret),
  1380. early_exec_keypair.public,
  1381. bulla_blind,
  1382. );
  1383. output.push(params.toml_str());
  1384. }
  1385. /// Auxiliary function to define the dao view subcommand handling.
  1386. async fn handle_dao_view(parts: &[&str], input: &[String], output: &mut Vec<String>) {
  1387. // Check correct subcommand structure
  1388. if parts.len() != 2 {
  1389. output.push(String::from("Malformed `dao view` subcommand"));
  1390. output.push(String::from("Usage: dao view"));
  1391. return
  1392. }
  1393. // Parse lines from input or fallback to stdin if its empty
  1394. let buf = match input.len() {
  1395. 0 => {
  1396. let mut buf = String::new();
  1397. if let Err(e) = stdin().read_to_string(&mut buf) {
  1398. output.push(format!("Failed to read from stdin: {e}"));
  1399. return
  1400. };
  1401. buf
  1402. }
  1403. _ => input.join("\n"),
  1404. };
  1405. let params = match DaoParams::from_toml_str(&buf) {
  1406. Ok(p) => p,
  1407. Err(e) => {
  1408. output.push(format!("Error while parsing DAO params: {e}"));
  1409. return
  1410. }
  1411. };
  1412. output.push(format!("{params}"));
  1413. }
  1414. /// Auxiliary function to define the dao import subcommand handling.
  1415. async fn handle_dao_import(
  1416. drk: &DrkPtr,
  1417. parts: &[&str],
  1418. input: &[String],
  1419. output: &mut Vec<String>,
  1420. ) {
  1421. // Check correct subcommand structure
  1422. if parts.len() != 3 {
  1423. output.push(String::from("Malformed `dao import` subcommand"));
  1424. output.push(String::from("Usage: dao import <name>"));
  1425. return
  1426. }
  1427. // Parse lines from input or fallback to stdin if its empty
  1428. let buf = match input.len() {
  1429. 0 => {
  1430. let mut buf = String::new();
  1431. if let Err(e) = stdin().read_to_string(&mut buf) {
  1432. output.push(format!("Failed to read from stdin: {e}"));
  1433. return
  1434. };
  1435. buf
  1436. }
  1437. _ => input.join("\n"),
  1438. };
  1439. let params = match DaoParams::from_toml_str(&buf) {
  1440. Ok(p) => p,
  1441. Err(e) => {
  1442. output.push(format!("Error while parsing DAO params: {e}"));
  1443. return
  1444. }
  1445. };
  1446. if let Err(e) = drk.read().await.import_dao(parts[2], &params, output).await {
  1447. output.push(format!("Failed to import DAO: {e}"))
  1448. }
  1449. }
  1450. /// Auxiliary function to define the dao list subcommand handling.
  1451. async fn handle_dao_list(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1452. // Check correct subcommand structure
  1453. if parts.len() != 2 && parts.len() != 3 {
  1454. output.push(String::from("Malformed `dao list` subcommand"));
  1455. output.push(String::from("Usage: dao list [name]"));
  1456. return
  1457. }
  1458. let name = if parts.len() == 3 { Some(String::from(parts[2])) } else { None };
  1459. if let Err(e) = drk.read().await.dao_list(&name, output).await {
  1460. output.push(format!("Failed to list DAO: {e}"))
  1461. }
  1462. }
  1463. /// Auxiliary function to define the dao balance subcommand handling.
  1464. async fn handle_dao_balance(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1465. // Check correct subcommand structure
  1466. if parts.len() != 3 {
  1467. output.push(String::from("Malformed `dao balance` subcommand"));
  1468. output.push(String::from("Usage: dao balance <name>"));
  1469. return
  1470. }
  1471. let lock = drk.read().await;
  1472. let balmap = match lock.dao_balance(parts[2]).await {
  1473. Ok(b) => b,
  1474. Err(e) => {
  1475. output.push(format!("Failed to fetch DAO balance: {e}"));
  1476. return
  1477. }
  1478. };
  1479. let alimap = match lock.get_aliases_mapped_by_token().await {
  1480. Ok(m) => m,
  1481. Err(e) => {
  1482. output.push(format!("Failed to fetch aliases map: {e}"));
  1483. return
  1484. }
  1485. };
  1486. let table = prettytable_balance(&balmap, &alimap);
  1487. if table.is_empty() {
  1488. output.push(String::from("No unspent balances found"))
  1489. } else {
  1490. output.push(format!("{table}"));
  1491. }
  1492. }
  1493. /// Auxiliary function to define the dao mint subcommand handling.
  1494. async fn handle_dao_mint(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1495. // Check correct subcommand structure
  1496. if parts.len() != 3 {
  1497. output.push(String::from("Malformed `dao mint` subcommand"));
  1498. output.push(String::from("Usage: dao mint <name>"));
  1499. return
  1500. }
  1501. match drk.read().await.dao_mint(parts[2]).await {
  1502. Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
  1503. Err(e) => output.push(format!("Failed to mint DAO: {e}")),
  1504. }
  1505. }
  1506. /// Auxiliary function to define the dao propose transfer subcommand handling.
  1507. async fn handle_dao_propose_transfer(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1508. // Check correct subcommand structure
  1509. if parts.len() < 7 || parts.len() > 9 {
  1510. output.push(String::from("Malformed `dao proposal-transfer` subcommand"));
  1511. output.push(String::from("Usage: dao proposal-transfer <name> <duration> <amount> <token> <recipient> [spend-hook] [user-data]"));
  1512. return
  1513. }
  1514. let duration = match u64::from_str(parts[3]) {
  1515. Ok(d) => d,
  1516. Err(e) => {
  1517. output.push(format!("Invalid duration: {e}"));
  1518. return
  1519. }
  1520. };
  1521. let amount = String::from(parts[4]);
  1522. if let Err(e) = f64::from_str(&amount) {
  1523. output.push(format!("Invalid amount: {e}"));
  1524. return
  1525. }
  1526. let lock = drk.read().await;
  1527. let token_id = match lock.get_token(String::from(parts[5])).await {
  1528. Ok(t) => t,
  1529. Err(e) => {
  1530. output.push(format!("Invalid token ID: {e}"));
  1531. return
  1532. }
  1533. };
  1534. let rcpt = match Address::from_str(parts[6]) {
  1535. Ok(r) => r,
  1536. Err(e) => {
  1537. output.push(format!("Invalid recipient: {e}"));
  1538. return
  1539. }
  1540. };
  1541. if rcpt.network() != lock.network {
  1542. output.push("Recipient address prefix mismatch".to_string());
  1543. return
  1544. }
  1545. let mut index = 7;
  1546. let spend_hook = if index < parts.len() {
  1547. match FuncId::from_str(parts[index]) {
  1548. Ok(s) => Some(s),
  1549. Err(e) => {
  1550. output.push(format!("Invalid spend hook: {e}"));
  1551. return
  1552. }
  1553. }
  1554. } else {
  1555. None
  1556. };
  1557. index += 1;
  1558. let user_data = if index < parts.len() {
  1559. let bytes = match bs58::decode(&parts[index]).into_vec() {
  1560. Ok(b) => b,
  1561. Err(e) => {
  1562. output.push(format!("Invalid user data: {e}"));
  1563. return
  1564. }
  1565. };
  1566. let bytes: [u8; 32] = match bytes.try_into() {
  1567. Ok(b) => b,
  1568. Err(e) => {
  1569. output.push(format!("Invalid user data: {e:?}"));
  1570. return
  1571. }
  1572. };
  1573. let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
  1574. Some(v) => v,
  1575. None => {
  1576. output.push(String::from("Invalid user data"));
  1577. return
  1578. }
  1579. };
  1580. Some(elem)
  1581. } else {
  1582. None
  1583. };
  1584. match drk
  1585. .read()
  1586. .await
  1587. .dao_propose_transfer(
  1588. parts[2],
  1589. duration,
  1590. &amount,
  1591. token_id,
  1592. *rcpt.public_key(),
  1593. spend_hook,
  1594. user_data,
  1595. )
  1596. .await
  1597. {
  1598. Ok(proposal) => output.push(format!("Generated proposal: {}", proposal.bulla())),
  1599. Err(e) => output.push(format!("Failed to create DAO transfer proposal: {e}")),
  1600. }
  1601. }
  1602. /// Auxiliary function to define the dao propose generic subcommand handling.
  1603. async fn handle_dao_propose_generic(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1604. // Check correct subcommand structure
  1605. if parts.len() != 4 && parts.len() != 5 {
  1606. output.push(String::from("Malformed `dao proposal-generic` subcommand"));
  1607. output.push(String::from("Usage: dao proposal-generic <name> <duration> [user-data]"));
  1608. return
  1609. }
  1610. let duration = match u64::from_str(parts[3]) {
  1611. Ok(d) => d,
  1612. Err(e) => {
  1613. output.push(format!("Invalid duration: {e}"));
  1614. return
  1615. }
  1616. };
  1617. let user_data = if parts.len() == 5 {
  1618. let bytes = match bs58::decode(&parts[4]).into_vec() {
  1619. Ok(b) => b,
  1620. Err(e) => {
  1621. output.push(format!("Invalid user data: {e}"));
  1622. return
  1623. }
  1624. };
  1625. let bytes: [u8; 32] = match bytes.try_into() {
  1626. Ok(b) => b,
  1627. Err(e) => {
  1628. output.push(format!("Invalid user data: {e:?}"));
  1629. return
  1630. }
  1631. };
  1632. let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
  1633. Some(v) => v,
  1634. None => {
  1635. output.push(String::from("Invalid user data"));
  1636. return
  1637. }
  1638. };
  1639. Some(elem)
  1640. } else {
  1641. None
  1642. };
  1643. match drk.read().await.dao_propose_generic(parts[2], duration, user_data).await {
  1644. Ok(proposal) => output.push(format!("Generated proposal: {}", proposal.bulla())),
  1645. Err(e) => output.push(format!("Failed to create DAO generic proposal: {e}")),
  1646. }
  1647. }
  1648. /// Auxiliary function to define the dao proposals subcommand handling.
  1649. async fn handle_dao_proposals(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1650. // Check correct subcommand structure
  1651. if parts.len() != 3 {
  1652. output.push(String::from("Malformed `dao proposals` subcommand"));
  1653. output.push(String::from("Usage: dao proposals <name>"));
  1654. return
  1655. }
  1656. match drk.read().await.get_dao_proposals(parts[2]).await {
  1657. Ok(proposals) => {
  1658. for (i, proposal) in proposals.iter().enumerate() {
  1659. output.push(format!("{i}. {}", proposal.bulla()));
  1660. }
  1661. }
  1662. Err(e) => output.push(format!("Failed to retrieve DAO proposals: {e}")),
  1663. }
  1664. }
  1665. /// Auxiliary function to define the dao proposal subcommand handling.
  1666. async fn handle_dao_proposal(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1667. // Check correct subcommand structure
  1668. if parts.len() != 3 && parts.len() != 4 {
  1669. output.push(String::from("Malformed `dao proposal` subcommand"));
  1670. output.push(String::from("Usage: dao proposal [--(export|mint-proposal)] <bulla>"));
  1671. return
  1672. }
  1673. let mut index = 2;
  1674. let (export, mint_proposal) = if parts.len() == 4 {
  1675. let flags = match parts[index] {
  1676. "--export" => (true, false),
  1677. "--mint-proposal" => (false, true),
  1678. _ => {
  1679. output.push(String::from("Malformed `dao proposal` subcommand"));
  1680. output.push(String::from("Usage: dao proposal [--(export|mint-proposal)] <bulla>"));
  1681. return
  1682. }
  1683. };
  1684. index += 1;
  1685. flags
  1686. } else {
  1687. (false, false)
  1688. };
  1689. let bulla = match DaoProposalBulla::from_str(parts[index]) {
  1690. Ok(b) => b,
  1691. Err(e) => {
  1692. output.push(format!("Invalid proposal bulla: {e}"));
  1693. return
  1694. }
  1695. };
  1696. let lock = drk.read().await;
  1697. let proposal = match lock.get_dao_proposal_by_bulla(&bulla).await {
  1698. Ok(p) => p,
  1699. Err(e) => {
  1700. output.push(format!("Failed to fetch DAO proposal: {e}"));
  1701. return
  1702. }
  1703. };
  1704. if export {
  1705. // Retrieve the DAO
  1706. let dao = match lock.get_dao_by_bulla(&proposal.proposal.dao_bulla).await {
  1707. Ok(d) => d,
  1708. Err(e) => {
  1709. output.push(format!("Failed to fetch DAO: {e}"));
  1710. return
  1711. }
  1712. };
  1713. // Encypt the proposal
  1714. let enc_note =
  1715. AeadEncryptedNote::encrypt(&proposal, &dao.params.dao.proposals_public_key, &mut OsRng)
  1716. .unwrap();
  1717. // Export it to base64
  1718. output.push(base64::encode(&serialize_async(&enc_note).await));
  1719. return
  1720. }
  1721. if mint_proposal {
  1722. // Identify proposal type by its auth calls
  1723. for call in &proposal.proposal.auth_calls {
  1724. // We only support transfer right now
  1725. if call.function_code == DaoFunction::AuthMoneyTransfer as u8 {
  1726. match lock.dao_transfer_proposal_tx(&proposal).await {
  1727. Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
  1728. Err(e) => output.push(format!("Failed to create DAO transfer proposal: {e}")),
  1729. }
  1730. return
  1731. }
  1732. }
  1733. // If proposal has no auth calls, we consider it a generic one
  1734. if proposal.proposal.auth_calls.is_empty() {
  1735. match lock.dao_generic_proposal_tx(&proposal).await {
  1736. Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
  1737. Err(e) => output.push(format!("Failed to create DAO generic proposal: {e}")),
  1738. }
  1739. return
  1740. }
  1741. output.push(String::from("Unsuported DAO proposal"));
  1742. return
  1743. }
  1744. output.push(format!("{proposal}"));
  1745. let mut contract_calls = "\nInvoked contracts:\n".to_string();
  1746. for call in proposal.proposal.auth_calls {
  1747. contract_calls.push_str(&format!(
  1748. "\tContract: {}\n\tFunction: {}\n\tData: ",
  1749. call.contract_id, call.function_code
  1750. ));
  1751. if call.auth_data.is_empty() {
  1752. contract_calls.push_str("-\n");
  1753. continue;
  1754. }
  1755. if call.function_code == DaoFunction::AuthMoneyTransfer as u8 {
  1756. // We know that the plaintext data live in the data plaintext vec
  1757. if proposal.data.is_none() {
  1758. contract_calls.push_str("-\n");
  1759. continue;
  1760. }
  1761. let coin: CoinAttributes = match deserialize_async(proposal.data.as_ref().unwrap())
  1762. .await
  1763. {
  1764. Ok(c) => c,
  1765. Err(e) => {
  1766. output.push(format!("Failed to deserialize transfer proposal coin data: {e}"));
  1767. return
  1768. }
  1769. };
  1770. let recipient: Address =
  1771. StandardAddress::from_public(lock.network, coin.public_key).into();
  1772. let spend_hook = if coin.spend_hook == FuncId::none() {
  1773. "-".to_string()
  1774. } else {
  1775. format!("{}", coin.spend_hook)
  1776. };
  1777. let user_data = if coin.user_data == pallas::Base::ZERO {
  1778. "-".to_string()
  1779. } else {
  1780. format!("{:?}", coin.user_data)
  1781. };
  1782. contract_calls.push_str(&format!(
  1783. "\n\t\t{}: {}\n\t\t{}: {} ({})\n\t\t{}: {}\n\t\t{}: {}\n\t\t{}: {}\n\t\t{}: {}\n\n",
  1784. "Recipient",
  1785. recipient,
  1786. "Amount",
  1787. coin.value,
  1788. encode_base10(coin.value, BALANCE_BASE10_DECIMALS),
  1789. "Token",
  1790. coin.token_id,
  1791. "Spend hook",
  1792. spend_hook,
  1793. "User data",
  1794. user_data,
  1795. "Blind",
  1796. coin.blind
  1797. ));
  1798. }
  1799. }
  1800. output.push(contract_calls);
  1801. let votes = match lock.get_dao_proposal_votes(&bulla).await {
  1802. Ok(v) => v,
  1803. Err(e) => {
  1804. output.push(format!("Failed to fetch DAO proposal votes: {e}"));
  1805. return
  1806. }
  1807. };
  1808. let mut total_yes_vote_value = 0;
  1809. let mut total_no_vote_value = 0;
  1810. let mut total_all_vote_value = 0;
  1811. let mut table = Table::new();
  1812. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  1813. table.set_titles(row!["Transaction", "Tokens", "Vote"]);
  1814. for vote in votes {
  1815. let vote_option = if vote.vote_option {
  1816. total_yes_vote_value += vote.all_vote_value;
  1817. "Yes"
  1818. } else {
  1819. total_no_vote_value += vote.all_vote_value;
  1820. "No"
  1821. };
  1822. total_all_vote_value += vote.all_vote_value;
  1823. table.add_row(row![
  1824. vote.tx_hash,
  1825. encode_base10(vote.all_vote_value, BALANCE_BASE10_DECIMALS),
  1826. vote_option
  1827. ]);
  1828. }
  1829. let outcome = if table.is_empty() {
  1830. output.push(String::from("Votes: No votes found"));
  1831. "Unknown"
  1832. } else {
  1833. output.push(String::from("Votes:"));
  1834. output.push(format!("{table}"));
  1835. output.push(format!(
  1836. "Total tokens votes: {}",
  1837. encode_base10(total_all_vote_value, BALANCE_BASE10_DECIMALS)
  1838. ));
  1839. let approval_ratio = (total_yes_vote_value as f64 * 100.0) / total_all_vote_value as f64;
  1840. output.push(format!(
  1841. "Total tokens Yes votes: {} ({approval_ratio:.2}%)",
  1842. encode_base10(total_yes_vote_value, BALANCE_BASE10_DECIMALS)
  1843. ));
  1844. output.push(format!(
  1845. "Total tokens No votes: {} ({:.2}%)",
  1846. encode_base10(total_no_vote_value, BALANCE_BASE10_DECIMALS),
  1847. (total_no_vote_value as f64 * 100.0) / total_all_vote_value as f64
  1848. ));
  1849. let dao = match lock.get_dao_by_bulla(&proposal.proposal.dao_bulla).await {
  1850. Ok(d) => d,
  1851. Err(e) => {
  1852. output.push(format!("Failed to fetch DAO: {e}"));
  1853. return
  1854. }
  1855. };
  1856. if total_all_vote_value >= dao.params.dao.quorum &&
  1857. approval_ratio >=
  1858. (dao.params.dao.approval_ratio_quot / dao.params.dao.approval_ratio_base)
  1859. as f64
  1860. {
  1861. "Approved"
  1862. } else {
  1863. "Rejected"
  1864. }
  1865. };
  1866. if let Some(exec_tx_hash) = proposal.exec_tx_hash {
  1867. output.push(format!("Proposal was executed on transaction: {exec_tx_hash}"));
  1868. return
  1869. }
  1870. // Retrieve next block height and current block time target,
  1871. // to compute their window.
  1872. let next_block_height = match lock.get_next_block_height().await {
  1873. Ok(n) => n,
  1874. Err(e) => {
  1875. output.push(format!("Failed to fetch next block height: {e}"));
  1876. return
  1877. }
  1878. };
  1879. let block_target = match lock.get_block_target().await {
  1880. Ok(b) => b,
  1881. Err(e) => {
  1882. output.push(format!("Failed to fetch block target: {e}"));
  1883. return
  1884. }
  1885. };
  1886. let current_window = blockwindow(next_block_height, block_target);
  1887. let end_time = proposal.proposal.creation_blockwindow + proposal.proposal.duration_blockwindows;
  1888. let (voting_status, proposal_status_message) = if current_window < end_time {
  1889. ("Ongoing", format!("Current proposal outcome: {outcome}"))
  1890. } else {
  1891. ("Concluded", format!("Proposal outcome: {outcome}"))
  1892. };
  1893. output.push(format!("Voting status: {voting_status}"));
  1894. output.push(proposal_status_message);
  1895. }
  1896. /// Auxiliary function to define the dao proposal import subcommand handling.
  1897. async fn handle_dao_proposal_import(
  1898. drk: &DrkPtr,
  1899. parts: &[&str],
  1900. input: &[String],
  1901. output: &mut Vec<String>,
  1902. ) {
  1903. // Check correct subcommand structure
  1904. if parts.len() != 2 {
  1905. output.push(String::from("Malformed `dao proposal-import` subcommand"));
  1906. output.push(String::from("Usage: dao proposal-import"));
  1907. return
  1908. }
  1909. // Parse line from input or fallback to stdin if its empty
  1910. let buf = match input.len() {
  1911. 0 => {
  1912. let mut buf = String::new();
  1913. if let Err(e) = stdin().read_to_string(&mut buf) {
  1914. output.push(format!("Failed to read from stdin: {e}"));
  1915. return
  1916. };
  1917. buf
  1918. }
  1919. 1 => input[0].clone(),
  1920. _ => {
  1921. output.push(String::from("Multiline input provided"));
  1922. return
  1923. }
  1924. };
  1925. let Some(bytes) = base64::decode(buf.trim()) else {
  1926. output.push(String::from("Failed to decode encrypted proposal data"));
  1927. return
  1928. };
  1929. let encrypted_proposal: AeadEncryptedNote = match deserialize_async(&bytes).await {
  1930. Ok(e) => e,
  1931. Err(e) => {
  1932. output.push(format!("Failed to deserialize encrypted proposal data: {e}"));
  1933. return
  1934. }
  1935. };
  1936. let lock = drk.read().await;
  1937. let daos = match lock.get_daos().await {
  1938. Ok(d) => d,
  1939. Err(e) => {
  1940. output.push(format!("Failed to retrieve DAOs: {e}"));
  1941. return
  1942. }
  1943. };
  1944. for dao in &daos {
  1945. // Check if we have the proposals key
  1946. let Some(proposals_secret_key) = dao.params.proposals_secret_key else { continue };
  1947. // Try to decrypt the proposal
  1948. let Ok(proposal) = encrypted_proposal.decrypt::<ProposalRecord>(&proposals_secret_key)
  1949. else {
  1950. continue
  1951. };
  1952. let proposal = match lock.get_dao_proposal_by_bulla(&proposal.bulla()).await {
  1953. Ok(p) => {
  1954. let mut our_proposal = p;
  1955. our_proposal.data = proposal.data;
  1956. our_proposal
  1957. }
  1958. Err(_) => proposal,
  1959. };
  1960. if let Err(e) = lock.put_dao_proposal(&proposal).await {
  1961. output.push(format!("Failed to put DAO proposal: {e}"));
  1962. }
  1963. return
  1964. }
  1965. output.push(String::from("Couldn't decrypt the proposal with out DAO keys"));
  1966. }
  1967. /// Auxiliary function to define the dao vote subcommand handling.
  1968. async fn handle_dao_vote(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  1969. // Check correct subcommand structure
  1970. if parts.len() != 4 && parts.len() != 5 {
  1971. output.push(String::from("Malformed `dao vote` subcommand"));
  1972. output.push(String::from("Usage: dao vote <bulla> <vote> [vote-weight]"));
  1973. return
  1974. }
  1975. let bulla = match DaoProposalBulla::from_str(parts[2]) {
  1976. Ok(b) => b,
  1977. Err(e) => {
  1978. output.push(format!("Invalid proposal bulla: {e}"));
  1979. return
  1980. }
  1981. };
  1982. let vote = match u8::from_str(parts[3]) {
  1983. Ok(v) => {
  1984. if v > 1 {
  1985. output.push(String::from("Vote can be either 0 (NO) or 1 (YES)"));
  1986. return
  1987. }
  1988. v != 0
  1989. }
  1990. Err(e) => {
  1991. output.push(format!("Invalid vote: {e}"));
  1992. return
  1993. }
  1994. };
  1995. let weight = if parts.len() == 5 {
  1996. if let Err(e) = f64::from_str(parts[4]) {
  1997. output.push(format!("Invalid vote weight: {e}"));
  1998. return
  1999. }
  2000. match decode_base10(parts[4], BALANCE_BASE10_DECIMALS, true) {
  2001. Ok(w) => Some(w),
  2002. Err(e) => {
  2003. output.push(format!("Error while parsing vote weight: {e}"));
  2004. return
  2005. }
  2006. }
  2007. } else {
  2008. None
  2009. };
  2010. match drk.read().await.dao_vote(&bulla, vote, weight).await {
  2011. Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
  2012. Err(e) => output.push(format!("Failed to create DAO Vote transaction: {e}")),
  2013. }
  2014. }
  2015. /// Auxiliary function to define the dao exec subcommand handling.
  2016. async fn handle_dao_exec(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2017. // Check correct subcommand structure
  2018. if parts.len() != 3 && parts.len() != 4 {
  2019. output.push(String::from("Malformed `dao exec` subcommand"));
  2020. output.push(String::from("Usage: dao exec [--early] <bulla>"));
  2021. return
  2022. }
  2023. let mut index = 2;
  2024. let mut early = false;
  2025. if parts[index] == "--early" {
  2026. early = true;
  2027. index += 1;
  2028. }
  2029. let bulla = match DaoProposalBulla::from_str(parts[index]) {
  2030. Ok(b) => b,
  2031. Err(e) => {
  2032. output.push(format!("Invalid proposal bulla: {e}"));
  2033. return
  2034. }
  2035. };
  2036. let lock = drk.read().await;
  2037. let proposal = match lock.get_dao_proposal_by_bulla(&bulla).await {
  2038. Ok(p) => p,
  2039. Err(e) => {
  2040. output.push(format!("Failed to fetch DAO proposal: {e}"));
  2041. return
  2042. }
  2043. };
  2044. // Identify proposal type by its auth calls
  2045. for call in &proposal.proposal.auth_calls {
  2046. // We only support transfer right now
  2047. if call.function_code == DaoFunction::AuthMoneyTransfer as u8 {
  2048. match lock.dao_exec_transfer(&proposal, early).await {
  2049. Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
  2050. Err(e) => output.push(format!("Failed to execute DAO transfer proposal: {e}")),
  2051. };
  2052. return
  2053. }
  2054. }
  2055. // If proposal has no auth calls, we consider it a generic one
  2056. if proposal.proposal.auth_calls.is_empty() {
  2057. match lock.dao_exec_generic(&proposal, early).await {
  2058. Ok(tx) => output.push(base64::encode(&serialize_async(&tx).await)),
  2059. Err(e) => output.push(format!("Failed to execute DAO generic proposal: {e}")),
  2060. };
  2061. return
  2062. }
  2063. output.push(String::from("Unsuported DAO proposal"));
  2064. }
  2065. /// Auxiliary function to define the dao spent hook subcommand handling.
  2066. async fn handle_dao_spend_hook(parts: &[&str], output: &mut Vec<String>) {
  2067. // Check correct subcommand structure
  2068. if parts.len() != 2 {
  2069. output.push(String::from("Malformed `dao spent-hook` subcommand"));
  2070. output.push(String::from("Usage: dao spent-hook"));
  2071. return
  2072. }
  2073. let spend_hook =
  2074. FuncRef { contract_id: *DAO_CONTRACT_ID, func_code: DaoFunction::Exec as u8 }.to_func_id();
  2075. output.push(format!("{spend_hook}"));
  2076. }
  2077. /// Auxiliary function to define the dao mining config subcommand handling.
  2078. async fn handle_dao_mining_config(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2079. // Check correct subcommand structure
  2080. if parts.len() != 3 {
  2081. output.push(String::from("Malformed `dao mining-config` subcommand"));
  2082. output.push(String::from("Usage: dao mining-config <name>"));
  2083. return
  2084. }
  2085. if let Err(e) = drk.read().await.dao_mining_config(parts[2], output).await {
  2086. output.push(format!("Failed to generate DAO mining configuration: {e}"));
  2087. }
  2088. }
  2089. /// Auxiliary function to define the attach fee command handling.
  2090. async fn handle_attach_fee(drk: &DrkPtr, input: &[String], output: &mut Vec<String>) {
  2091. let mut tx = match parse_tx_from_input(input).await {
  2092. Ok(t) => t,
  2093. Err(e) => {
  2094. output.push(format!("Error while parsing transaction: {e}"));
  2095. return
  2096. }
  2097. };
  2098. match drk.read().await.attach_fee(&mut tx).await {
  2099. Ok(_) => output.push(base64::encode(&serialize_async(&tx).await)),
  2100. Err(e) => output.push(format!("Failed to attach the fee call to the transaction: {e}")),
  2101. }
  2102. }
  2103. /// Auxiliary function to define the tx from calls command handling.
  2104. async fn handle_tx_from_calls(parts: &[&str], input: &[String], output: &mut Vec<String>) {
  2105. // Check correct subcommand structure
  2106. if parts.len() != 1 && parts.len() != 2 {
  2107. output.push(String::from("Malformed `tx-from-calls` subcommand"));
  2108. output.push(String::from("Usage: tx-from-calls [calls-map]"));
  2109. return
  2110. }
  2111. // Parse calls
  2112. let calls = match parse_calls_from_input(input).await {
  2113. Ok(c) => c,
  2114. Err(e) => {
  2115. output.push(format!("Error while parsing transaction calls: {e}"));
  2116. return
  2117. }
  2118. };
  2119. if calls.is_empty() {
  2120. output.push(String::from("No calls were parsed"));
  2121. return
  2122. }
  2123. // If there is a given map, parse it, otherwise construct a
  2124. // linear map.
  2125. let calls_map = if parts.len() == 2 {
  2126. match parse_tree(parts[1]) {
  2127. Ok(m) => m,
  2128. Err(e) => {
  2129. output.push(format!("Failed parsing calls map: {e}"));
  2130. return
  2131. }
  2132. }
  2133. } else {
  2134. let mut calls_map = Vec::with_capacity(calls.len());
  2135. for (i, _) in calls.iter().enumerate() {
  2136. calls_map.push((i, vec![]));
  2137. }
  2138. calls_map
  2139. };
  2140. if calls_map.len() != calls.len() {
  2141. output.push(String::from("Calls map size not equal to parsed calls"));
  2142. return
  2143. }
  2144. // Create a transaction from the mapped calls.
  2145. let (mut tx_builder, signature_secrets) = match tx_from_calls_mapped(&calls, &calls_map) {
  2146. Ok(pair) => pair,
  2147. Err(e) => {
  2148. output.push(format!("Failed to create a transaction from the mapped calls: {e}"));
  2149. return
  2150. }
  2151. };
  2152. // Now build and sign the tx
  2153. let mut tx = match tx_builder.build() {
  2154. Ok(tx) => tx,
  2155. Err(e) => {
  2156. output.push(format!("Failed to build the transaction: {e}"));
  2157. return
  2158. }
  2159. };
  2160. let sigs = match tx.create_sigs(&signature_secrets) {
  2161. Ok(s) => s,
  2162. Err(e) => {
  2163. output.push(format!("Failed to create the transaction signatures: {e}"));
  2164. return
  2165. }
  2166. };
  2167. tx.signatures.push(sigs);
  2168. output.push(base64::encode(&serialize_async(&tx).await));
  2169. }
  2170. /// Auxiliary function to define the inspect command handling.
  2171. async fn handle_inspect(input: &[String], output: &mut Vec<String>) {
  2172. match parse_tx_from_input(input).await {
  2173. Ok(tx) => output.push(format!("{tx:#?}")),
  2174. Err(e) => output.push(format!("Error while parsing transaction: {e}")),
  2175. }
  2176. }
  2177. /// Auxiliary function to define the broadcast command handling.
  2178. async fn handle_broadcast(drk: &DrkPtr, input: &[String], output: &mut Vec<String>) {
  2179. let tx = match parse_tx_from_input(input).await {
  2180. Ok(t) => t,
  2181. Err(e) => {
  2182. output.push(format!("Error while parsing transaction: {e}"));
  2183. return
  2184. }
  2185. };
  2186. let lock = drk.read().await;
  2187. if let Err(e) = lock.simulate_tx(&tx).await {
  2188. output.push(format!("Failed to simulate tx: {e}"));
  2189. return
  2190. };
  2191. if let Err(e) = lock.mark_tx_spend(&tx, output).await {
  2192. output.push(format!("Failed to mark transaction coins as spent: {e}"));
  2193. return
  2194. };
  2195. match lock.broadcast_tx(&tx, output).await {
  2196. Ok(txid) => output.push(format!("Transaction ID: {txid}")),
  2197. Err(e) => output.push(format!("Failed to broadcast transaction: {e}")),
  2198. }
  2199. }
  2200. /// Auxiliary function to define the subscribe command handling.
  2201. async fn handle_subscribe(
  2202. drk: &DrkPtr,
  2203. endpoint: &Url,
  2204. subscription_active: &mut bool,
  2205. subscription_tasks: &[StoppableTaskPtr; 2],
  2206. shell_sender: &Sender<Vec<String>>,
  2207. ex: &ExecutorPtr,
  2208. ) {
  2209. // Kill zombie tasks if they failed
  2210. subscription_tasks[0].stop_nowait();
  2211. subscription_tasks[1].stop_nowait();
  2212. *subscription_active = true;
  2213. // Start the subscription task
  2214. let drk_ = drk.clone();
  2215. let rpc_task_ = subscription_tasks[1].clone();
  2216. let shell_sender_ = shell_sender.clone();
  2217. let endpoint_ = endpoint.clone();
  2218. let ex_ = ex.clone();
  2219. subscription_tasks[0].clone().start(
  2220. async move { subscribe_blocks(&drk_, rpc_task_, shell_sender_, endpoint_, &ex_).await },
  2221. |_| async { /* Do nothing */ },
  2222. Error::DetachedTaskStopped,
  2223. ex.clone(),
  2224. );
  2225. }
  2226. /// Auxiliary function to define the unsubscribe command handling.
  2227. async fn handle_unsubscribe(
  2228. subscription_active: &mut bool,
  2229. subscription_tasks: &[StoppableTaskPtr; 2],
  2230. ) {
  2231. subscription_tasks[0].stop_nowait();
  2232. subscription_tasks[1].stop_nowait();
  2233. *subscription_active = false;
  2234. }
  2235. /// Auxiliary function to define the scan command handling.
  2236. async fn handle_scan(
  2237. drk: &DrkPtr,
  2238. subscription_active: &bool,
  2239. parts: &[&str],
  2240. output: &mut Vec<String>,
  2241. print: &bool,
  2242. ) {
  2243. if *subscription_active {
  2244. append_or_print(output, None, print, vec![String::from("Subscription is already active!")])
  2245. .await;
  2246. return
  2247. }
  2248. // Check correct command structure
  2249. if parts.len() != 1 && parts.len() != 3 {
  2250. append_or_print(output, None, print, vec![String::from("Malformed `scan` command")]).await;
  2251. return
  2252. }
  2253. // Check if reset was requested
  2254. let lock = drk.read().await;
  2255. if parts.len() == 3 {
  2256. if parts[1] != "--reset" {
  2257. append_or_print(
  2258. output,
  2259. None,
  2260. print,
  2261. vec![
  2262. String::from("Malformed `scan` command"),
  2263. String::from("Usage: scan --reset <height>"),
  2264. ],
  2265. )
  2266. .await;
  2267. return
  2268. }
  2269. let height = match u32::from_str(parts[2]) {
  2270. Ok(h) => h,
  2271. Err(e) => {
  2272. append_or_print(output, None, print, vec![format!("Invalid reset height: {e}")])
  2273. .await;
  2274. return
  2275. }
  2276. };
  2277. let mut buf = vec![];
  2278. if let Err(e) = lock.reset_to_height(height, &mut buf).await {
  2279. buf.push(format!("Failed during wallet reset: {e}"));
  2280. append_or_print(output, None, print, buf).await;
  2281. return
  2282. }
  2283. append_or_print(output, None, print, buf).await;
  2284. }
  2285. if let Err(e) = lock.scan_blocks(output, None, print).await {
  2286. append_or_print(output, None, print, vec![format!("Failed during scanning: {e}")]).await;
  2287. return
  2288. }
  2289. append_or_print(output, None, print, vec![String::from("Finished scanning blockchain")]).await;
  2290. }
  2291. /// Auxiliary function to define the explorer command handling.
  2292. async fn handle_explorer(drk: &DrkPtr, parts: &[&str], input: &[String], output: &mut Vec<String>) {
  2293. // Check correct command structure
  2294. if parts.len() < 2 {
  2295. output.push(String::from("Malformed `explorer` command"));
  2296. output.push(String::from(
  2297. "Usage: explorer (fetch-tx|simulate-tx|txs-history|clear-reverted|scanned-blocks|mining-config)",
  2298. ));
  2299. return
  2300. }
  2301. // Handle subcommand
  2302. match parts[1] {
  2303. "fetch-tx" => handle_explorer_fetch_tx(drk, parts, output).await,
  2304. "simulate-tx" => handle_explorer_simulate_tx(drk, parts, input, output).await,
  2305. "txs-history" => handle_explorer_txs_history(drk, parts, output).await,
  2306. "clear-reverted" => handle_explorer_clear_reverted(drk, parts, output).await,
  2307. "scanned-blocks" => handle_explorer_scanned_blocks(drk, parts, output).await,
  2308. "mining-config" => handle_explorer_mining_config(parts, input, output).await,
  2309. _ => {
  2310. output.push(format!("Unrecognized explorer subcommand: {}", parts[1]));
  2311. output.push(String::from(
  2312. "Usage: explorer (fetch-tx|simulate-tx|txs-history|clear-reverted|scanned-blocks|mining-config)",
  2313. ));
  2314. }
  2315. }
  2316. }
  2317. /// Auxiliary function to define the explorer fetch transaction subcommand handling.
  2318. async fn handle_explorer_fetch_tx(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2319. // Check correct subcommand structure
  2320. if parts.len() != 3 && parts.len() != 4 {
  2321. output.push(String::from("Malformed `explorer fetch-tx` subcommand"));
  2322. output.push(String::from("Usage: explorer fetch-tx [--encode] <tx-hash>"));
  2323. return
  2324. }
  2325. let mut index = 2;
  2326. let mut encode = false;
  2327. if parts[index] == "--encode" {
  2328. encode = true;
  2329. index += 1;
  2330. }
  2331. let hash = match blake3::Hash::from_hex(parts[index]) {
  2332. Ok(h) => h,
  2333. Err(e) => {
  2334. output.push(format!("Invalid transaction hash: {e}"));
  2335. return
  2336. }
  2337. };
  2338. let tx_hash = TransactionHash(*hash.as_bytes());
  2339. let tx = match drk.read().await.get_tx(&tx_hash).await {
  2340. Ok(tx) => tx,
  2341. Err(e) => {
  2342. output.push(format!("Failed to fetch transaction: {e}"));
  2343. return
  2344. }
  2345. };
  2346. let Some(tx) = tx else {
  2347. output.push(String::from("Transaction was not found"));
  2348. return
  2349. };
  2350. // Make sure the tx is correct
  2351. if tx.hash() != tx_hash {
  2352. output.push(format!("Transaction hash missmatch: {tx_hash} - {}", tx.hash()));
  2353. return
  2354. }
  2355. if encode {
  2356. output.push(base64::encode(&serialize_async(&tx).await));
  2357. return
  2358. }
  2359. output.push(format!("Transaction ID: {tx_hash}"));
  2360. output.push(format!("{tx:?}"));
  2361. }
  2362. /// Auxiliary function to define the explorer simulate transaction subcommand handling.
  2363. async fn handle_explorer_simulate_tx(
  2364. drk: &DrkPtr,
  2365. parts: &[&str],
  2366. input: &[String],
  2367. output: &mut Vec<String>,
  2368. ) {
  2369. // Check correct subcommand structure
  2370. if parts.len() != 2 {
  2371. output.push(String::from("Malformed `explorer simulate-tx` subcommand"));
  2372. output.push(String::from("Usage: explorer simulate-tx"));
  2373. return
  2374. }
  2375. let tx = match parse_tx_from_input(input).await {
  2376. Ok(t) => t,
  2377. Err(e) => {
  2378. output.push(format!("Error while parsing transaction: {e}"));
  2379. return
  2380. }
  2381. };
  2382. match drk.read().await.simulate_tx(&tx).await {
  2383. Ok(is_valid) => {
  2384. output.push(format!("Transaction ID: {}", tx.hash()));
  2385. output.push(format!("State: {}", if is_valid { "valid" } else { "invalid" }));
  2386. }
  2387. Err(e) => output.push(format!("Failed to simulate tx: {e}")),
  2388. }
  2389. }
  2390. /// Auxiliary function to define the explorer transactions history subcommand handling.
  2391. async fn handle_explorer_txs_history(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2392. // Check correct command structure
  2393. if parts.len() < 2 || parts.len() > 4 {
  2394. output.push(String::from("Malformed `explorer txs-history` command"));
  2395. output.push(String::from("Usage: explorer txs-history [--encode] [tx-hash]"));
  2396. return
  2397. }
  2398. let lock = drk.read().await;
  2399. if parts.len() > 2 {
  2400. let mut index = 2;
  2401. let mut encode = false;
  2402. if parts[index] == "--encode" {
  2403. encode = true;
  2404. index += 1;
  2405. }
  2406. let (tx_hash, status, block_height, tx) =
  2407. match lock.get_tx_history_record(parts[index]).await {
  2408. Ok(i) => i,
  2409. Err(e) => {
  2410. output.push(format!("Failed to fetch transaction: {e}"));
  2411. return
  2412. }
  2413. };
  2414. if encode {
  2415. output.push(base64::encode(&serialize_async(&tx).await));
  2416. return
  2417. }
  2418. output.push(format!("Transaction ID: {tx_hash}"));
  2419. output.push(format!("Status: {status}"));
  2420. match block_height {
  2421. Some(block_height) => output.push(format!("Block height: {block_height}")),
  2422. None => output.push(String::from("Block height: -")),
  2423. }
  2424. output.push(format!("{tx:?}"));
  2425. return
  2426. }
  2427. let map = match lock.get_txs_history() {
  2428. Ok(m) => m,
  2429. Err(e) => {
  2430. output.push(format!("Failed to retrieve transactions history records: {e}"));
  2431. return
  2432. }
  2433. };
  2434. // Create a prettytable with the new data:
  2435. let mut table = Table::new();
  2436. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  2437. table.set_titles(row!["Transaction Hash", "Status", "Block Height"]);
  2438. for (txs_hash, status, block_height) in map.iter() {
  2439. let block_height = match block_height {
  2440. Some(block_height) => block_height.to_string(),
  2441. None => String::from("-"),
  2442. };
  2443. table.add_row(row![txs_hash, status, block_height]);
  2444. }
  2445. if table.is_empty() {
  2446. output.push(String::from("No transactions found"));
  2447. } else {
  2448. output.push(format!("{table}"));
  2449. }
  2450. }
  2451. /// Auxiliary function to define the explorer clear reverted subcommand handling.
  2452. async fn handle_explorer_clear_reverted(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2453. // Check correct subcommand structure
  2454. if parts.len() != 2 {
  2455. output.push(String::from("Malformed `explorer clear-reverted` subcommand"));
  2456. output.push(String::from("Usage: explorer clear-reverted"));
  2457. return
  2458. }
  2459. if let Err(e) = drk.read().await.remove_reverted_txs(output) {
  2460. output.push(format!("Failed to remove reverted transactions: {e}"));
  2461. }
  2462. }
  2463. /// Auxiliary function to define the explorer scanned blocks subcommand handling.
  2464. async fn handle_explorer_scanned_blocks(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2465. // Check correct subcommand structure
  2466. if parts.len() != 2 && parts.len() != 3 {
  2467. output.push(String::from("Malformed `explorer scanned-blocks` subcommand"));
  2468. output.push(String::from("Usage: explorer scanned-blocks [height]"));
  2469. return
  2470. }
  2471. let lock = drk.read().await;
  2472. if parts.len() == 3 {
  2473. let height = match u32::from_str(parts[2]) {
  2474. Ok(d) => d,
  2475. Err(e) => {
  2476. output.push(format!("Invalid height: {e}"));
  2477. return
  2478. }
  2479. };
  2480. match lock.get_scanned_block(&height) {
  2481. Ok((hash, signing_key)) => {
  2482. output.push(format!("Height: {height}"));
  2483. output.push(format!("Hash: {hash}"));
  2484. output.push(format!("Signing key: {signing_key}"));
  2485. }
  2486. Err(e) => output.push(format!("Failed to retrieve scanned block record: {e}")),
  2487. };
  2488. return
  2489. }
  2490. let map = match lock.get_scanned_block_records() {
  2491. Ok(m) => m,
  2492. Err(e) => {
  2493. output.push(format!("Failed to retrieve scanned blocks records: {e}"));
  2494. return
  2495. }
  2496. };
  2497. let table = prettytable_scanned_blocks(&map);
  2498. if table.is_empty() {
  2499. output.push(String::from("No scanned blocks records found"));
  2500. } else {
  2501. output.push(format!("{table}"));
  2502. }
  2503. }
  2504. /// Auxiliary function to define the explorer mining config subcommand handling.
  2505. async fn handle_explorer_mining_config(parts: &[&str], input: &[String], output: &mut Vec<String>) {
  2506. // Check correct subcommand structure
  2507. if parts.len() != 2 {
  2508. output.push(String::from("Malformed `explorer mining-config` subcommand"));
  2509. output.push(String::from("Usage: explorer mining-config"));
  2510. return
  2511. }
  2512. let (config, recipient, spend_hook, user_data) =
  2513. match parse_mining_config_from_input(input).await {
  2514. Ok(c) => c,
  2515. Err(e) => {
  2516. output.push(format!("Error while parsing mining config: {e}"));
  2517. return
  2518. }
  2519. };
  2520. display_mining_config(&config, &recipient, &spend_hook, &user_data, output)
  2521. }
  2522. /// Auxiliary function to define the alias command handling.
  2523. async fn handle_alias(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2524. // Check correct command structure
  2525. if parts.len() < 2 {
  2526. output.push(String::from("Malformed `alias` command"));
  2527. output.push(String::from("Usage: alias (add|show|remove)"));
  2528. return
  2529. }
  2530. // Handle subcommand
  2531. match parts[1] {
  2532. "add" => handle_alias_add(drk, parts, output).await,
  2533. "show" => handle_alias_show(drk, parts, output).await,
  2534. "remove" => handle_alias_remove(drk, parts, output).await,
  2535. _ => {
  2536. output.push(format!("Unrecognized alias subcommand: {}", parts[1]));
  2537. output.push(String::from("Usage: alias (add|show|remove)"));
  2538. }
  2539. }
  2540. }
  2541. /// Auxiliary function to define the alias add subcommand handling.
  2542. async fn handle_alias_add(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2543. // Check correct subcommand structure
  2544. if parts.len() != 4 {
  2545. output.push(String::from("Malformed `alias add` subcommand"));
  2546. output.push(String::from("Usage: alias add <alias> <token>"));
  2547. return
  2548. }
  2549. if parts[2].len() > 5 {
  2550. output.push(String::from("Error: Alias exceeds 5 characters"));
  2551. return
  2552. }
  2553. let token_id = match TokenId::from_str(parts[3]) {
  2554. Ok(t) => t,
  2555. Err(e) => {
  2556. output.push(format!("Invalid Token ID: {e}"));
  2557. return
  2558. }
  2559. };
  2560. if let Err(e) = drk.read().await.add_alias(String::from(parts[2]), token_id, output).await {
  2561. output.push(format!("Failed to add alias: {e}"));
  2562. }
  2563. }
  2564. /// Auxiliary function to define the alias show subcommand handling.
  2565. async fn handle_alias_show(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2566. // Check correct command structure
  2567. if parts.len() != 2 && parts.len() != 4 && parts.len() != 6 {
  2568. output.push(String::from("Malformed `alias show` command"));
  2569. output.push(String::from("Usage: alias show [-a, --alias <alias>] [-t, --token <token>]"));
  2570. return
  2571. }
  2572. let mut alias = None;
  2573. let mut token_id = None;
  2574. if parts.len() > 2 {
  2575. let mut index = 2;
  2576. if parts[index] == "-a" || parts[index] == "--alias" {
  2577. alias = Some(String::from(parts[index + 1]));
  2578. index += 2;
  2579. }
  2580. if index < parts.len() && (parts[index] == "-t" || parts[index] == "--token") {
  2581. match TokenId::from_str(parts[index + 1]) {
  2582. Ok(t) => token_id = Some(t),
  2583. Err(e) => {
  2584. output.push(format!("Invalid Token ID: {e}"));
  2585. return
  2586. }
  2587. };
  2588. index += 2;
  2589. }
  2590. // Check alias again in case it was after token
  2591. if index < parts.len() && (parts[index] == "-a" || parts[index] == "--alias") {
  2592. alias = Some(String::from(parts[index + 1]));
  2593. }
  2594. }
  2595. let map = match drk.read().await.get_aliases(alias, token_id).await {
  2596. Ok(m) => m,
  2597. Err(e) => {
  2598. output.push(format!("Failed to fetch aliases map: {e}"));
  2599. return
  2600. }
  2601. };
  2602. let table = prettytable_aliases(&map);
  2603. if table.is_empty() {
  2604. output.push(String::from("No aliases found"));
  2605. } else {
  2606. output.push(format!("{table}"));
  2607. }
  2608. }
  2609. /// Auxiliary function to define the alias remove subcommand handling.
  2610. async fn handle_alias_remove(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2611. // Check correct subcommand structure
  2612. if parts.len() != 3 {
  2613. output.push(String::from("Malformed `alias remove` subcommand"));
  2614. output.push(String::from("Usage: alias remove <alias>"));
  2615. return
  2616. }
  2617. if let Err(e) = drk.read().await.remove_alias(String::from(parts[2]), output).await {
  2618. output.push(format!("Failed to remove alias: {e}"));
  2619. }
  2620. }
  2621. /// Auxiliary function to define the token command handling.
  2622. async fn handle_token(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2623. // Check correct command structure
  2624. if parts.len() < 2 {
  2625. output.push(String::from("Malformed `token` command"));
  2626. output.push(String::from("Usage: token (import|generate-mint|list|mint|freeze)"));
  2627. return
  2628. }
  2629. // Handle subcommand
  2630. match parts[1] {
  2631. "import" => handle_token_import(drk, parts, output).await,
  2632. "generate-mint" => handle_token_generate_mint(drk, parts, output).await,
  2633. "list" => handle_token_list(drk, parts, output).await,
  2634. "mint" => handle_token_mint(drk, parts, output).await,
  2635. "freeze" => handle_token_freeze(drk, parts, output).await,
  2636. _ => {
  2637. output.push(format!("Unrecognized token subcommand: {}", parts[1]));
  2638. output.push(String::from("Usage: token (import|generate-mint|list|mint|freeze)"));
  2639. }
  2640. }
  2641. }
  2642. /// Auxiliary function to define the token import subcommand handling.
  2643. async fn handle_token_import(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2644. // Check correct subcommand structure
  2645. if parts.len() != 4 {
  2646. output.push(String::from("Malformed `token import` subcommand"));
  2647. output.push(String::from("Usage: token import <secret-key> <token-blind>"));
  2648. return
  2649. }
  2650. let mint_authority = match SecretKey::from_str(parts[2]) {
  2651. Ok(ma) => ma,
  2652. Err(e) => {
  2653. output.push(format!("Invalid mint authority: {e}"));
  2654. return
  2655. }
  2656. };
  2657. let token_blind = match BaseBlind::from_str(parts[3]) {
  2658. Ok(tb) => tb,
  2659. Err(e) => {
  2660. output.push(format!("Invalid token blind: {e}"));
  2661. return
  2662. }
  2663. };
  2664. match drk.read().await.import_mint_authority(mint_authority, token_blind).await {
  2665. Ok(token_id) => {
  2666. output.push(format!("Successfully imported mint authority for token ID: {token_id}"))
  2667. }
  2668. Err(e) => output.push(format!("Failed to import mint authority: {e}")),
  2669. }
  2670. }
  2671. /// Auxiliary function to define the token generate mint subcommand handling.
  2672. async fn handle_token_generate_mint(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2673. // Check correct subcommand structure
  2674. if parts.len() != 2 {
  2675. output.push(String::from("Malformed `token generate-mint` subcommand"));
  2676. output.push(String::from("Usage: token generate-mint"));
  2677. return
  2678. }
  2679. let mint_authority = SecretKey::random(&mut OsRng);
  2680. let token_blind = BaseBlind::random(&mut OsRng);
  2681. match drk.read().await.import_mint_authority(mint_authority, token_blind).await {
  2682. Ok(token_id) => {
  2683. output.push(format!("Successfully imported mint authority for token ID: {token_id}"))
  2684. }
  2685. Err(e) => output.push(format!("Failed to import mint authority: {e}")),
  2686. }
  2687. }
  2688. /// Auxiliary function to define the token list subcommand handling.
  2689. async fn handle_token_list(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2690. // Check correct subcommand structure
  2691. if parts.len() != 2 {
  2692. output.push(String::from("Malformed `token list` subcommand"));
  2693. output.push(String::from("Usage: token list"));
  2694. return
  2695. }
  2696. let lock = drk.read().await;
  2697. let tokens = match lock.get_mint_authorities().await {
  2698. Ok(m) => m,
  2699. Err(e) => {
  2700. output.push(format!("Failed to fetch mint authorities: {e}"));
  2701. return
  2702. }
  2703. };
  2704. let aliases_map = match lock.get_aliases_mapped_by_token().await {
  2705. Ok(m) => m,
  2706. Err(e) => {
  2707. output.push(format!("Failed to fetch aliases map: {e}"));
  2708. return
  2709. }
  2710. };
  2711. let table = prettytable_tokenlist(&tokens, &aliases_map);
  2712. if table.is_empty() {
  2713. output.push(String::from("No tokens found"));
  2714. } else {
  2715. output.push(format!("{table}"));
  2716. }
  2717. }
  2718. /// Auxiliary function to define the token mint subcommand handling.
  2719. async fn handle_token_mint(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2720. // Check correct command structure
  2721. if parts.len() < 5 || parts.len() > 7 {
  2722. output.push(String::from("Malformed `token mint` subcommand"));
  2723. output.push(String::from(
  2724. "Usage: token mint <token> <amount> <recipient> [spend-hook] [user-data]",
  2725. ));
  2726. return
  2727. }
  2728. let amount = String::from(parts[3]);
  2729. if let Err(e) = f64::from_str(&amount) {
  2730. output.push(format!("Invalid amount: {e}"));
  2731. return
  2732. }
  2733. let rcpt = match Address::from_str(parts[4]) {
  2734. Ok(r) => r,
  2735. Err(e) => {
  2736. output.push(format!("Invalid recipient: {e}"));
  2737. return
  2738. }
  2739. };
  2740. let lock = drk.read().await;
  2741. if rcpt.network() != lock.network {
  2742. output.push("Recipient address prefix mismatch".to_string());
  2743. return
  2744. }
  2745. let token_id = match lock.get_token(String::from(parts[2])).await {
  2746. Ok(t) => t,
  2747. Err(e) => {
  2748. output.push(format!("Invalid token ID: {e}"));
  2749. return
  2750. }
  2751. };
  2752. // Parse command
  2753. let mut index = 5;
  2754. let spend_hook = if index < parts.len() {
  2755. match FuncId::from_str(parts[index]) {
  2756. Ok(s) => Some(s),
  2757. Err(e) => {
  2758. output.push(format!("Invalid spend hook: {e}"));
  2759. return
  2760. }
  2761. }
  2762. } else {
  2763. None
  2764. };
  2765. index += 1;
  2766. let user_data = if index < parts.len() {
  2767. let bytes = match bs58::decode(&parts[index]).into_vec() {
  2768. Ok(b) => b,
  2769. Err(e) => {
  2770. output.push(format!("Invalid user data: {e}"));
  2771. return
  2772. }
  2773. };
  2774. let bytes: [u8; 32] = match bytes.try_into() {
  2775. Ok(b) => b,
  2776. Err(e) => {
  2777. output.push(format!("Invalid user data: {e:?}"));
  2778. return
  2779. }
  2780. };
  2781. let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
  2782. Some(v) => v,
  2783. None => {
  2784. output.push(String::from("Invalid user data"));
  2785. return
  2786. }
  2787. };
  2788. Some(elem)
  2789. } else {
  2790. None
  2791. };
  2792. match lock.mint_token(&amount, *rcpt.public_key(), token_id, spend_hook, user_data).await {
  2793. Ok(t) => output.push(base64::encode(&serialize_async(&t).await)),
  2794. Err(e) => output.push(format!("Failed to create token mint transaction: {e}")),
  2795. }
  2796. }
  2797. /// Auxiliary function to define the token freeze subcommand handling.
  2798. async fn handle_token_freeze(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2799. // Check correct subcommand structure
  2800. if parts.len() != 3 {
  2801. output.push(String::from("Malformed `token freeze` subcommand"));
  2802. output.push(String::from("Usage: token freeze <token>"));
  2803. return
  2804. }
  2805. let lock = drk.read().await;
  2806. let token_id = match lock.get_token(String::from(parts[2])).await {
  2807. Ok(t) => t,
  2808. Err(e) => {
  2809. output.push(format!("Invalid token ID: {e}"));
  2810. return
  2811. }
  2812. };
  2813. match lock.freeze_token(token_id).await {
  2814. Ok(t) => output.push(base64::encode(&serialize_async(&t).await)),
  2815. Err(e) => output.push(format!("Failed to create token freeze transaction: {e}")),
  2816. }
  2817. }
  2818. /// Auxiliary function to define the contract command handling.
  2819. async fn handle_contract(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2820. // Check correct command structure
  2821. if parts.len() < 2 {
  2822. output.push(String::from("Malformed `contract` command"));
  2823. output.push(String::from("Usage: contract (generate-deploy|list|export-data|deploy|lock)"));
  2824. return
  2825. }
  2826. // Handle subcommand
  2827. match parts[1] {
  2828. "generate-deploy" => handle_contract_generate_deploy(drk, parts, output).await,
  2829. "list" => handle_contract_list(drk, parts, output).await,
  2830. "export-data" => handle_contract_export_data(drk, parts, output).await,
  2831. "deploy" => handle_contract_deploy(drk, parts, output).await,
  2832. "lock" => handle_contract_lock(drk, parts, output).await,
  2833. _ => {
  2834. output.push(format!("Unrecognized contract subcommand: {}", parts[1]));
  2835. output.push(String::from(
  2836. "Usage: contract (generate-deploy|list|export-data|deploy|lock)",
  2837. ));
  2838. }
  2839. }
  2840. }
  2841. /// Auxiliary function to define the contract generate deploy subcommand handling.
  2842. async fn handle_contract_generate_deploy(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2843. // Check correct subcommand structure
  2844. if parts.len() != 2 {
  2845. output.push(String::from("Malformed `contract generate-deploy` subcommand"));
  2846. output.push(String::from("Usage: contract generate-deploy"));
  2847. return
  2848. }
  2849. if let Err(e) = drk.read().await.deploy_auth_keygen(output).await {
  2850. output.push(format!("Error creating deploy auth keypair: {e}"));
  2851. }
  2852. }
  2853. /// Auxiliary function to define the contract list subcommand handling.
  2854. async fn handle_contract_list(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2855. // Check correct subcommand structure
  2856. if parts.len() != 2 && parts.len() != 3 {
  2857. output.push(String::from("Malformed `contract list` subcommand"));
  2858. output.push(String::from("Usage: contract list [contract-id]"));
  2859. return
  2860. }
  2861. if parts.len() == 3 {
  2862. let deploy_auth = match ContractId::from_str(parts[2]) {
  2863. Ok(d) => d,
  2864. Err(e) => {
  2865. output.push(format!("Invalid deploy authority: {e}"));
  2866. return
  2867. }
  2868. };
  2869. let history = match drk.read().await.get_deploy_auth_history(&deploy_auth).await {
  2870. Ok(a) => a,
  2871. Err(e) => {
  2872. output.push(format!("Failed to fetch deploy authority history records: {e}"));
  2873. return
  2874. }
  2875. };
  2876. let table = prettytable_contract_history(&history);
  2877. if table.is_empty() {
  2878. output.push(String::from("No history records found"));
  2879. } else {
  2880. output.push(format!("{table}"));
  2881. }
  2882. return
  2883. }
  2884. let auths = match drk.read().await.list_deploy_auth().await {
  2885. Ok(a) => a,
  2886. Err(e) => {
  2887. output.push(format!("Failed to fetch deploy authorities: {e}"));
  2888. return
  2889. }
  2890. };
  2891. let table = prettytable_contract_auth(&auths);
  2892. if table.is_empty() {
  2893. output.push(String::from("No deploy authorities found"));
  2894. } else {
  2895. output.push(format!("{table}"));
  2896. }
  2897. }
  2898. /// Auxiliary function to define the contract export data subcommand handling.
  2899. async fn handle_contract_export_data(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2900. // Check correct subcommand structure
  2901. if parts.len() != 3 {
  2902. output.push(String::from("Malformed `contract export-data` subcommand"));
  2903. output.push(String::from("Usage: contract export-data <tx-hash>"));
  2904. return
  2905. }
  2906. match drk.read().await.get_deploy_history_record_data(parts[2]).await {
  2907. Ok(pair) => output.push(base64::encode(&serialize_async(&pair).await)),
  2908. Err(e) => output.push(format!("Failed to retrieve history record: {e}")),
  2909. }
  2910. }
  2911. /// Auxiliary function to define the contract deploy subcommand handling.
  2912. async fn handle_contract_deploy(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2913. // Check correct subcommand structure
  2914. if parts.len() != 4 && parts.len() != 5 {
  2915. output.push(String::from("Malformed `contract deploy` subcommand"));
  2916. output.push(String::from("Usage: contract deploy <deploy-auth> <wasm-path> [deploy-ix]"));
  2917. return
  2918. }
  2919. let deploy_auth = match ContractId::from_str(parts[2]) {
  2920. Ok(d) => d,
  2921. Err(e) => {
  2922. output.push(format!("Invalid deploy authority: {e}"));
  2923. return
  2924. }
  2925. };
  2926. // Read the wasm bincode and deploy instruction
  2927. let file_path = match expand_path(parts[3]) {
  2928. Ok(p) => p,
  2929. Err(e) => {
  2930. output.push(format!("Error while expanding wasm bincode file path: {e}"));
  2931. return
  2932. }
  2933. };
  2934. let wasm_bin = match smol::fs::read(file_path).await {
  2935. Ok(w) => w,
  2936. Err(e) => {
  2937. output.push(format!("Error while reading wasm bincode file: {e}"));
  2938. return
  2939. }
  2940. };
  2941. let deploy_ix = if parts.len() == 5 {
  2942. let file_path = match expand_path(parts[4]) {
  2943. Ok(p) => p,
  2944. Err(e) => {
  2945. output.push(format!("Error while expanding deploy instruction file path: {e}"));
  2946. return
  2947. }
  2948. };
  2949. match smol::fs::read(file_path).await {
  2950. Ok(d) => d,
  2951. Err(e) => {
  2952. output.push(format!("Error while reading deploy instruction file: {e}"));
  2953. return
  2954. }
  2955. }
  2956. } else {
  2957. vec![]
  2958. };
  2959. match drk.read().await.deploy_contract(&deploy_auth, wasm_bin, deploy_ix).await {
  2960. Ok(t) => output.push(base64::encode(&serialize_async(&t).await)),
  2961. Err(e) => output.push(format!("Failed to create contract deployment transaction: {e}")),
  2962. }
  2963. }
  2964. /// Auxiliary function to define the contract lock subcommand handling.
  2965. async fn handle_contract_lock(drk: &DrkPtr, parts: &[&str], output: &mut Vec<String>) {
  2966. // Check correct subcommand structure
  2967. if parts.len() != 3 {
  2968. output.push(String::from("Malformed `contract lock` subcommand"));
  2969. output.push(String::from("Usage: contract lock <deploy-auth>"));
  2970. return
  2971. }
  2972. let deploy_auth = match ContractId::from_str(parts[2]) {
  2973. Ok(d) => d,
  2974. Err(e) => {
  2975. output.push(format!("Invalid deploy authority: {e}"));
  2976. return
  2977. }
  2978. };
  2979. match drk.read().await.lock_contract(&deploy_auth).await {
  2980. Ok(t) => output.push(base64::encode(&serialize_async(&t).await)),
  2981. Err(e) => output.push(format!("Failed to create contract lock transaction: {e}")),
  2982. }
  2983. }