Преглед изворни кода

drk: restructer as a library

skoupidi пре 2 година
родитељ
комит
1f4d72d3ad
5 измењених фајлова са 194 додато и 120 уклоњено
  1. 107 0
      bin/drk/src/drk.rs
  2. 24 0
      bin/drk/src/error.rs
  3. 54 0
      bin/drk/src/lib.rs
  4. 8 119
      bin/drk/src/main.rs
  5. 1 1
      bin/drk/src/money.rs

+ 107 - 0
bin/drk/src/drk.rs

@@ -0,0 +1,107 @@
+/* This file is part of DarkFi (https://dark.fi)
+ *
+ * Copyright (C) 2020-2024 Dyne.org foundation
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <https://www.gnu.org/licenses/>.
+ */
+
+use std::{fs, process::exit, sync::Arc, time::Instant};
+
+use url::Url;
+
+use darkfi::{
+    rpc::{client::RpcClient, jsonrpc::JsonRequest, util::JsonValue},
+    util::path::expand_path,
+    Result,
+};
+
+use crate::walletdb::{WalletDb, WalletPtr};
+
+/// CLI-util structure
+pub struct Drk {
+    /// Wallet database operations handler
+    pub wallet: WalletPtr,
+    /// JSON-RPC client to execute requests to darkfid daemon
+    pub rpc_client: Option<RpcClient>,
+}
+
+impl Drk {
+    pub async fn new(
+        wallet_path: String,
+        wallet_pass: String,
+        endpoint: Option<Url>,
+        ex: Arc<smol::Executor<'static>>,
+    ) -> Result<Self> {
+        // Script kiddies protection
+        if wallet_pass == "changeme" {
+            eprintln!("Please don't use default wallet password...");
+            exit(2);
+        }
+
+        // Initialize wallet
+        let wallet_path = expand_path(&wallet_path)?;
+        if !wallet_path.exists() {
+            if let Some(parent) = wallet_path.parent() {
+                fs::create_dir_all(parent)?;
+            }
+        }
+        let wallet = match WalletDb::new(Some(wallet_path), Some(&wallet_pass)) {
+            Ok(w) => w,
+            Err(e) => {
+                eprintln!("Error initializing wallet: {e:?}");
+                exit(2);
+            }
+        };
+
+        // Initialize rpc client
+        let rpc_client = if let Some(endpoint) = endpoint {
+            Some(RpcClient::new(endpoint, ex).await?)
+        } else {
+            None
+        };
+
+        Ok(Self { wallet, rpc_client })
+    }
+
+    /// Initialize wallet with tables for drk
+    pub fn initialize_wallet(&self) -> Result<()> {
+        let wallet_schema = include_str!("../wallet.sql");
+        if let Err(e) = self.wallet.exec_batch_sql(wallet_schema) {
+            eprintln!("Error initializing wallet: {e:?}");
+            exit(2);
+        }
+
+        Ok(())
+    }
+
+    /// Auxiliary function to ping configured darkfid daemon for liveness.
+    pub async fn ping(&self) -> Result<()> {
+        println!("Executing ping request to darkfid...");
+        let latency = Instant::now();
+        let req = JsonRequest::new("ping", JsonValue::Array(vec![]));
+        let rep = self.rpc_client.as_ref().unwrap().request(req).await?;
+        let latency = latency.elapsed();
+        println!("Got reply: {rep:?}");
+        println!("Latency: {latency:?}");
+        Ok(())
+    }
+
+    /// Auxiliary function to stop current JSON-RPC client, if its initialized.
+    pub async fn stop_rpc_client(&self) -> Result<()> {
+        if let Some(ref rpc_client) = self.rpc_client {
+            rpc_client.stop().await;
+        };
+        Ok(())
+    }
+}

+ 24 - 0
bin/drk/src/error.rs

@@ -40,3 +40,27 @@ pub enum WalletDbError {
     // Generic error
     // Generic error
     GenericError = -32130,
     GenericError = -32130,
 }
 }
