interactive.rs 115 KB

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