drk.rs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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};
  19. use url::Url;
  20. use darkfi::{rpc::client::RpcClient, util::path::expand_path, Result};
  21. use crate::walletdb::{WalletDb, WalletPtr};
  22. /// CLI-util structure
  23. pub struct Drk {
  24. /// Wallet database operations handler
  25. pub wallet: WalletPtr,
  26. /// JSON-RPC client to execute requests to darkfid daemon
  27. pub rpc_client: Option<RpcClient>,
  28. }
  29. impl Drk {
  30. pub async fn new(
  31. wallet_path: String,
  32. wallet_pass: String,
  33. endpoint: Option<Url>,
  34. ex: Arc<smol::Executor<'static>>,
  35. ) -> Result<Self> {
  36. // Script kiddies protection
  37. if wallet_pass == "changeme" {
  38. eprintln!("Please don't use default wallet password...");
  39. exit(2);
  40. }
  41. // Initialize wallet
  42. let wallet_path = expand_path(&wallet_path)?;
  43. if !wallet_path.exists() {
  44. if let Some(parent) = wallet_path.parent() {
  45. fs::create_dir_all(parent)?;
  46. }
  47. }
  48. let wallet = match WalletDb::new(Some(wallet_path), Some(&wallet_pass)) {
  49. Ok(w) => w,
  50. Err(e) => {
  51. eprintln!("Error initializing wallet: {e:?}");
  52. exit(2);
  53. }
  54. };
  55. // Initialize rpc client
  56. let rpc_client = if let Some(endpoint) = endpoint {
  57. Some(RpcClient::new(endpoint, ex).await?)
  58. } else {
  59. None
  60. };
  61. Ok(Self { wallet, rpc_client })
  62. }
  63. /// Initialize wallet with tables for drk
  64. pub fn initialize_wallet(&self) -> Result<()> {
  65. let wallet_schema = include_str!("../wallet.sql");
  66. if let Err(e) = self.wallet.exec_batch_sql(wallet_schema) {
  67. eprintln!("Error initializing wallet: {e:?}");
  68. exit(2);
  69. }
  70. Ok(())
  71. }
  72. }