+
+impl std::fmt::Display for WalletDbError {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        match self {
+            WalletDbError::ConnectionFailed => write!(f, "WalletDbError::ConnectionFailed"),
+            WalletDbError::FailedToAquireLock => write!(f, "WalletDbError::FailedToAquireLock"),
+            WalletDbError::PragmaUpdateError => write!(f, "WalletDbError::PragmaUpdateError"),
+            WalletDbError::QueryPreparationFailed => {
+                write!(f, "WalletDbError::QueryPreparationFailed")
+            }
+            WalletDbError::QueryExecutionFailed => write!(f, "WalletDbError::QueryExecutionFailed"),
+            WalletDbError::QueryFinalizationFailed => {
+                write!(f, "WalletDbError::QueryFinalizationFailed")
+            }
+            WalletDbError::ParseColumnValueError => {
+                write!(f, "WalletDbError::ParseColumnValueError")
+            }
+            WalletDbError::RowNotFound => write!(f, "WalletDbError::RowNotFound"),
+            WalletDbError::GenericError => write!(f, "WalletDbError::GenericError"),
+        }
+    }
+}
+
+impl std::error::Error for WalletDbError {}

+ 54 - 0
bin/drk/src/lib.rs

@@ -0,0 +1,54 @@
+/* This file is part of DarkFi (https://dark.fi)
+ *
+ * Copyright (C) 2020-2024 Dyne.org foundation
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <https://www.gnu.org/licenses/>.
+ */
+
+/// Main CLI-util structure
+mod drk;
+pub use drk::Drk;
+
+/// Error codes
+pub mod error;
+
+/// darkfid JSON-RPC related methods
+pub mod rpc;
+
+/// Payment methods
+pub mod transfer;
+
+/// Swap methods
+pub mod swap;
+
+/// Token methods
+pub mod token;
+
+/// CLI utility functions
+pub mod cli_util;
+
+/// Wallet functionality related to Money
+pub mod money;
+
+/// Wallet functionality related to Dao
+pub mod dao;
+
+/// Wallet functionality related to Deployooor
+pub mod deploy;
+
+/// Wallet functionality related to transactions history
+pub mod txs_history;
+
+/// Wallet database operations handler
+pub mod walletdb;

+ 8 - 119
bin/drk/src/main.rs

@@ -17,12 +17,10 @@
  */
  */
 
 
 use std::{
 use std::{
-    fs,
     io::{stdin, Read},
     io::{stdin, Read},
     process::exit,
     process::exit,
     str::FromStr,
     str::FromStr,
     sync::Arc,
     sync::Arc,
-    time::Instant,
 };
 };
 
 
 use prettytable::{format, row, Table};
 use prettytable::{format, row, Table};
@@ -33,7 +31,6 @@ use url::Url;
 
 
 use darkfi::{
 use darkfi::{
     async_daemonize, cli_desc,
     async_daemonize, cli_desc,
-    rpc::{client::RpcClient, jsonrpc::JsonRequest, util::JsonValue},
     util::{
     util::{
         encoding::base64,
         encoding::base64,
         parse::{decode_base10, encode_base10},
         parse::{decode_base10, encode_base10},
@@ -53,46 +50,16 @@ use darkfi_sdk::{
 };
 };
 use darkfi_serial::{deserialize_async, serialize_async};
 use darkfi_serial::{deserialize_async, serialize_async};
 
 
-/// Error codes
-mod error;
-
-/// darkfid JSON-RPC related methods
-mod rpc;
-
-/// Payment methods
-mod transfer;
-
-/// Swap methods
-mod swap;
-use swap::PartialSwapData;
-
-/// Token methods
-mod token;
-
-/// CLI utility functions
-mod cli_util;
-use cli_util::{
-    generate_completions, kaching, parse_token_pair, parse_tx_from_stdin, parse_value_pair,
+use drk::{
+    cli_util::{
+        generate_completions, kaching, parse_token_pair, parse_tx_from_stdin, parse_value_pair,
+    },
+    dao::{DaoParams, ProposalRecord},
+    money::BALANCE_BASE10_DECIMALS,
+    swap::PartialSwapData,
+    Drk,
 };
 };
 
 
-/// Wallet functionality related to Money
-mod money;
-use money::BALANCE_BASE10_DECIMALS;
-
-/// Wallet functionality related to Dao
-mod dao;
-use dao::{DaoParams, ProposalRecord};
-
-/// Wallet functionality related to Deployooor
-mod deploy;
-
-/// Wallet functionality related to transactions history
-mod txs_history;
-
-/// Wallet database operations handler
-mod walletdb;
-use walletdb::{WalletDb, WalletPtr};
-
 const CONFIG_FILE: &str = "drk_config.toml";
 const CONFIG_FILE: &str = "drk_config.toml";
 const CONFIG_FILE_CONTENTS: &str = include_str!("../drk_config.toml");
 const CONFIG_FILE_CONTENTS: &str = include_str!("../drk_config.toml");
 
 
@@ -548,84 +515,6 @@ enum ContractSubcmd {
     },
     },
 }
 }
 
 
