main.rs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 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::{process::exit, sync::Arc, time::Instant};
  19. use smol::stream::StreamExt;
  20. use structopt_toml::{serde::Deserialize, structopt::StructOpt, StructOptToml};
  21. use url::Url;
  22. use darkfi::{
  23. async_daemonize, cli_desc,
  24. rpc::{client::RpcClient, jsonrpc::JsonRequest, util::JsonValue},
  25. util::path::expand_path,
  26. Result,
  27. };
  28. /// Error codes
  29. mod error;
  30. /// CLI utility functions
  31. mod cli_util;
  32. use cli_util::kaching;
  33. /// Wallet database operations handler
  34. mod walletdb;
  35. use walletdb::{WalletDb, WalletPtr};
  36. const CONFIG_FILE: &str = "drk_config.toml";
  37. const CONFIG_FILE_CONTENTS: &str = include_str!("../drk_config.toml");
  38. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  39. #[serde(default)]
  40. #[structopt(name = "drk", about = cli_desc!())]
  41. struct Args {
  42. #[structopt(short, long)]
  43. /// Configuration file to use
  44. config: Option<String>,
  45. #[structopt(long, default_value = "~/.local/darkfi/drk/wallet.db")]
  46. /// Path to wallet database
  47. wallet_path: String,
  48. #[structopt(long, default_value = "changeme")]
  49. /// Password for the wallet database
  50. wallet_pass: String,
  51. #[structopt(short, long, default_value = "tcp://127.0.0.1:8340")]
  52. /// darkfid JSON-RPC endpoint
  53. endpoint: Url,
  54. #[structopt(subcommand)]
  55. /// Sub command to execute
  56. command: Subcmd,
  57. #[structopt(short, long)]
  58. /// Set log file to ouput into
  59. log: Option<String>,
  60. #[structopt(short, parse(from_occurrences))]
  61. /// Increase verbosity (-vvv supported)
  62. verbose: u8,
  63. }
  64. #[derive(Clone, Debug, Deserialize, StructOpt)]
  65. enum Subcmd {
  66. /// Fun
  67. Kaching,
  68. /// Send a ping request to the darkfid RPC endpoint
  69. Ping,
  70. // TODO: shell completions
  71. /// Wallet operations
  72. Wallet {
  73. #[structopt(long)]
  74. /// Initialize wallet database
  75. initialize: bool,
  76. #[structopt(long)]
  77. /// Generate a new keypair in the wallet
  78. keygen: bool,
  79. #[structopt(long)]
  80. /// Query the wallet for known balances
  81. balance: bool,
  82. #[structopt(long)]
  83. /// Get the default address in the wallet
  84. address: bool,
  85. #[structopt(long)]
  86. /// Print all the secret keys from the wallet
  87. secrets: bool,
  88. #[structopt(long)]
  89. /// Import secret keys from stdin into the wallet, separated by newlines
  90. import_secrets: bool,
  91. #[structopt(long)]
  92. /// Print the Merkle tree in the wallet
  93. tree: bool,
  94. #[structopt(long)]
  95. /// Print all the coins in the wallet
  96. coins: bool,
  97. },
  98. }
  99. /// CLI-util structure
  100. pub struct Drk {
  101. /// Wallet database operations handler
  102. pub wallet: WalletPtr,
  103. /// JSON-RPC client to execute requests to darkfid daemon
  104. pub rpc_client: RpcClient,
  105. }
  106. impl Drk {
  107. async fn new(
  108. wallet_path: String,
  109. wallet_pass: String,
  110. endpoint: Url,
  111. ex: Arc<smol::Executor<'static>>,
  112. ) -> Result<Self> {
  113. let wallet = match WalletDb::new(Some(expand_path(&wallet_path)?), Some(&wallet_pass)) {
  114. Ok(w) => w,
  115. Err(e) => {
  116. eprintln!("Error initializing wallet: {e:?}");
  117. exit(2);
  118. }
  119. };
  120. let rpc_client = RpcClient::new(endpoint, ex).await?;
  121. Ok(Self { wallet, rpc_client })
  122. }
  123. /// Auxilliary function to ping configured darkfid daemon for liveness.
  124. async fn ping(&self) -> Result<()> {
  125. eprintln!("Executing ping request to darkfid...");
  126. let latency = Instant::now();
  127. let req = JsonRequest::new("ping", JsonValue::Array(vec![]));
  128. let rep = self.rpc_client.oneshot_request(req).await?;
  129. let latency = latency.elapsed();
  130. eprintln!("Got reply: {:?}", rep);
  131. eprintln!("Latency: {:?}", latency);
  132. Ok(())
  133. }
  134. }
  135. async_daemonize!(realmain);
  136. async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
  137. match args.command {
  138. Subcmd::Kaching => {
  139. kaching().await;
  140. Ok(())
  141. }
  142. Subcmd::Ping => {
  143. let drk = Drk::new(args.wallet_path, args.wallet_pass, args.endpoint, ex).await?;
  144. drk.ping().await
  145. }
  146. Subcmd::Wallet {
  147. initialize,
  148. keygen,
  149. balance,
  150. address,
  151. secrets,
  152. import_secrets,
  153. tree,
  154. coins,
  155. } => {
  156. if !initialize &&
  157. !keygen &&
  158. !balance &&
  159. !address &&
  160. !secrets &&
  161. !tree &&
  162. !coins &&
  163. !import_secrets
  164. {
  165. eprintln!("Error: You must use at least one flag for this subcommand");
  166. eprintln!("Run with \"wallet -h\" to see the subcommand usage.");
  167. exit(2);
  168. }
  169. // TODO
  170. Ok(())
  171. }
  172. }
  173. }