interactive.rs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{
  19. io::{stdin, ErrorKind, Read},
  20. str::FromStr,
  21. };
  22. use futures::{select, FutureExt};
  23. use libc::{fcntl, F_GETFL, F_SETFL, O_NONBLOCK};
  24. use linenoise_rs::{
  25. linenoise_history_add, linenoise_history_load, linenoise_history_save,
  26. linenoise_set_completion_callback, linenoise_set_hints_callback, LinenoiseState,
  27. };
  28. use prettytable::{format, row, Table};
  29. use smol::channel::{unbounded, Receiver, Sender};
  30. use url::Url;
  31. use darkfi::{
  32. cli_desc,
  33. system::{msleep, ExecutorPtr, StoppableTask, StoppableTaskPtr},
  34. util::{encoding::base64, parse::encode_base10, path::expand_path},
  35. zk::halo2::Field,
  36. Error,
  37. };
  38. use darkfi_money_contract::model::Coin;
  39. use darkfi_sdk::{
  40. crypto::{FuncId, PublicKey},
  41. pasta::{group::ff::PrimeField, pallas},
  42. };
  43. use darkfi_serial::{deserialize_async, serialize_async};
  44. use crate::{
  45. cli_util::{
  46. generate_completions, kaching, parse_token_pair, parse_tx_from_stdin, parse_value_pair,
  47. },
  48. money::BALANCE_BASE10_DECIMALS,
  49. rpc::subscribe_blocks,
  50. swap::PartialSwapData,
  51. DrkPtr,
  52. };
  53. // TODO:
  54. // 1. add rest commands handling, along with their completions, hints and help message.
  55. // 2. add input definitions, so you input from files not just stdin.
  56. // 3. add output definitions, so you can output to files not just stdout.
  57. // 4. create a transactions cache in the wallet db, so you can use it to handle them.
  58. /// Auxiliary function to print the help message.
  59. fn help() {
  60. println!("{}", cli_desc!());
  61. println!("Commands:");
  62. println!("\thelp: Prints the help message");
  63. println!("\tkaching: Fun");
  64. println!("\tping: Send a ping request to the darkfid RPC endpoint");
  65. println!("\tcompletions: Generate a SHELL completion script and print to stdout");
  66. println!("\twallet: Wallet operations");
  67. println!("\tspend: Read a transaction from stdin and mark its input coins as spent");
  68. println!("\tunspend: Unspend a coin");
  69. println!("\ttransfer: Create a payment transaction");
  70. println!("\totc: OTC atomic swap");
  71. println!("\tattach-fee: Attach the fee call to a transaction given from stdin");
  72. println!("\tinspect: Inspect a transaction from stdin");
  73. println!("\tbroadcast: Read a transaction from stdin and broadcast it");
  74. println!(
  75. "\tsubscribe: Perform a scan and then subscribe to darkfid to listen for incoming blocks"
  76. );
  77. println!("\tunsubscribe: Stops the background subscription, if its active");
  78. println!("\tsnooze: Disables the background subscription messages printing");
  79. println!("\tunsnooze: Enables the background subscription messages printing");
  80. println!("\tscan: Scan the blockchain and parse relevant transactions");
  81. }
  82. /// Auxiliary function to define the interactive shell completions.
  83. fn completion(buf: &str, lc: &mut Vec<String>) {
  84. // First we define the specific commands prefixes
  85. if buf.starts_with("h") {
  86. lc.push("help".to_string());
  87. return
  88. }
  89. if buf.starts_with("k") {
  90. lc.push("kaching".to_string());
  91. return
  92. }
  93. if buf.starts_with("p") {
  94. lc.push("ping".to_string());
  95. return
  96. }
  97. if buf.starts_with("c") {
  98. lc.push("completions".to_string());
  99. return
  100. }
  101. if buf.starts_with("w") {
  102. lc.push("wallet".to_string());
  103. lc.push("wallet --initialize".to_string());
  104. lc.push("wallet --keygen".to_string());
  105. lc.push("wallet --balance".to_string());
  106. lc.push("wallet --address".to_string());
  107. lc.push("wallet --addresses".to_string());
  108. lc.push("wallet --default-address".to_string());
  109. lc.push("wallet --secrets".to_string());
  110. lc.push("wallet --import-secrets".to_string());
  111. lc.push("wallet --tree".to_string());
  112. lc.push("wallet --coins".to_string());
  113. return
  114. }
  115. if buf.starts_with("sp") {
  116. lc.push("spend".to_string());
  117. return
  118. }
  119. if buf.starts_with("unsp") {
  120. lc.push("unspend".to_string());
  121. return
  122. }
  123. if buf.starts_with("t") {
  124. lc.push("transfer".to_string());
  125. return
  126. }
  127. if buf.starts_with("o") {
  128. lc.push("otc".to_string());
  129. lc.push("otc init".to_string());
  130. lc.push("otc join".to_string());
  131. lc.push("otc inspect".to_string());
  132. lc.push("otc sign".to_string());
  133. return
  134. }
  135. if buf.starts_with("a") {
  136. lc.push("attach-fee".to_string());
  137. return
  138. }
  139. if buf.starts_with("i") {
  140. lc.push("inspect".to_string());
  141. return
  142. }
  143. if buf.starts_with("b") {
  144. lc.push("broadcast".to_string());
  145. return
  146. }
  147. if buf.starts_with("su") {
  148. lc.push("subscribe".to_string());
  149. return
  150. }
  151. if buf.starts_with("unsu") {
  152. lc.push("unsubscribe".to_string());
  153. return
  154. }
  155. if buf.starts_with("sn") {
  156. lc.push("snooze".to_string());
  157. return
  158. }
  159. if buf.starts_with("unsn") {
  160. lc.push("unsnooze".to_string());
  161. return
  162. }
  163. if buf.starts_with("sc") {
  164. lc.push("scan".to_string());
  165. lc.push("scan --reset".to_string());
  166. return
  167. }
  168. // Now the catch alls
  169. if buf.starts_with("s") {
  170. lc.push("spend".to_string());
  171. lc.push("subscribe".to_string());
  172. lc.push("snooze".to_string());
  173. lc.push("scan".to_string());
  174. lc.push("scan --reset".to_string());
  175. return
  176. }
  177. if buf.starts_with("u") {
  178. lc.push("unspend".to_string());
  179. lc.push("unsubscribe".to_string());
  180. lc.push("unsnooze".to_string());
  181. }
  182. }
  183. /// Auxiliary function to define the interactive shell hints.
  184. fn hints(buf: &str) -> Option<(String, i32, bool)> {
  185. match buf {
  186. "completions " => Some(("<shell>".to_string(), 35, false)), // 35 = magenta
  187. "wallet " => Some(("--(initialize|keygen|balance|address|addresses|default-address|secrets|import-secrets|tree|coins)".to_string(), 35, false)),
  188. "wallet -" => Some(("-(initialize|keygen|balance|address|addresses|default-address|secrets|import-secrets|tree|coins)".to_string(), 35, false)),
  189. "wallet --" => Some(("(initialize|keygen|balance|address|addresses|default-address|secrets|import-secrets|tree|coins)".to_string(), 35, false)),
  190. "wallet --default-address " => Some(("<address_id>".to_string(), 35, false)),
  191. "unspend " => Some(("<coin>".to_string(), 35, false)),
  192. "transfer " => Some(("[--half-split] <amount> <token> <recipient> [spend_hook] [user_data]".to_string(), 35, false)),
  193. "otc " => Some(("(init|join|inspect|sign)".to_string(), 35, false)),
  194. "otc init " => Some(("<value_pair> <token_pair>".to_string(), 35, false)),
  195. "scan --reset " => Some(("<height>".to_string(), 35, false)),
  196. _ => None,
  197. }
  198. }
  199. /// Auxiliary function to start provided Drk as an interactive shell.
  200. /// Only sane/linenoise terminals are suported.
  201. pub async fn interactive(drk: &DrkPtr, endpoint: &Url, history_path: &str, ex: &ExecutorPtr) {
  202. // Expand the history file path
  203. let history_path = match expand_path(history_path) {
  204. Ok(p) => p,
  205. Err(e) => {
  206. eprintln!("Error while expanding history file path: {e}");
  207. return
  208. }
  209. };
  210. let history_path = history_path.into_os_string();
  211. let history_file = history_path.to_str().unwrap();
  212. // Set the completion callback. This will be called every time the
  213. // user uses the <tab> key.
  214. linenoise_set_completion_callback(completion);
  215. // Set the shell hints
  216. linenoise_set_hints_callback(hints);
  217. // Load history from file.The history file is just a plain text file
  218. // where entries are separated by newlines.
  219. let _ = linenoise_history_load(history_file);
  220. // Create a detached task to use for block subscription
  221. let mut subscription_active = false;
  222. let mut snooze_active = false;
  223. let subscription_task = StoppableTask::new();
  224. // Create an unbounded smol channel, so we can have a printing
  225. // queue the background task can submit messages to the shell.
  226. let (shell_sender, shell_receiver) = unbounded();
  227. // Start the interactive shell
  228. loop {
  229. // Wait for next line to process
  230. let line = listen_for_line(&snooze_active, &shell_receiver).await;
  231. // Grab input or end if Ctrl-D or Ctrl-C was pressed
  232. let Some(line) = line else { break };
  233. // Check if line is empty
  234. if line.is_empty() {
  235. continue
  236. }
  237. // Add line to history
  238. linenoise_history_add(&line);
  239. // Parse command parts
  240. let parts: Vec<&str> = line.split_whitespace().collect();
  241. if parts.is_empty() {
  242. continue
  243. }
  244. // Handle command
  245. match parts[0] {
  246. "help" => help(),
  247. "kaching" => kaching().await,
  248. "ping" => handle_ping(drk).await,
  249. "completions" => handle_completions(&parts),
  250. "wallet" => handle_wallet(drk, &parts).await,
  251. "spend" => handle_spend(drk).await,
  252. "unspend" => handle_unspend(drk, &parts).await,
  253. "transfer" => handle_transfer(drk, &parts).await,
  254. "otc" => handle_otc(drk, &parts).await,
  255. "attach-fee" => handle_attach_fee(drk).await,
  256. "inspect" => handle_inspect().await,
  257. "broadcast" => handle_broadcast(drk).await,
  258. "subscribe" => {
  259. handle_subscribe(
  260. drk,
  261. endpoint,
  262. &mut subscription_active,
  263. &subscription_task,
  264. &shell_sender,
  265. ex,
  266. )
  267. .await
  268. }
  269. "unsubscribe" => handle_unsubscribe(&mut subscription_active, &subscription_task).await,
  270. "snooze" => snooze_active = true,
  271. "unsnooze" => snooze_active = false,
  272. "scan" => handle_scan(drk, &subscription_active, &parts).await,
  273. _ => println!("Unreconized command: {}", parts[0]),
  274. }
  275. }
  276. // Stop the subscription task if its active
  277. if subscription_active {
  278. subscription_task.stop().await;
  279. }
  280. // Write history file
  281. let _ = linenoise_history_save(history_file);
  282. }
  283. /// Auxiliary function to listen for linenoise input line and handle
  284. /// background task messages.
  285. async fn listen_for_line(
  286. snooze_active: &bool,
  287. shell_receiver: &Receiver<Vec<String>>,
  288. ) -> Option<String> {
  289. // Generate the linoise state structure
  290. let mut state = match LinenoiseState::edit_start(-1, -1, "drk> ") {
  291. Ok(s) => s,
  292. Err(e) => {
  293. eprintln!("Error while generating linenoise state: {e}");
  294. return None
  295. }
  296. };
  297. // Set stdin to non-blocking mode
  298. let fd = state.get_fd();
  299. unsafe {
  300. let flags = fcntl(fd, F_GETFL, 0);
  301. fcntl(fd, F_SETFL, flags | O_NONBLOCK);
  302. }
  303. // Read until we get a line to process
  304. let mut line = None;
  305. loop {
  306. // Future that polls stdin for input
  307. let input_future = async {
  308. loop {
  309. match state.edit_feed() {
  310. Ok(Some(l)) => {
  311. line = Some(l);
  312. break
  313. }
  314. Ok(None) => break,
  315. Err(e) if e.kind() == ErrorKind::Interrupted => break,
  316. Err(e) if e.kind() == ErrorKind::WouldBlock => {
  317. // No data available, yield and retry
  318. msleep(10).await;
  319. continue
  320. }
  321. Err(e) => {
  322. eprintln!("Error while reading linenoise feed: {e}");
  323. break
  324. }
  325. }
  326. }
  327. };
  328. // Future that polls the channel
  329. let channel_future = async {
  330. loop {
  331. if !shell_receiver.is_empty() {
  332. break
  333. }
  334. msleep(1000).await;
  335. }
  336. };
  337. // Manage the futures
  338. select! {
  339. // When input is ready we break out the loop
  340. _ = input_future.fuse() => break,
  341. // Manage filled channel
  342. _ = channel_future.fuse() => {
  343. while !shell_receiver.is_empty() {
  344. match shell_receiver.recv().await {
  345. Ok(msg) => {
  346. // We only print if snooze is inactive,
  347. // but have to consume the message regardless,
  348. // so the queue gets empty.
  349. if *snooze_active {
  350. continue
  351. }
  352. // Hide prompt, print output, show prompt again
  353. let _ = state.hide();
  354. for line in msg {
  355. println!("{}\r", line.replace("\n", "\n\r"));
  356. }
  357. let _ = state.show();
  358. }
  359. Err(e) => {
  360. eprintln!("Error while reading shell receiver channel: {e}");
  361. break
  362. }
  363. }
  364. }
  365. }
  366. }
  367. }
  368. // Restore blocking mode
  369. unsafe {
  370. let flags = fcntl(fd, F_GETFL, 0);
  371. fcntl(fd, F_SETFL, flags & !O_NONBLOCK);
  372. }
  373. let _ = state.edit_stop();
  374. line
  375. }
  376. /// Auxiliary function to define the ping command handling.
  377. async fn handle_ping(drk: &DrkPtr) {
  378. if let Err(e) = drk.read().await.ping().await {
  379. println!("Error while executing ping command: {e}")
  380. }
  381. }
  382. /// Auxiliary function to define the completions command handling.
  383. fn handle_completions(parts: &[&str]) {
  384. // Check correct command structure
  385. if parts.len() != 2 {
  386. println!("Malformed `completions` command");
  387. println!("Usage: completions <shell>");
  388. return
  389. }
  390. if let Err(e) = generate_completions(parts[1]) {
  391. println!("Error while executing completions command: {e}")
  392. }
  393. }
  394. /// Auxiliary function to define the wallet command handling.
  395. async fn handle_wallet(drk: &DrkPtr, parts: &[&str]) {
  396. // Check correct command structure
  397. if parts.len() != 2 && parts.len() != 3 {
  398. println!("Malformed `wallet` command");
  399. println!("Usage: wallet --(initialize|keygen|balance|address|addresses|default-address|secrets|import-secrets|tree|coins)");
  400. return
  401. }
  402. // Handle command flag
  403. if parts[1] == "--initialize" {
  404. let lock = drk.read().await;
  405. if let Err(e) = lock.initialize_wallet().await {
  406. println!("Error initializing wallet: {e:?}");
  407. return
  408. }
  409. if let Err(e) = lock.initialize_money().await {
  410. println!("Failed to initialize Money: {e:?}");
  411. return
  412. }
  413. if let Err(e) = lock.initialize_dao().await {
  414. println!("Failed to initialize DAO: {e:?}");
  415. return
  416. }
  417. if let Err(e) = lock.initialize_deployooor() {
  418. println!("Failed to initialize Deployooor: {e:?}");
  419. }
  420. return
  421. }
  422. if parts[1] == "--keygen" {
  423. if let Err(e) = drk.read().await.money_keygen().await {
  424. println!("Failed to generate keypair: {e:?}");
  425. }
  426. return
  427. }
  428. if parts[1] == "--balance" {
  429. let lock = drk.read().await;
  430. let balmap = match lock.money_balance().await {
  431. Ok(m) => m,
  432. Err(e) => {
  433. println!("Failed to fetch balances map: {e:?}");
  434. return
  435. }
  436. };
  437. let aliases_map = match lock.get_aliases_mapped_by_token().await {
  438. Ok(m) => m,
  439. Err(e) => {
  440. println!("Failed to fetch aliases map: {e:?}");
  441. return
  442. }
  443. };
  444. // Create a prettytable with the new data:
  445. let mut table = Table::new();
  446. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  447. table.set_titles(row!["Token ID", "Aliases", "Balance"]);
  448. for (token_id, balance) in balmap.iter() {
  449. let aliases = match aliases_map.get(token_id) {
  450. Some(a) => a,
  451. None => "-",
  452. };
  453. table.add_row(row![
  454. token_id,
  455. aliases,
  456. encode_base10(*balance, BALANCE_BASE10_DECIMALS)
  457. ]);
  458. }
  459. if table.is_empty() {
  460. println!("No unspent balances found");
  461. } else {
  462. println!("{table}");
  463. }
  464. return
  465. }
  466. if parts[1] == "--address" {
  467. match drk.read().await.default_address().await {
  468. Ok(address) => println!("{address}"),
  469. Err(e) => println!("Failed to fetch default address: {e:?}"),
  470. }
  471. return
  472. }
  473. if parts[1] == "--addresses" {
  474. let addresses = match drk.read().await.addresses().await {
  475. Ok(a) => a,
  476. Err(e) => {
  477. println!("Failed to fetch addresses: {e:?}");
  478. return
  479. }
  480. };
  481. // Create a prettytable with the new data:
  482. let mut table = Table::new();
  483. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  484. table.set_titles(row!["Key ID", "Public Key", "Secret Key", "Is Default"]);
  485. for (key_id, public_key, secret_key, is_default) in addresses {
  486. let is_default = match is_default {
  487. 1 => "*",
  488. _ => "",
  489. };
  490. table.add_row(row![key_id, public_key, secret_key, is_default]);
  491. }
  492. if table.is_empty() {
  493. println!("No addresses found");
  494. } else {
  495. println!("{table}");
  496. }
  497. return
  498. }
  499. if parts[1] == "--default-address" {
  500. if parts.len() != 3 {
  501. println!("Malformed `wallet` command");
  502. println!("Usage: wallet --default-address <address_id>");
  503. return
  504. }
  505. let idx = match usize::from_str(parts[2]) {
  506. Ok(i) => i,
  507. Err(e) => {
  508. println!("Invalid address id: {e:?}");
  509. return
  510. }
  511. };
  512. if let Err(e) = drk.read().await.set_default_address(idx) {
  513. println!("Failed to set default address: {e:?}");
  514. }
  515. return
  516. }
  517. if parts[1] == "--secrets" {
  518. match drk.read().await.get_money_secrets().await {
  519. Ok(secrets) => {
  520. for secret in secrets {
  521. println!("{secret}");
  522. }
  523. }
  524. Err(e) => println!("Failed to fetch secrets: {e:?}"),
  525. }
  526. return
  527. }
  528. if parts[1] == "--import-secrets" {
  529. let mut secrets = vec![];
  530. // TODO: read from a file here not stdin
  531. let lines = stdin().lines();
  532. for (i, line) in lines.enumerate() {
  533. if let Ok(line) = line {
  534. let Ok(bytes) = bs58::decode(&line.trim()).into_vec() else {
  535. println!("Warning: Failed to decode secret on line {i}");
  536. continue
  537. };
  538. let Ok(secret) = deserialize_async(&bytes).await else {
  539. println!("Warning: Failed to deserialize secret on line {i}");
  540. continue
  541. };
  542. secrets.push(secret);
  543. }
  544. }
  545. match drk.read().await.import_money_secrets(secrets).await {
  546. Ok(pubkeys) => {
  547. for key in pubkeys {
  548. println!("{key}");
  549. }
  550. }
  551. Err(e) => println!("Failed to import secrets: {e:?}"),
  552. }
  553. return
  554. }
  555. if parts[1] == "--tree" {
  556. // TODO: write to a file here not stdout
  557. match drk.read().await.get_money_tree().await {
  558. Ok(tree) => println!("{tree:#?}"),
  559. Err(e) => println!("Failed to fetch tree: {e:?}"),
  560. }
  561. return
  562. }
  563. if parts[1] == "--coins" {
  564. let lock = drk.read().await;
  565. let coins = match lock.get_coins(true).await {
  566. Ok(c) => c,
  567. Err(e) => {
  568. println!("Failed to fetch coins: {e:?}");
  569. return
  570. }
  571. };
  572. if coins.is_empty() {
  573. return
  574. }
  575. let aliases_map = match lock.get_aliases_mapped_by_token().await {
  576. Ok(m) => m,
  577. Err(e) => {
  578. println!("Failed to fetch aliases map: {e:?}");
  579. return
  580. }
  581. };
  582. let mut table = Table::new();
  583. table.set_format(*format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR);
  584. table.set_titles(row![
  585. "Coin",
  586. "Token ID",
  587. "Aliases",
  588. "Value",
  589. "Spend Hook",
  590. "User Data",
  591. "Creation Height",
  592. "Spent",
  593. "Spent Height",
  594. "Spent TX"
  595. ]);
  596. for coin in coins {
  597. let aliases = match aliases_map.get(&coin.0.note.token_id.to_string()) {
  598. Some(a) => a,
  599. None => "-",
  600. };
  601. let spend_hook = if coin.0.note.spend_hook != FuncId::none() {
  602. format!("{}", coin.0.note.spend_hook)
  603. } else {
  604. String::from("-")
  605. };
  606. let user_data = if coin.0.note.user_data != pallas::Base::ZERO {
  607. bs58::encode(&serialize_async(&coin.0.note.user_data).await)
  608. .into_string()
  609. .to_string()
  610. } else {
  611. String::from("-")
  612. };
  613. let spent_height = match coin.3 {
  614. Some(spent_height) => spent_height.to_string(),
  615. None => String::from("-"),
  616. };
  617. table.add_row(row![
  618. bs58::encode(&serialize_async(&coin.0.coin.inner()).await)
  619. .into_string()
  620. .to_string(),
  621. coin.0.note.token_id,
  622. aliases,
  623. format!(
  624. "{} ({})",
  625. coin.0.note.value,
  626. encode_base10(coin.0.note.value, BALANCE_BASE10_DECIMALS)
  627. ),
  628. spend_hook,
  629. user_data,
  630. coin.1,
  631. coin.2,
  632. spent_height,
  633. coin.4,
  634. ]);
  635. }
  636. println!("{table}");
  637. return
  638. }
  639. println!("Malformed `wallet` command");
  640. println!("Usage: wallet --(initialize|keygen|balance|address|addresses|default-address|secrets|import-secrets|tree|coins)");
  641. }
  642. /// Auxiliary function to define the spend command handling.
  643. async fn handle_spend(drk: &DrkPtr) {
  644. let tx = match parse_tx_from_stdin().await {
  645. Ok(t) => t,
  646. Err(e) => {
  647. println!("Error while parsing transaction: {e}");
  648. return
  649. }
  650. };
  651. if let Err(e) = drk.read().await.mark_tx_spend(&tx).await {
  652. println!("Failed to mark transaction coins as spent: {e}")
  653. }
  654. }
  655. /// Auxiliary function to define the unspend command handling.
  656. async fn handle_unspend(drk: &DrkPtr, parts: &[&str]) {
  657. // Check correct command structure
  658. if parts.len() != 2 {
  659. println!("Malformed `unspend` command");
  660. println!("Usage: unspend <coin>");
  661. return
  662. }
  663. let bytes = match bs58::decode(&parts[1]).into_vec() {
  664. Ok(b) => b,
  665. Err(e) => {
  666. println!("Invalid coin: {e}");
  667. return
  668. }
  669. };
  670. let bytes: [u8; 32] = match bytes.try_into() {
  671. Ok(b) => b,
  672. Err(e) => {
  673. println!("Invalid coin: {e:?}");
  674. return
  675. }
  676. };
  677. let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
  678. Some(v) => v,
  679. None => {
  680. println!("Invalid coin");
  681. return
  682. }
  683. };
  684. if let Err(e) = drk.read().await.unspend_coin(&Coin::from(elem)).await {
  685. println!("Failed to mark coin as unspent: {e}")
  686. }
  687. }
  688. /// Auxiliary function to define the transfer command handling.
  689. async fn handle_transfer(drk: &DrkPtr, parts: &[&str]) {
  690. // Check correct command structure
  691. if parts.len() < 4 || parts.len() > 7 {
  692. println!("Malformed `transfer` command");
  693. println!(
  694. "Usage: transfer [--half-split] <amount> <token> <recipient> [spend_hook] [user_data]"
  695. );
  696. return
  697. }
  698. // Parse command
  699. let mut index = 1;
  700. let mut half_split = false;
  701. if parts[index] == "--half-split" {
  702. half_split = true;
  703. index += 1;
  704. }
  705. let amount = String::from(parts[index]);
  706. if let Err(e) = f64::from_str(&amount) {
  707. println!("Invalid amount: {e}");
  708. return
  709. }
  710. index += 1;
  711. let lock = drk.read().await;
  712. let token_id = match lock.get_token(String::from(parts[index])).await {
  713. Ok(t) => t,
  714. Err(e) => {
  715. println!("Invalid token alias: {e}");
  716. return
  717. }
  718. };
  719. index += 1;
  720. let rcpt = match PublicKey::from_str(parts[index]) {
  721. Ok(r) => r,
  722. Err(e) => {
  723. println!("Invalid recipient: {e}");
  724. return
  725. }
  726. };
  727. index += 1;
  728. let spend_hook = if index < parts.len() {
  729. match FuncId::from_str(parts[index]) {
  730. Ok(s) => Some(s),
  731. Err(e) => {
  732. println!("Invalid spend hook: {e}");
  733. return
  734. }
  735. }
  736. } else {
  737. None
  738. };
  739. index += 1;
  740. let user_data = if index < parts.len() {
  741. let bytes = match bs58::decode(&parts[index]).into_vec() {
  742. Ok(b) => b,
  743. Err(e) => {
  744. println!("Invalid user data: {e}");
  745. return
  746. }
  747. };
  748. let bytes: [u8; 32] = match bytes.try_into() {
  749. Ok(b) => b,
  750. Err(e) => {
  751. println!("Invalid user data: {e:?}");
  752. return
  753. }
  754. };
  755. let elem: pallas::Base = match pallas::Base::from_repr(bytes).into() {
  756. Some(v) => v,
  757. None => {
  758. println!("Invalid user data");
  759. return
  760. }
  761. };
  762. Some(elem)
  763. } else {
  764. None
  765. };
  766. // TODO: write to a file here not stdout
  767. match lock.transfer(&amount, token_id, rcpt, spend_hook, user_data, half_split).await {
  768. Ok(t) => println!("{}", base64::encode(&serialize_async(&t).await)),
  769. Err(e) => println!("Failed to create payment transaction: {e}"),
  770. }
  771. }
  772. /// Auxiliary function to define the otc command handling.
  773. async fn handle_otc(drk: &DrkPtr, parts: &[&str]) {
  774. // Check correct command structure
  775. if parts.len() < 2 {
  776. println!("Malformed `otc` command");
  777. println!("Usage: otc (init|join|inspect|sign)");
  778. return
  779. }
  780. // Handle subcommand
  781. match parts[1] {
  782. "init" => handle_otc_init(drk, parts).await,
  783. "join" => handle_otc_join(drk, parts).await,
  784. "inspect" => handle_otc_inspect(drk, parts).await,
  785. "sign" => handle_otc_sign(drk, parts).await,
  786. _ => {
  787. println!("Unreconized OTC subcommand: {}", parts[1]);
  788. println!("Usage: otc (init|join|inspect|sign)");
  789. }
  790. }
  791. }
  792. /// Auxiliary function to define the otc init subcommand handling.
  793. async fn handle_otc_init(drk: &DrkPtr, parts: &[&str]) {
  794. // Check correct subcommand structure
  795. if parts.len() != 4 {
  796. println!("Malformed `otc init` subcommand");
  797. println!("Usage: otc init <value_pair> <token_pair>");
  798. return
  799. }
  800. let value_pair = match parse_value_pair(parts[2]) {
  801. Ok(v) => v,
  802. Err(e) => {
  803. println!("Invalid value pair: {e}");
  804. return
  805. }
  806. };
  807. let lock = drk.read().await;
  808. let token_pair = match parse_token_pair(&lock, parts[3]).await {
  809. Ok(t) => t,
  810. Err(e) => {
  811. println!("Invalid token pair: {e}");
  812. return
  813. }
  814. };
  815. match lock.init_swap(value_pair, token_pair, None, None, None).await {
  816. Ok(half) => println!("{}", base64::encode(&serialize_async(&half).await)),
  817. Err(e) => eprintln!("Failed to create swap transaction half: {e}"),
  818. }
  819. }
  820. /// Auxiliary function to define the otc join subcommand handling.
  821. async fn handle_otc_join(drk: &DrkPtr, parts: &[&str]) {
  822. // Check correct subcommand structure
  823. if parts.len() != 2 {
  824. println!("Malformed `otc join` subcommand");
  825. println!("Usage: otc join");
  826. return
  827. }
  828. // TODO: read from a file here not stdin
  829. let mut buf = String::new();
  830. if let Err(e) = stdin().read_to_string(&mut buf) {
  831. println!("Failed to read from stdin: {e}");
  832. return
  833. };
  834. let Some(bytes) = base64::decode(buf.trim()) else {
  835. println!("Failed to decode partial swap data");
  836. return
  837. };
  838. let partial: PartialSwapData = match deserialize_async(&bytes).await {
  839. Ok(p) => p,
  840. Err(e) => {
  841. println!("Failed to deserialize partial swap data: {e}");
  842. return
  843. }
  844. };
  845. match drk.read().await.join_swap(partial, None, None, None).await {
  846. Ok(tx) => println!("{}", base64::encode(&serialize_async(&tx).await)),
  847. Err(e) => eprintln!("Failed to create a join swap transaction: {e}"),
  848. }
  849. }
  850. /// Auxiliary function to define the otc inspect subcommand handling.
  851. async fn handle_otc_inspect(drk: &DrkPtr, parts: &[&str]) {
  852. // Check correct subcommand structure
  853. if parts.len() != 2 {
  854. println!("Malformed `otc inspect` subcommand");
  855. println!("Usage: otc inspect");
  856. return
  857. }
  858. // TODO: read from a file here not stdin
  859. let mut buf = String::new();
  860. if let Err(e) = stdin().read_to_string(&mut buf) {
  861. println!("Failed to read from stdin: {e}");
  862. return
  863. };
  864. let Some(bytes) = base64::decode(buf.trim()) else {
  865. println!("Failed to decode swap transaction");
  866. return
  867. };
  868. if let Err(e) = drk.read().await.inspect_swap(bytes).await {
  869. println!("Failed to inspect swap: {e}");
  870. }
  871. }
  872. /// Auxiliary function to define the otc sign subcommand handling.
  873. async fn handle_otc_sign(drk: &DrkPtr, parts: &[&str]) {
  874. // Check correct subcommand structure
  875. if parts.len() != 2 {
  876. println!("Malformed `otc sign` subcommand");
  877. println!("Usage: otc sign");
  878. return
  879. }
  880. // TODO: read from a file here not stdin
  881. let mut tx = match parse_tx_from_stdin().await {
  882. Ok(t) => t,
  883. Err(e) => {
  884. println!("Error while parsing transaction: {e}");
  885. return
  886. }
  887. };
  888. match drk.read().await.sign_swap(&mut tx).await {
  889. Ok(_) => println!("{}", base64::encode(&serialize_async(&tx).await)),
  890. Err(e) => println!("Failed to sign joined swap transaction: {e}"),
  891. }
  892. }
  893. /// Auxiliary function to define the attach fee command handling.
  894. async fn handle_attach_fee(drk: &DrkPtr) {
  895. // TODO: read from a file here not stdin
  896. let mut tx = match parse_tx_from_stdin().await {
  897. Ok(t) => t,
  898. Err(e) => {
  899. println!("Error while parsing transaction: {e}");
  900. return
  901. }
  902. };
  903. match drk.read().await.attach_fee(&mut tx).await {
  904. Ok(_) => println!("{}", base64::encode(&serialize_async(&tx).await)),
  905. Err(e) => println!("Failed to attach the fee call to the transaction: {e}"),
  906. }
  907. }
  908. /// Auxiliary function to define the inspect command handling.
  909. async fn handle_inspect() {
  910. // TODO: read from a file here not stdin
  911. match parse_tx_from_stdin().await {
  912. Ok(tx) => println!("{tx:#?}"),
  913. Err(e) => println!("Error while parsing transaction: {e}"),
  914. }
  915. }
  916. /// Auxiliary function to define the broadcast command handling.
  917. async fn handle_broadcast(drk: &DrkPtr) {
  918. // TODO: read from a file here not stdin
  919. let tx = match parse_tx_from_stdin().await {
  920. Ok(t) => t,
  921. Err(e) => {
  922. println!("Error while parsing transaction: {e}");
  923. return
  924. }
  925. };
  926. let lock = drk.read().await;
  927. if let Err(e) = lock.simulate_tx(&tx).await {
  928. println!("Failed to simulate tx: {e}");
  929. return
  930. };
  931. if let Err(e) = lock.mark_tx_spend(&tx).await {
  932. println!("Failed to mark transaction coins as spent: {e}");
  933. return
  934. };
  935. match lock.broadcast_tx(&tx).await {
  936. Ok(txid) => println!("Transaction ID: {txid}"),
  937. Err(e) => println!("Failed to broadcast transaction: {e}"),
  938. }
  939. }
  940. /// Auxiliary function to define the subscribe command handling.
  941. async fn handle_subscribe(
  942. drk: &DrkPtr,
  943. endpoint: &Url,
  944. subscription_active: &mut bool,
  945. subscription_task: &StoppableTaskPtr,
  946. shell_sender: &Sender<Vec<String>>,
  947. ex: &ExecutorPtr,
  948. ) {
  949. if *subscription_active {
  950. println!("Subscription is already active!");
  951. return
  952. }
  953. if let Err(e) = drk.read().await.scan_blocks().await {
  954. println!("Failed during scanning: {e:?}");
  955. return
  956. }
  957. println!("Finished scanning blockchain");
  958. // Start the subcristion task
  959. let drk_ = drk.clone();
  960. let endpoint_ = endpoint.clone();
  961. let shell_sender_ = shell_sender.clone();
  962. let ex_ = ex.clone();
  963. subscription_task.clone().start(
  964. async move { subscribe_blocks(&drk_, shell_sender_, endpoint_, &ex_).await },
  965. |res| async {
  966. match res {
  967. Ok(()) | Err(Error::DetachedTaskStopped) => { /* Do nothing */ }
  968. Err(e) => println!("Failed starting subscription task: {e}"),
  969. }
  970. },
  971. Error::DetachedTaskStopped,
  972. ex.clone(),
  973. );
  974. *subscription_active = true;
  975. }
  976. /// Auxiliary function to define the unsubscribe command handling.
  977. async fn handle_unsubscribe(subscription_active: &mut bool, subscription_task: &StoppableTaskPtr) {
  978. if !*subscription_active {
  979. println!("Subscription is already inactive!");
  980. return
  981. }
  982. subscription_task.stop().await;
  983. *subscription_active = false;
  984. }
  985. /// Auxiliary function to define the scan command handling.
  986. async fn handle_scan(drk: &DrkPtr, subscription_active: &bool, parts: &[&str]) {
  987. if *subscription_active {
  988. println!("Subscription is already active!");
  989. return
  990. }
  991. // Check correct command structure
  992. if parts.len() != 1 && parts.len() != 3 {
  993. println!("Malformed `scan` command");
  994. return
  995. }
  996. // Check if reset was requested
  997. let lock = drk.read().await;
  998. if parts.len() == 3 {
  999. if parts[1] != "--reset" {
  1000. println!("Malformed `scan` command");
  1001. println!("Usage: scan --reset <height>");
  1002. return
  1003. }
  1004. let height = match u32::from_str(parts[2]) {
  1005. Ok(h) => h,
  1006. Err(e) => {
  1007. println!("Invalid reset height: {e:?}");
  1008. return
  1009. }
  1010. };
  1011. if let Err(e) = lock.reset_to_height(height) {
  1012. println!("Failed during wallet reset: {e:?}");
  1013. return
  1014. }
  1015. }
  1016. if let Err(e) = lock.scan_blocks().await {
  1017. println!("Failed during scanning: {e:?}");
  1018. return
  1019. }
  1020. println!("Finished scanning blockchain");
  1021. }