-/// CLI-util structure
-pub struct Drk {
-    /// Wallet database operations handler
-    pub wallet: WalletPtr,
-    /// JSON-RPC client to execute requests to darkfid daemon
-    pub rpc_client: Option<RpcClient>,
-}
-
-impl Drk {
-    async fn new(
-        wallet_path: String,
-        wallet_pass: String,
-        endpoint: Option<Url>,
-        ex: Arc<smol::Executor<'static>>,
-    ) -> Result<Self> {
-        // Script kiddies protection
-        if wallet_pass == "changeme" {
-            eprintln!("Please don't use default wallet password...");
-            exit(2);
-        }
-
-        // Initialize wallet
-        let wallet_path = expand_path(&wallet_path)?;
-        if !wallet_path.exists() {
-            if let Some(parent) = wallet_path.parent() {
-                fs::create_dir_all(parent)?;
-            }
-        }
-        let wallet = match WalletDb::new(Some(wallet_path), Some(&wallet_pass)) {
-            Ok(w) => w,
-            Err(e) => {
-                eprintln!("Error initializing wallet: {e:?}");
-                exit(2);
-            }
-        };
-
-        // Initialize rpc client
-        let rpc_client = if let Some(endpoint) = endpoint {
-            Some(RpcClient::new(endpoint, ex).await?)
-        } else {
-            None
-        };
-
-        Ok(Self { wallet, rpc_client })
-    }
-
-    /// Initialize wallet with tables for drk
-    fn initialize_wallet(&self) -> Result<()> {
-        let wallet_schema = include_str!("../wallet.sql");
-        if let Err(e) = self.wallet.exec_batch_sql(wallet_schema) {
-            eprintln!("Error initializing wallet: {e:?}");
-            exit(2);
-        }
-
-        Ok(())
-    }
-
-    /// Auxiliary function to ping configured darkfid daemon for liveness.
-    async fn ping(&self) -> Result<()> {
-        println!("Executing ping request to darkfid...");
-        let latency = Instant::now();
-        let req = JsonRequest::new("ping", JsonValue::Array(vec![]));
-        let rep = self.rpc_client.as_ref().unwrap().request(req).await?;
-        let latency = latency.elapsed();
-        println!("Got reply: {rep:?}");
-        println!("Latency: {latency:?}");
-        Ok(())
-    }
-
-    /// Auxiliary function to stop current JSON-RPC client, if its initialized.
-    async fn stop_rpc_client(&self) -> Result<()> {
-        if let Some(ref rpc_client) = self.rpc_client {
-            rpc_client.stop().await;
-        };
-        Ok(())
-    }
-}
-
 async_daemonize!(realmain);
 async_daemonize!(realmain);
 async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
 async fn realmain(args: Args, ex: Arc<smol::Executor<'static>>) -> Result<()> {
     match args.command {
     match args.command {

+ 1 - 1
bin/drk/src/money.rs

@@ -58,9 +58,9 @@ use darkfi_sdk::{
 use darkfi_serial::{deserialize_async, serialize_async, AsyncEncodable};
 use darkfi_serial::{deserialize_async, serialize_async, AsyncEncodable};
 
 
 use crate::{
 use crate::{
+    cli_util::kaching,
     convert_named_params,
     convert_named_params,
     error::{WalletDbError, WalletDbResult},
     error::{WalletDbError, WalletDbResult},
-    kaching,
     walletdb::{WalletSmt, WalletStorage},
     walletdb::{WalletSmt, WalletStorage},
     Drk,
     Drk,
 };
 };