main.rs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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::{fs, 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 functionality related to Money
  34. mod money;
  35. /// Wallet functionality related to Dao
  36. mod dao;
  37. /// Wallet database operations handler
  38. mod walletdb;
  39. use walletdb::{WalletDb, WalletPtr};
  40. const CONFIG_FILE: &str = "drk_config.toml";
  41. const CONFIG_FILE_CONTENTS: &str = include_str!("../drk_config.toml");
  42. #[derive(Clone, Debug, Deserialize, StructOpt, StructOptToml)]
  43. #[serde(default)]
  44. #[structopt(name = "drk", about = cli_desc!())]
  45. struct Args {
  46. #[structopt(short, long)]
  47. /// Configuration file to use
  48. config: Option<String>,
  49. #[structopt(long, default_value = "~/.local/darkfi/drk/wallet.db")]
  50. /// Path to wallet database
  51. wallet_path: String,
  52. #[structopt(long, default_value = "changeme")]
  53. /// Password for the wallet database
  54. wallet_pass: String,
  55. #[structopt(short, long, default_value = "tcp://127.0.0.1:8340")]
  56. /// darkfid JSON-RPC endpoint
  57. endpoint: Url,
  58. #[structopt(subcommand)]
  59. /// Sub command to execute
  60. command: Subcmd,
  61. #[structopt(short, long)]
  62. /// Set log file to ouput into
  63. log: Option<String>,
  64. #[structopt(short, parse(from_occurrences))]
  65. /// Increase verbosity (-vvv supported)
  66. verbose: u8,
  67. }
  68. #[derive(Clone, Debug, Deserialize, StructOpt)]
  69. enum Subcmd {
  70. /// Fun
  71. Kaching,
  72. /// Send a ping request to the darkfid RPC endpoint
  73. Ping,
  74. // TODO: shell completions
  75. /// Wallet operations
  76. Wallet {
  77. #[structopt(long)]
  78. /// Initialize wallet database
  79. initialize: bool,
  80. #[structopt(long)]
  81. /// Generate a new keypair in the wallet
  82. keygen: bool,
  83. #[structopt(long)]
  84. /// Query the wallet for known balances
  85. balance: bool,
  86. #[structopt(long)]
  87. /// Get the default address in the wallet
  88. address: bool,
  89. #[structopt(long)]
  90. /// Print all the secret keys from the wallet
  91. secrets: bool,
  92. #[structopt(long)]
  93. /// Import secret keys from stdin into the wallet, separated by newlines
  94. import_secrets: bool,
  95. #[structopt(long)]
  96. /// Print the Merkle tree in the wallet
  97. tree: bool,
  98. #[structopt(long)]
  99. /// Print all the coins in the wallet
  100. coins: bool,
  101. },
  102. }
  103. /// CLI-util structure
  104. pub struct Drk {
  105. /// Wallet database operations handler
  106. pub wallet: WalletPtr,
  107. /// JSON-RPC client to execute requests to darkfid daemon
  108. pub rpc_client: RpcClient,
  109. }
  110. impl Drk {
  111. async fn new(
  112. wallet_path: String,
  113. wallet_pass: String,
  114. endpoint: Url,
  115. ex: Arc<smol::Executor<'static>>,
  116. ) -> Result<Self> {
  117. // Initialize wallet
  118. let wallet_path = expand_path(&wallet_path)?;
  119. if !wallet_path.exists() {
  120. if let Some(parent) = wallet_path.parent() {
  121. fs::create_dir_all(parent)?;
  122. }
  123. }
  124. let wallet = match WalletDb::new(Some(wallet_path), Some(&wallet_pass)) {
  125. Ok(w) => w,
  126. Err(e) => {
  127. eprintln!("Error initializing wallet: {e:?}");
  128. exit(2);
  129. }
  130. };
  131. // Initialize rpc client
  132. let rpc_client = RpcClient::new(endpoint, ex).await?;
  133. Ok(Self { wallet, rpc_client })
  134. }
  135. /// Initialize wallet with tables for drk
  136. async fn initialize_wallet(&self) -> Result<()> {
  137. let wallet_schema = include_str!("../wallet.sql");
  138. if let Err(e) = self.wallet.exec_batch_sql(wallet_schema).await {
  139. eprintln!("Error initializing wallet: {e:?}");
  140. exit(2);
  141. }
  142. Ok(())
  143. }
  144. /// Auxilliary function to ping configured darkfid daemon for liveness.
  145. async fn ping(&self) -> Result<()> {
  146. eprintln!("Executing ping request to darkfid...");
  147. let latency = Instant::now();
  148. let req = JsonRequest::new("ping", JsonValue::Array(vec![]));
  149. let rep = self.rpc_client.oneshot_request(req).await?;
  150. let latency = latency.elapsed();
  151. eprintln!("Got reply: {:?}", rep);
  152. eprintln!("Latency: {:?}", latency);
  153. Ok(())
  154. }
  155. }
  156. async_daemonize!(realmain);
  157. async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
  158. match args.command {
  159. Subcmd::Kaching => {
  160. kaching().await;
  161. Ok(())
  162. }
  163. Subcmd::Ping => {
  164. let drk = Drk::new(args.wallet_path, args.wallet_pass, args.endpoint, ex).await?;
  165. drk.ping().await
  166. }
  167. Subcmd::Wallet {
  168. initialize,
  169. keygen,
  170. balance,
  171. address,
  172. secrets,
  173. import_secrets,
  174. tree,
  175. coins,
  176. } => {
  177. if !initialize &&
  178. !keygen &&
  179. !balance &&
  180. !address &&
  181. !secrets &&
  182. !tree &&
  183. !coins &&
  184. !import_secrets
  185. {
  186. eprintln!("Error: You must use at least one flag for this subcommand");
  187. eprintln!("Run with \"wallet -h\" to see the subcommand usage.");
  188. exit(2);
  189. }
  190. let drk = Drk::new(args.wallet_path, args.wallet_pass, args.endpoint, ex).await?;
  191. if initialize {
  192. drk.initialize_wallet().await?;
  193. drk.initialize_money().await?;
  194. drk.initialize_dao().await?;
  195. return Ok(())
  196. }
  197. // TODO
  198. Ok(())
  199. }
  200. }
  201. }