Procházet zdrojové kódy

WIP clean and refactoring according to issue #35

ghassmo před 4 roky
rodič
revize
a591bb526d
46 změnil soubory, kde provedl 516 přidání a 2662 odebrání
  1. 47 629
      Cargo.lock
  2. 3 33
      Cargo.toml
  3. 3 0
      bin/cashier/.gitignore
  4. 61 0
      bin/cashier/Cargo.toml
  5. 12 14
      bin/cashier/example/eth.rs
  6. 1 0
      bin/cashier/src/lib.rs
  7. 82 211
      bin/cashier/src/main.rs
  8. 1 1
      bin/cashier/src/service/bridge.rs
  9. 60 24
      bin/cashier/src/service/btc.rs
  10. 78 29
      bin/cashier/src/service/eth.rs
  11. 16 0
      bin/cashier/src/service/mod.rs
  12. 51 16
      bin/cashier/src/service/sol.rs
  13. 3 0
      bin/drk/.gitignore
  14. 25 0
      bin/drk/Cargo.toml
  15. 3 0
      bin/drk/src/main.rs
  16. 3 0
      bin/gateway/.gitignore
  17. 29 0
      bin/gateway/Cargo.toml
  18. 4 3
      bin/gateway/src/main.rs
  19. 4 4
      src/bin/darkfid.rs
  20. 0 151
      src/bin/darkpulse.rs
  21. 0 379
      src/bin/drk.rs
  22. 1 1
      src/bin/tree.rs
  23. 1 1
      src/bin/tui_ex.rs
  24. 1 1
      src/bin/tx.rs
  25. 1 1
      src/bin/vm.rs
  26. 1 1
      src/bin/vm_burn.rs
  27. 0 11
      src/cli/cli_config.rs
  28. 1 0
      src/cli/mod.rs
  29. 0 53
      src/darkpulse/aes.rs
  30. 0 89
      src/darkpulse/channel.rs
  31. 0 176
      src/darkpulse/cli_option.rs
  32. 0 64
      src/darkpulse/control_message.rs
  33. 0 156
      src/darkpulse/dbsql.rs
  34. 0 21
      src/darkpulse/mod.rs
  35. 0 104
      src/darkpulse/net/messages.rs
  36. 0 2
      src/darkpulse/net/mod.rs
  37. 0 175
      src/darkpulse/net/protocol_slab.rs
  38. 0 1
      src/darkpulse/net/protocols/mod.rs
  39. 0 119
      src/darkpulse/slabs_manager.rs
  40. 0 164
      src/darkpulse/utility.rs
  41. 0 3
      src/lib.rs
  42. 0 16
      src/service/mod.rs
  43. 1 1
      src/util/mod.rs
  44. 17 2
      src/util/path.rs
  45. 3 3
      src/wallet/cashierdb.rs
  46. 3 3
      src/wallet/walletdb.rs

Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 47 - 629
Cargo.lock


+ 3 - 33
Cargo.toml

@@ -9,7 +9,7 @@ license = "AGPL-3.0-only"
 edition = "2021"
 
 [lib]
-name = "drk"
+name = "darkfi"
 
 [dependencies.halo2_gadgets]
 git = "https://github.com/parazyd/halo2_gadgets.git"
@@ -84,43 +84,13 @@ libsqlite3-sys = {version = "0.23.1", features = ["bundled-sqlcipher"]}
 # Used for gatewayd network transport.
 zeromq = {version = "0.3.1", default-features = false, features = ["async-std-runtime", "all-transport"]}
 
-# Cashier Bitcoin dependencies
-bdk = {version = "0.14.0", optional = true}
-bitcoin = {version = "0.27.1", optional = true}
-secp256k1 = {version = "0.20.3", default-features = false, features = ["rand-std"], optional = true}
-
-# Cashier Ethereum dependencies
-hash-db = {version = "0.15.2", optional = true}
-keccak-hasher = {version = "0.15.3", optional = true}
-
-# Cashier Solana dependencies
-solana-client = {version = "1.8.11", optional = true}
-solana-sdk = {version = "1.8.11", optional = true}
-spl-associated-token-account = {version = "1.0.3", features = ["no-entrypoint"], optional = true}
-spl-token = {version = "3.2.0", features = ["no-entrypoint"], optional = true}
-
-# Darkpulse and tui dependencies
-aes-gcm = {version = "0.9.4", optional = true}
-chrono = {version = "0.4.19", optional = true}
-rusqlite = {version = "0.26.3", optional = true}
+#tui dependencies
 crossbeam-channel = { version = "0.5.1", optional = true}
 libc = { version = "0.2.112", optional = true}
 termion = { version = "1.5.6", optional = true}
 
 [features]
-btc = ["bdk", "bitcoin", "secp256k1"]
-eth = ["keccak-hasher", "hash-db"]
-sol = ["solana-sdk", "solana-client", "spl-token", "spl-associated-token-account"]
-darkpulse = ["aes-gcm", "chrono","rusqlite"]
-tui = ["termion", "chrono","libc", "crossbeam-channel"]
-
-[[bin]]         
-name = "darkpulse"    
-required-features = ["darkpulse"]
-
-[[bin]]         
-name = "eth"    
-required-features = ["eth"]
+tui = ["termion", "libc", "crossbeam-channel"]
 
 [[bin]]         
 name = "tui_ex"    

+ 3 - 0
bin/cashier/.gitignore

@@ -0,0 +1,3 @@
+
+/target
+Cargo.lock

+ 61 - 0
bin/cashier/Cargo.toml

@@ -0,0 +1,61 @@
+[package]
+name = "cashier"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+darkfi = {path= "../../"}
+
+# Encoding and parsing
+serde_json = "1.0.72"
+serde = {version = "1.0.130", features = ["derive"]}
+hex = "0.4.3"
+url = "2.2.2"
+
+# Utilities
+clap = { version = "3.0.0", features = ["derive"] }
+log = "0.4.14"
+simplelog = "0.11.1"
+thiserror = "1.0.30"
+rand = "0.8.4"
+num_cpus = "1.13.0"
+lazy_static = "1.4.0"
+anyhow = "1.0.49"
+num-bigint = {version = "0.4.3", features = ["rand", "serde"]}
+
+# Used for Websockets client implementation.
+async-tungstenite = "0.16.0"
+tungstenite = "0.16.0"
+
+# Async
+async-std = "1.10.0"
+async-trait = "0.1.51"
+async-channel = "1.6.1"
+easy-parallel = "3.1.0"
+async-executor = "1.4.1"
+futures = "0.3.17"
+smol = "1.2.5"
+native-tls = "0.2.8"
+async-native-tls = "0.4.0"
+
+# Cashier Bitcoin dependencies
+bdk = {version = "0.14.0", optional = true}
+bitcoin = {version = "0.27.1", optional = true}
+secp256k1 = {version = "0.20.3", default-features = false, features = ["rand-std"], optional = true}
+
+# Cashier Ethereum dependencies
+hash-db = {version = "0.15.2", optional = true}
+keccak-hasher = {version = "0.15.3", optional = true}
+
+# Cashier Solana dependencies
+solana-client = {version = "1.8.11", optional = true}
+solana-sdk = {version = "1.8.11", optional = true}
+spl-associated-token-account = {version = "1.0.3", features = ["no-entrypoint"], optional = true}
+spl-token = {version = "3.2.0", features = ["no-entrypoint"], optional = true}
+
+[features]
+btc = ["bdk", "bitcoin", "secp256k1"]
+eth = ["keccak-hasher", "hash-db"]
+sol = ["solana-sdk", "solana-client", "spl-token", "spl-associated-token-account"]

+ 12 - 14
src/bin/eth.rs → bin/cashier/example/eth.rs

@@ -1,8 +1,8 @@
 use num_bigint::BigUint;
 use simplelog::{ColorChoice, LevelFilter, TermLogger, TerminalMode};
 
-use drk::{
-    service::eth::{erc20_transfer_data, EthClient, EthTx, Keypair},
+use darkfi::{
+    service::eth::{erc20_transfer_data, EthClient, EthTx},
     util::{decode_base10, encode_base10},
     Result,
 };
@@ -19,12 +19,10 @@ async fn main() -> Result<()> {
     let acc = "0x113b6648f34f4d0340d04ff171cbcf0b49d47827".to_string();
     let key = "67cbb73cb293eea5fa2a7025d5479dbd50319010c03fd8821917ad0d9d53276c".to_string();
 
-    let mut eth = EthClient::new(
-        "/home/parazyd/.ethereum/ropsten/geth.ipc".to_string(),
-        String::from("foobar"),
-    );
+    let mut eth = EthClient::new("", "/home/parazyd/.ethereum/ropsten/geth.ipc", "foobar");
 
-    eth.set_main_keypair(&Keypair { private_key: key, public_key: acc.clone() });
+    eth.main_keypair.private_key = key;
+    eth.main_keypair.public_key = acc.clone();
 
     //let key = generate_privkey();
     //let passphrase = "foobar".to_string();
@@ -49,13 +47,13 @@ async fn main() -> Result<()> {
     /*
     // Transfer native ETH
     let tx = EthTx::new(
-        &acc,
-        &dest,
-        None,
-        None,
-        Some(decode_base10("0.051", 18, true)?),
-        None,
-        None,
+    &acc,
+    &dest,
+    None,
+    None,
+    Some(decode_base10("0.051", 18, true)?),
+    None,
+    None,
     );
 
     let rep = eth.send_transaction(&tx, &passphrase).await?;

+ 1 - 0
bin/cashier/src/lib.rs

@@ -0,0 +1 @@
+pub mod service;

+ 82 - 211
src/bin/cashierd.rs → bin/cashier/src/main.rs

@@ -10,7 +10,7 @@ use rand::rngs::OsRng;
 use serde_json::{json, Value};
 use simplelog::{ColorChoice, LevelFilter, TermLogger, TerminalMode};
 
-use drk::{
+use darkfi::{
     blockchain::{rocks::columns, Rocks, RocksColumn},
     circuit::{MintContract, SpendContract},
     cli::{CashierdConfig, CliCashierd, Config},
@@ -23,18 +23,19 @@ use drk::{
         jsonrpc::{error as jsonerr, response as jsonresp, ErrorCode::*, JsonRequest, JsonResult},
         rpcserver::{listen_and_serve, RequestHandler, RpcServerConfig},
     },
-    serial::{deserialize, serialize},
-    service::{bridge, bridge::Bridge},
+    serial::serialize,
     state::State,
     types::DrkTokenId,
     util::{expand_path, generate_id2, join_config_path, parse::truncate, Address, NetworkName},
     wallet::{
-        cashierdb::{CashierDb, TokenKey},
+        cashierdb::CashierDb, 
         walletdb::WalletDb,
     },
     Error, Result,
 };
 
+use cashier::service::{bridge, bridge::Bridge};
+
 fn handle_bridge_error(error_code: u32) -> Result<()> {
     match error_code {
         1 => Err(Error::BridgeError("Not Supported Client".into())),
@@ -55,7 +56,7 @@ struct Cashierd {
     bridge: Arc<Bridge>,
     cashier_wallet: Arc<CashierDb>,
     networks: Vec<Network>,
-    public_key: String,
+    public_key: Address,
     config: CashierdConfig,
 }
 
@@ -81,18 +82,17 @@ impl RequestHandler for Cashierd {
 }
 
 impl Cashierd {
-    async fn new(config: CashierdConfig) -> Result<Self> {
+    async fn new(config: CashierdConfig, public_key: Address) -> Result<Self> {
         debug!(target: "CASHIER DAEMON", "Initialize");
 
         let wallet_path =
             format!("sqlite://{}", expand_path(&config.cashier_wallet_path)?.to_str().unwrap());
-        let cashier_wallet =
-            CashierDb::new(&wallet_path, config.cashier_wallet_password.clone()).await?;
+
+        let cashier_wallet = CashierDb::new(&wallet_path, &config.cashier_wallet_password).await?;
 
         let mut networks = Vec::new();
 
-        let cfg = config.clone();
-        for network in cfg.networks {
+        for network in config.clone().networks {
             networks.push(Network {
                 name: NetworkName::from_str(&network.name)?,
                 blockchain: network.blockchain,
@@ -102,7 +102,7 @@ impl Cashierd {
 
         let bridge = bridge::Bridge::new();
 
-        Ok(Self { bridge, cashier_wallet, networks, public_key: String::from(""), config })
+        Ok(Self { bridge, cashier_wallet, networks, public_key, config })
     }
 
     async fn start(
@@ -111,150 +111,55 @@ impl Cashierd {
         state: Arc<Mutex<State>>,
         executor: Arc<Executor<'_>>,
     ) -> Result<(smol::Task<Result<()>>, smol::Task<Result<()>>)> {
+
         self.cashier_wallet.init_db().await?;
 
+
         for network in self.networks.iter() {
             match network.name {
                 #[cfg(feature = "sol")]
                 NetworkName::Solana => {
                     debug!(target: "CASHIER DAEMON", "Adding solana network");
-                    use drk::service::{sol::SolFailed, SolClient};
-                    use solana_sdk::{signature::Signer, signer::keypair::Keypair};
-
-                    let bridge2 = self.bridge.clone();
-
-                    let main_keypair: Keypair;
-
-                    let main_keypairs =
-                        self.cashier_wallet.get_main_keys(&NetworkName::Solana).await?;
-
-                    if network.keypair.is_empty() {
-                        if main_keypairs.is_empty() {
-                            main_keypair = Keypair::new();
-                            self.cashier_wallet
-                                .put_main_keys(
-                                    &TokenKey {
-                                        secret_key: serialize(&main_keypair),
-                                        public_key: serialize(&main_keypair.pubkey()),
-                                    },
-                                    &NetworkName::Solana,
-                                )
-                                .await?;
-                        } else {
-                            main_keypair =
-                                deserialize(&main_keypairs[main_keypairs.len() - 1].secret_key)?;
-                        }
-                    } else {
-                        let keypair_str = drk::cli::cli_config::load_keypair_to_str(expand_path(
-                            &network.keypair.clone(),
-                        )?)?;
-                        let keypair_bytes: Vec<u8> = serde_json::from_str(&keypair_str)?;
-                        main_keypair = Keypair::from_bytes(&keypair_bytes)
-                            .map_err(|e| SolFailed::Signature(e.to_string()))?;
-                    }
+                    use drk::service::SolClient;
+
+                    let _bridge = self.bridge.clone();
 
-                    let sol_client = SolClient::new(main_keypair, &network.blockchain).await?;
+                    let sol_client = SolClient::new(self.cashier_wallet.clone(), &network.blockchain, &network.keypair).await?;
 
-                    bridge2.add_clients(NetworkName::Solana, sol_client).await?;
+                    _bridge.add_clients(NetworkName::Solana, sol_client).await?;
                 }
 
                 #[cfg(feature = "eth")]
                 NetworkName::Ethereum => {
                     debug!(target: "CASHIER DAEMON", "Adding ethereum network");
-                    use drk::service::{
-                        eth::{generate_privkey, Keypair},
-                        EthClient,
-                    };
 
-                    let bridge2 = self.bridge.clone();
+                    use drk::service::EthClient;
 
-                    let main_keypair: Keypair;
-
-                    let main_keypairs =
-                        self.cashier_wallet.get_main_keys(&NetworkName::Ethereum).await?;
+                    let _bridge = self.bridge.clone();
 
                     let passphrase = self.config.geth_passphrase.clone();
 
                     let mut eth_client = EthClient::new(
-                        expand_path(&self.config.geth_socket)?.to_str().unwrap().into(),
-                        passphrase.clone(),
+                        &network.blockchain,
+                        expand_path(&self.config.geth_socket)?.to_str().unwrap(),
+                        &passphrase,
                     );
 
-                    if main_keypairs.is_empty() {
-                        let main_private_key = generate_privkey();
-                        let main_public_key = eth_client
-                            .import_privkey(&main_private_key, &passphrase)
-                            .await?
-                            .as_str()
-                            .unwrap()
-                            .to_string();
-
-                        self.cashier_wallet
-                            .put_main_keys(
-                                &TokenKey {
-                                    secret_key: serialize(&main_private_key),
-                                    public_key: serialize(&main_public_key),
-                                },
-                                &NetworkName::Ethereum,
-                            )
-                            .await?;
-
-                        main_keypair =
-                            Keypair { private_key: main_private_key, public_key: main_public_key };
-                    } else {
-                        let last_keypair = &main_keypairs[main_keypairs.len() - 1];
-
-                        main_keypair = Keypair {
-                            private_key: deserialize(&last_keypair.secret_key)?,
-                            public_key: deserialize(&last_keypair.public_key)?,
-                        }
-                    }
-
-                    eth_client.set_main_keypair(&main_keypair);
+                    eth_client.setup_keypair(self.cashier_wallet.clone(), &network.keypair).await?;
 
-                    bridge2.add_clients(NetworkName::Ethereum, Arc::new(eth_client)).await?;
+                    _bridge.add_clients(NetworkName::Ethereum, Arc::new(eth_client)).await?;
                 }
 
                 #[cfg(feature = "btc")]
                 NetworkName::Bitcoin => {
                     debug!(target: "CASHIER DAEMON", "Adding bitcoin network");
-                    use drk::service::btc::{BtcClient, BtcFailed, Keypair};
-
-                    let bridge2 = self.bridge.clone();
-
-                    let main_keypair: Keypair;
-
-                    let main_keypairs =
-                        self.cashier_wallet.get_main_keys(&NetworkName::Bitcoin).await?;
-
-                    if network.keypair.is_empty() {
-                        if main_keypairs.is_empty() {
-                            main_keypair = Keypair::new();
-                            self.cashier_wallet
-                                .put_main_keys(
-                                    &TokenKey {
-                                        secret_key: serialize(&main_keypair),
-                                        public_key: serialize(&main_keypair.pubkey()),
-                                    },
-                                    &NetworkName::Bitcoin,
-                                )
-                                .await?;
-                        } else {
-                            main_keypair =
-                                deserialize(&main_keypairs[main_keypairs.len() - 1].secret_key)?;
-                        }
-                    } else {
-                        let keypair_str = drk::cli::cli_config::load_keypair_to_str(expand_path(
-                            &network.keypair.clone(),
-                        )?)?;
-                        let keypair_bytes: Vec<u8> = serde_json::from_str(&keypair_str)?;
-                        main_keypair = Keypair::from_bytes(&keypair_bytes)
-                            .map_err(|e| BtcFailed::DecodeAndEncodeError(e.to_string()))?;
-                    }
+                    use drk::service::btc::BtcClient;
+
+                    let _bridge = self.bridge.clone();
 
-                    let btc_client = BtcClient::new(main_keypair, &network.blockchain).await?;
+                    let btc_client = BtcClient::new(self.cashier_wallet.clone(), &network.blockchain, &network.keypair).await?;
 
-                    bridge2.add_clients(NetworkName::Bitcoin, btc_client).await?;
+                    _bridge.add_clients(NetworkName::Bitcoin, btc_client).await?;
                 }
                 _ => {}
             }
@@ -285,8 +190,8 @@ impl Cashierd {
                     recv_coin.clone(),
                     ex2.clone(),
                 )
-                .await?;
-            }
+                    .await?;
+                }
         });
 
         let bridge2 = self.bridge.clone();
@@ -312,7 +217,7 @@ impl Cashierd {
                             state.clone(),
                         )
                         .await?;
-                }
+                    }
                 Ok(())
             });
 
@@ -352,7 +257,7 @@ impl Cashierd {
                         amount,
                     ),
                 })
-                .await?;
+            .await?;
 
             // receive a response
             let res = bridge_subscribtion.receiver.recv().await?;
@@ -372,7 +277,7 @@ impl Cashierd {
                             &withdraw_token.network,
                         )
                         .await?;
-                }
+                    }
                 _ => {
                     return Err(Error::BridgeError("Receive unknown value from Subscription".into()))
                 }
@@ -436,9 +341,9 @@ impl Cashierd {
         // Check if the features list contains this network
         if !self.networks.iter().any(|net| net.name == network) {
             return JsonResult::Err(jsonerr(
-                InvalidParams,
-                Some(format!("Cashier doesn't support this network: {}", network)),
-                id,
+                    InvalidParams,
+                    Some(format!("Cashier doesn't support this network: {}", network)),
+                    id,
             ))
         }
 
@@ -483,15 +388,15 @@ impl Cashierd {
                         network: network.clone(),
                         payload: bridge::BridgeRequestsPayload::Watch(None),
                     })
-                    .await?;
-            } else {
-                let keypair = check[0].clone();
-                bridge_subscribtion
-                    .sender
-                    .send(bridge::BridgeRequests {
-                        network: network.clone(),
-                        payload: bridge::BridgeRequestsPayload::Watch(Some(keypair)),
-                    })
+                .await?;
+                } else {
+                    let keypair = check[0].clone();
+                    bridge_subscribtion
+                        .sender
+                        .send(bridge::BridgeRequests {
+                            network: network.clone(),
+                            payload: bridge::BridgeRequestsPayload::Watch(Some(keypair)),
+                        })
                     .await?;
             }
 
@@ -561,9 +466,9 @@ impl Cashierd {
         // Check if the features list contains this network
         if !self.networks.iter().any(|net| net.name == network) {
             return JsonResult::Err(jsonerr(
-                InvalidParams,
-                Some(format!("Cashier doesn't support this network: {}", network)),
-                id,
+                    InvalidParams,
+                    Some(format!("Cashier doesn't support this network: {}", network)),
+                    id,
             ))
         }
 
@@ -583,8 +488,8 @@ impl Cashierd {
 
             if let Some(addr) = self
                 .cashier_wallet
-                .get_withdraw_keys_by_token_public_key(&address, &network)
-                .await?
+                    .get_withdraw_keys_by_token_public_key(&address, &network)
+                    .await?
             {
                 cashier_public = addr.public;
             } else {
@@ -640,7 +545,7 @@ impl Cashierd {
         {
             "server_version": env!("CARGO_PKG_VERSION"),
             "protocol_version": "1.0",
-            "public_key": self.public_key,
+            "public_key": self.public_key.to_string(),
             "networks": [],
             "hosts": {
                 "tcp_port": tcp_port,
@@ -669,12 +574,10 @@ async fn start(
     config: &CashierdConfig,
     get_address_flag: bool,
 ) -> Result<()> {
-    let mut cashierd = Cashierd::new(config.clone()).await?;
-
     let client_wallet_path =
         format!("sqlite://{}", expand_path(&config.client_wallet_path)?.to_str().unwrap());
-    let client_wallet =
-        WalletDb::new(&client_wallet_path, config.client_wallet_password.clone()).await?;
+
+    let client_wallet = WalletDb::new(&client_wallet_path, &config.client_wallet_password).await?;
 
     let rocks = Rocks::new(expand_path(&config.database_path.clone())?.as_path())?;
 
@@ -683,37 +586,42 @@ async fn start(
     info!("Building verifying key for the spend contract...");
     let spend_vk = VerifyingKey::build(11, SpendContract::default());
 
-    let client = Client::new(
-        rocks.clone(),
-        (config.gateway_protocol_url.parse()?, config.gateway_publisher_url.parse()?),
-        client_wallet.clone(),
-    )
-    .await?;
+    // new Client
+    let gateway_urls =
+        (config.gateway_protocol_url.parse()?, config.gateway_publisher_url.parse()?);
+    let client = Client::new(rocks.clone(), gateway_urls, client_wallet.clone()).await?;
 
     let tree = client.get_tree().await?;
     let merkle_roots = RocksColumn::<columns::MerkleRoots>::new(rocks.clone());
     let nullifiers = RocksColumn::<columns::Nullifiers>::new(rocks);
 
+    // get cashier public key
     let cashier_public = client.main_keypair.public;
-    let cashier_public_str = Address::from(cashier_public).to_string();
-    cashierd.public_key = cashier_public_str.clone();
 
-    let cashier_public_keys = vec![cashier_public];
+    // new Cashier daemon
+    let mut cashierd = Cashierd::new(config.clone(), Address::from(cashier_public)).await?;
+
+    // this will print the cashier public key and exit
+    if get_address_flag {
+        info!("Public Key: {}", cashierd.public_key);
+        return Ok(())
+    };
 
+    // new State
+    let public_keys = vec![cashier_public];
     let state = Arc::new(Mutex::new(State {
         tree,
         merkle_roots,
         nullifiers,
-        public_keys: cashier_public_keys,
+        public_keys,
         mint_vk,
         spend_vk,
     }));
 
-    if get_address_flag {
-        info!("Public Key: {}", cashier_public_str);
-        return Ok(())
-    };
+    // start cashier
+    let (t1, t2) = cashierd.start(client, state, executor.clone()).await?;
 
+    // config for rpc
     let cfg = RpcServerConfig {
         socket_addr: config.rpc_listen_address,
         use_tls: config.serve_tls,
@@ -721,7 +629,7 @@ async fn start(
         identity_pass: config.tls_identity_password.clone(),
     };
 
-    let (t1, t2) = cashierd.start(client, state, executor.clone()).await?;
+    // listen and serve RPC
     listen_and_serve(cfg, Arc::new(cashierd), executor).await?;
 
     t1.cancel().await;
@@ -760,26 +668,27 @@ async fn main() -> Result<()> {
 
     if args.refresh {
         info!(target: "CASHIER DAEMON", "Refresh the wallet and the database");
+
+        // refresh cashier's client wallet
         let client_wallet_path =
             format!("sqlite://{}", expand_path(&config.client_wallet_path)?.to_str().unwrap());
         let client_wallet =
-            WalletDb::new(&client_wallet_path, config.client_wallet_password.clone()).await?;
-
+            WalletDb::new(&client_wallet_path, &config.client_wallet_password).await?;
         client_wallet.remove_own_coins().await?;
 
+        // refresh cashier wallet
         let wallet_path =
             format!("sqlite://{}", expand_path(&config.cashier_wallet_path)?.to_str().unwrap());
-        let wallet = CashierDb::new(&wallet_path, config.cashier_wallet_password.clone()).await?;
-
+        let wallet = CashierDb::new(&wallet_path, &config.cashier_wallet_password).await?;
         wallet.remove_withdraw_and_deposit_keys().await?;
 
+        // refresh rocks database
         if let Some(path) = expand_path(&config.database_path)?.to_str() {
             info!(target: "CASHIER DAEMON", "Remove database: {}", path);
             std::fs::remove_dir_all(path)?;
         }
 
         info!("Wallet updated successfully.");
-
         return Ok(())
     }
 
@@ -800,47 +709,9 @@ async fn main() -> Result<()> {
             smol::future::block_on(async move {
                 start(ex2, &config, get_address_flag).await?;
                 drop(signal);
-                Ok::<(), drk::Error>(())
+                Ok::<(), darkfi::Error>(())
             })
         });
 
     result
 }
-
-// async fn resume_watch_deposit_keys(
-//     bridge: Arc<Bridge>,
-//     cashier_wallet: Arc<CashierDb>,
-//     networks: Vec<Network>,
-//     executor: Arc<Executor<'_>>,
-// ) -> Result<()> {
-//     debug!(target: "CASHIER DAEMON", "Resume watch deposit keys");
-
-//     for network in networks.iter() {
-//         let keypairs_to_watch =
-//             cashier_wallet.get_deposit_token_keys_by_network(&network.name)?;
-
-//         for deposit_token in keypairs_to_watch {
-//             let bridge = bridge.clone();
-
-//             let bridge_subscribtion = bridge
-//                 .subscribe(
-//                     deposit_token.drk_public_key,
-//                     Some(deposit_token.mint_address),
-//                     executor.clone(),
-//                 )
-//                 .await;
-
-//             bridge_subscribtion
-//                 .sender
-//                 .send(bridge::BridgeRequests {
-//                     network: network.name.clone(),
-//                     payload: bridge::BridgeRequestsPayload::Watch(Some(
-//                         deposit_token.token_key,
-//                     )),
-//                 })
-//                 .await?;
-//         }
-//     }
-
-//     Ok(())
-// }

+ 1 - 1
src/service/bridge.rs → bin/cashier/src/service/bridge.rs

@@ -6,7 +6,7 @@ use async_trait::async_trait;
 use futures::stream::{FuturesUnordered, StreamExt};
 use log::{debug, error};
 
-use crate::{
+use darkfi::{
     crypto::keypair::PublicKey, types::*, util::NetworkName, wallet::cashierdb::TokenKey, Error,
     Result,
 };

+ 60 - 24
src/service/btc.rs → bin/cashier/src/service/btc.rs

@@ -41,10 +41,11 @@ use secp256k1::{
 };
 
 use super::bridge::{NetworkClient, TokenNotification, TokenSubscribtion};
-use crate::{
+use darkfi::{
     crypto::keypair::PublicKey as DrkPublicKey,
     serial::{deserialize, serialize, Decodable, Encodable},
-    util::{generate_id2, NetworkName},
+    util::{generate_id2, NetworkName, load_keypair_to_str, expand_path},
+    wallet::cashierdb::{CashierDb, TokenKey},
     Error, Result,
 };
 
@@ -228,7 +229,7 @@ impl Client {
         let _client = ElectrumClient::from_config(electrum_url, config)?;
 
         let electrum = ElectrumClient::new(electrum_url)
-            .map_err(|err| crate::Error::from(super::BtcFailed::from(err)))?;
+            .map_err(|err| darkfi::Error::from(super::BtcFailed::from(err)))?;
 
         let latest_block = electrum.block_headers_subscribe()?;
 
@@ -239,10 +240,10 @@ impl Client {
             electrum,
             subscriptions: Vec::new(),
             latest_block_height: BlockHeight::try_from(latest_block)
-                .map_err(|_| crate::Error::TryFromError)?,
-            last_sync: Instant::now(),
-            sync_interval: interval,
-            script_history: Default::default(),
+                .map_err(|_| darkfi::Error::TryFromError)?,
+                last_sync: Instant::now(),
+                sync_interval: interval,
+                script_history: Default::default(),
         })
     }
     fn update_state(&mut self) -> Result<()> {
@@ -306,8 +307,8 @@ impl Client {
                     Ok(ScriptStatus::InMempool)
                 } else {
                     Ok(ScriptStatus::Confirmed(Confirmed::from_inclusion_and_latest_block(
-                        u32::try_from(last.height).map_err(|_| crate::Error::TryFromError)?,
-                        u32::from(self.latest_block_height),
+                                u32::try_from(last.height).map_err(|_| darkfi::Error::TryFromError)?,
+                                u32::from(self.latest_block_height),
                     )))
                 }
             }
@@ -319,10 +320,42 @@ pub struct BtcClient {
     client: Arc<Mutex<Client>>,
     notify_channel:
         (async_channel::Sender<TokenNotification>, async_channel::Receiver<TokenNotification>),
-    network: Network,
+        network: Network,
 }
 impl BtcClient {
-    pub async fn new(main_keypair: Keypair, network: &str) -> Result<Arc<Self>> {
+    pub async fn new(cashier_wallet: Arc<CashierDb>, network: &str, keypair_path: &str) -> Result<Arc<Self>> {
+
+        let main_keypair: Keypair;
+
+        let main_keypairs =
+            cashier_wallet.get_main_keys(&NetworkName::Bitcoin).await?;
+
+        if keypair_path.is_empty() {
+            if main_keypairs.is_empty() {
+                main_keypair = Keypair::new();
+                cashier_wallet
+                    .put_main_keys(
+                        &TokenKey {
+                            secret_key: serialize(&main_keypair),
+                            public_key: serialize(&main_keypair.pubkey()),
+                        },
+                        &NetworkName::Bitcoin,
+                    )
+                    .await?;
+                } else {
+                    main_keypair =
+                        deserialize(&main_keypairs[main_keypairs.len() - 1].secret_key)?;
+            }
+        } else {
+            let keypair_str = load_keypair_to_str(expand_path(
+                    &keypair_path,
+            )?)?;
+            let keypair_bytes: Vec<u8> = serde_json::from_str(&keypair_str)?;
+            main_keypair = Keypair::from_bytes(&keypair_bytes)
+                .map_err(|e| BtcFailed::DecodeAndEncodeError(e.to_string()))?;
+            }
+
+
         let notify_channel = async_channel::unbounded();
 
         let (network, url) = match network {
@@ -417,7 +450,7 @@ impl BtcClient {
                 received_balance: amnt as u64,
                 decimals: 8,
             })
-            .await
+        .await
             .map_err(Error::from)?;
 
         info!(target: "BTC BRIDGE", "Received {} btc", ui_amnt);
@@ -523,7 +556,7 @@ impl NetworkClient for BtcClient {
                     error!(target: "BTC BRIDGE SUBSCRIPTION","{}", e.to_string());
                 }
             })
-            .detach();
+        .detach();
 
         Ok(TokenSubscribtion { private_key, public_key })
     }
@@ -547,7 +580,7 @@ impl NetworkClient for BtcClient {
                     error!(target: "BTC BRIDGE SUBSCRIPTION","{}", e.to_string());
                 }
             })
-            .detach();
+        .detach();
 
         Ok(public_key)
     }
@@ -739,7 +772,7 @@ impl Decodable for bitcoin::Address {
     fn decode<D: std::io::Read>(mut d: D) -> Result<Self> {
         let addr: String = Decodable::decode(&mut d)?;
         let addr = bitcoin::Address::from_str(&addr)
-            .map_err(|err| crate::Error::from(BtcFailed::from(err)))?;
+            .map_err(|err| darkfi::Error::from(BtcFailed::from(err)))?;
         Ok(addr)
     }
 }
@@ -756,7 +789,7 @@ impl Decodable for bitcoin::PublicKey {
     fn decode<D: std::io::Read>(mut d: D) -> Result<Self> {
         let key: Vec<u8> = Decodable::decode(&mut d)?;
         let key = bitcoin::PublicKey::from_slice(&key)
-            .map_err(|err| crate::Error::from(BtcFailed::from(err)))?;
+            .map_err(|err| darkfi::Error::from(BtcFailed::from(err)))?;
         Ok(key)
     }
 }
@@ -773,7 +806,7 @@ impl Decodable for bitcoin::PrivateKey {
     fn decode<D: std::io::Read>(mut d: D) -> Result<Self> {
         let key: String = Decodable::decode(&mut d)?;
         let key = bitcoin::PrivateKey::from_str(&key)
-            .map_err(|err| crate::Error::from(BtcFailed::from(err)))?;
+            .map_err(|err| darkfi::Error::from(BtcFailed::from(err)))?;
         Ok(key)
     }
 }
@@ -788,7 +821,7 @@ impl Decodable for secp256k1::key::PublicKey {
     fn decode<D: std::io::Read>(mut d: D) -> Result<Self> {
         let key: Vec<u8> = Decodable::decode(&mut d)?;
         let key = secp256k1::key::PublicKey::from_slice(&key)
-            .map_err(|err| crate::Error::from(BtcFailed::from(err)))?;
+            .map_err(|err| darkfi::Error::from(BtcFailed::from(err)))?;
         Ok(key)
     }
 }
@@ -805,7 +838,7 @@ impl Decodable for Keypair {
     fn decode<D: std::io::Read>(mut d: D) -> Result<Self> {
         let key: Vec<u8> = Decodable::decode(&mut d)?;
         let key = Keypair::from_bytes(key.as_slice()).map_err(|_| {
-            crate::Error::from(BtcFailed::DecodeAndEncodeError("load keypair from slice".into()))
+            darkfi::Error::from(BtcFailed::DecodeAndEncodeError("load keypair from slice".into()))
         })?;
         Ok(key)
     }
@@ -829,8 +862,8 @@ pub enum BtcFailed {
     Notification(String),
 }
 
-impl From<crate::error::Error> for BtcFailed {
-    fn from(err: crate::error::Error) -> BtcFailed {
+impl From<darkfi::error::Error> for BtcFailed {
+    fn from(err: darkfi::error::Error) -> BtcFailed {
         BtcFailed::BtcError(err.to_string())
     }
 }
@@ -866,11 +899,14 @@ pub type BtcResult<T> = std::result::Result<T, BtcFailed>;
 #[cfg(test)]
 mod tests {
 
-    use super::Keypair;
-    use crate::serial::{deserialize, serialize};
-    use secp256k1::constants::{PUBLIC_KEY_SIZE, SECRET_KEY_SIZE};
     use std::str::FromStr;
 
+    use secp256k1::constants::{PUBLIC_KEY_SIZE, SECRET_KEY_SIZE};
+
+    use darkfi::serial::{deserialize, serialize};
+
+    use super::Keypair;
+
     const KEYPAIR_LENGTH: usize = SECRET_KEY_SIZE + PUBLIC_KEY_SIZE;
 
     #[test]

+ 78 - 29
src/service/eth.rs → bin/cashier/src/service/eth.rs

@@ -13,11 +13,12 @@ use serde_json::{json, Value};
 
 use super::bridge::{NetworkClient, TokenNotification, TokenSubscribtion};
 
-use crate::{
+use darkfi::{
     crypto::keypair::PublicKey,
     rpc::{jsonrpc, jsonrpc::JsonResult},
     serial::{deserialize, serialize, Decodable, Encodable},
     util::{generate_id2, parse::truncate, sleep, NetworkName},
+    wallet::cashierdb::{CashierDb, TokenKey},
     Error, Result,
 };
 
@@ -189,7 +190,7 @@ impl EthTx {
 // INFO [10-25|19:47:32.845] IPC endpoint opened: url=/home/x/.ethereum/ropsten/geth.ipc
 //
 pub struct EthClient {
-    main_keypair: Keypair,
+    pub main_keypair: Keypair,
     passphrase: String,
     socket_path: String,
     subscriptions: Arc<Mutex<Vec<String>>>,
@@ -198,21 +199,69 @@ pub struct EthClient {
 }
 
 impl EthClient {
-    pub fn new(socket_path: String, passphrase: String) -> Self {
+    pub fn new(_network: &str, socket_path: &str, passphrase: &str) -> Self {
+
         let notify_channel = async_channel::unbounded();
+
         let subscriptions = Arc::new(Mutex::new(Vec::new()));
+
+
+        let main_keypair = Keypair{ public_key: "".into(), private_key: "".into()};
+
         Self {
-            // This must be set by the cashier
-            main_keypair: Keypair { private_key: String::new(), public_key: String::new() },
-            passphrase,
-            socket_path,
+            main_keypair,
+            passphrase: passphrase.into(),
+            socket_path: socket_path.into(),
             subscriptions,
             notify_channel,
         }
     }
 
-    pub fn set_main_keypair(&mut self, keypair: &Keypair) {
-        self.main_keypair = keypair.clone();
+    pub async fn setup_keypair(
+        &mut self,
+        cashier_wallet: Arc<CashierDb>, 
+        _keypair_path: &str
+    ) -> Result<()> {
+
+        let main_keypair: Keypair;
+
+        let main_keypairs =
+            cashier_wallet.get_main_keys(&NetworkName::Ethereum).await?;
+
+        if main_keypairs.is_empty() {
+            let main_private_key = generate_privkey();
+            let main_public_key = self
+                .import_privkey(&main_private_key)
+                .await?
+                .as_str()
+                .unwrap()
+                .to_string();
+
+            cashier_wallet
+                .put_main_keys(
+                    &TokenKey {
+                        secret_key: serialize(&main_private_key),
+                        public_key: serialize(&main_public_key),
+                    },
+                    &NetworkName::Ethereum,
+                )
+                .await?;
+
+            main_keypair =
+                Keypair { private_key: main_private_key, public_key: main_public_key };
+
+        } else {
+            let last_keypair = &main_keypairs[main_keypairs.len() - 1];
+
+            main_keypair = Keypair {
+                private_key: deserialize(&last_keypair.secret_key)?,
+                public_key: deserialize(&last_keypair.public_key)?,
+            }
+        }
+
+        self.main_keypair = main_keypair;
+
+        Ok(())
     }
 
     async fn send_eth_to_main_wallet(&self, acc: &str, amount: BigUint) -> Result<()> {
@@ -248,7 +297,7 @@ impl EthClient {
             if sub_iter > 60 * 10 {
                 // 10 minutes
                 self.unsubscribe(&addr).await;
-                return Err(crate::Error::ClientFailed("Deposit for expired".into()))
+                return Err(darkfi::Error::ClientFailed("Deposit for expired".into()))
             }
 
             sub_iter += iter_interval;
@@ -266,8 +315,8 @@ impl EthClient {
         self.unsubscribe(&addr).await;
 
         if current_balance < prev_balance {
-            return Err(crate::Error::ClientFailed(
-                "New balance is less than previous balance".into(),
+            return Err(darkfi::Error::ClientFailed(
+                    "New balance is less than previous balance".into(),
             ))
         }
 
@@ -284,7 +333,7 @@ impl EthClient {
                 received_balance: received_balance.to_u64_digits()[0],
                 decimals: decimals as u16,
             })
-            .await
+        .await
             .map_err(Error::from)?;
 
         self.send_eth_to_main_wallet(&addr, received_balance).await?;
@@ -308,10 +357,10 @@ impl EthClient {
         let reply: JsonResult = match jsonrpc::send_unix_request(&self.socket_path, json!(r))
             .await
             .map_err(EthFailed::from)
-        {
-            Ok(v) => v,
-            Err(e) => return Err(e),
-        };
+            {
+                Ok(v) => v,
+                Err(e) => return Err(e),
+            };
 
         match reply {
             JsonResult::Resp(r) => {
@@ -331,17 +380,17 @@ impl EthClient {
         }
     }
 
-    pub async fn import_privkey(&self, key: &str, passphrase: &str) -> EthResult<Value> {
-        let req = jsonrpc::request(json!("personal_importRawKey"), json!([key, passphrase]));
+    pub async fn import_privkey(&self, key: &str,) -> EthResult<Value> {
+        let req = jsonrpc::request(json!("personal_importRawKey"), json!([key, self.passphrase]));
         Ok(self.request(req).await?)
     }
 
     /*
-    pub async fn estimate_gas(&self, tx: &EthTx) -> Result<Value> {
-    let req = jsonrpc::request(json!("eth_estimateGas"), json!([tx]));
-    Ok(self.request(req).await?)
-    }
-    */
+       pub async fn estimate_gas(&self, tx: &EthTx) -> Result<Value> {
+       let req = jsonrpc::request(json!("eth_estimateGas"), json!([tx]));
+       Ok(self.request(req).await?)
+       }
+       */
 
     pub async fn block_number(&self) -> EthResult<Value> {
         let req = jsonrpc::request(json!("eth_blockNumber"), json!([]));
@@ -388,7 +437,7 @@ impl NetworkClient for EthClient {
     ) -> Result<TokenSubscribtion> {
         let private_key = generate_privkey();
 
-        let addr = self.import_privkey(&private_key, &self.passphrase).await?;
+        let addr = self.import_privkey(&private_key).await?;
 
         let address: String = if addr.as_str().is_some() {
             addr.as_str().unwrap().to_string()
@@ -404,7 +453,7 @@ impl NetworkClient for EthClient {
                     error!(target: "ETH BRIDGE SUBSCRIPTION","{}", e.to_string());
                 }
             })
-            .detach();
+        .detach();
 
         let private_key: Vec<u8> = serialize(&private_key);
 
@@ -429,7 +478,7 @@ impl NetworkClient for EthClient {
                     error!(target: "ETH BRIDGE SUBSCRIPTION","{}", e.to_string());
                 }
             })
-            .detach();
+        .detach();
 
         Ok(public_key)
     }
@@ -492,8 +541,8 @@ pub enum EthFailed {
     ImportPrivateError,
 }
 
-impl From<crate::error::Error> for EthFailed {
-    fn from(err: crate::error::Error) -> EthFailed {
+impl From<darkfi::Error> for EthFailed {
+    fn from(err: darkfi::Error) -> EthFailed {
         EthFailed::EthClientError(err.to_string())
     }
 }

+ 16 - 0
bin/cashier/src/service/mod.rs

@@ -0,0 +1,16 @@
+pub mod bridge;
+
+#[cfg(feature = "btc")]
+pub mod btc;
+#[cfg(feature = "btc")]
+pub use btc::{Account, BtcFailed, BtcResult, Keypair, PubAddress};
+
+#[cfg(feature = "sol")]
+pub mod sol;
+#[cfg(feature = "sol")]
+pub use sol::{SolClient, SolFailed, SolResult};
+
+#[cfg(feature = "eth")]
+pub mod eth;
+#[cfg(feature = "eth")]
+pub use eth::{EthClient, EthFailed, EthResult};

+ 51 - 16
src/service/sol.rs → bin/cashier/src/service/sol.rs

@@ -12,9 +12,9 @@ use solana_client::{blockhash_query::BlockhashQuery, rpc_client::RpcClient};
 use solana_sdk::{
     native_token::{lamports_to_sol, sol_to_lamports},
     program_pack::Pack,
-    pubkey::Pubkey,
+    pubkey::Pubkey as SolPubkey,
     signature::{Signature, Signer},
-    signer::keypair::Keypair,
+    signer::keypair::Keypair as SolKeypair,
     system_instruction,
     transaction::Transaction,
 };
@@ -23,16 +23,21 @@ use tungstenite::Message;
 
 use super::bridge::{NetworkClient, TokenNotification, TokenSubscribtion};
 
-use crate::{
+use darkfi::{
     crypto::keypair::PublicKey,
     rpc::{jsonrpc, jsonrpc::JsonResult, websockets, websockets::WsStream},
     serial::{deserialize, serialize, Decodable, Encodable},
-    util::{generate_id2, parse::truncate, sleep, NetworkName},
+    util::{generate_id2, parse::truncate, sleep, NetworkName, expand_path, load_keypair_to_str},
     Error, Result,
+    wallet::cashierdb::{TokenKey, CashierDb},
 };
 
 pub const SOL_NATIVE_TOKEN_ID: &str = "So11111111111111111111111111111111111111112";
 
+
+struct Keypair(SolKeypair);
+struct Pubkey(SolPubkey);
+
 #[derive(Serialize)]
 struct SubscribeParams {
     encoding: Value,
@@ -45,14 +50,43 @@ pub struct SolClient {
     subscriptions: Arc<Mutex<Vec<Pubkey>>>,
     notify_channel:
         (async_channel::Sender<TokenNotification>, async_channel::Receiver<TokenNotification>),
-    rpc_server: &'static str,
-    wss_server: &'static str,
+        rpc_server: &'static str,
+        wss_server: &'static str,
 }
 
 impl SolClient {
-    pub async fn new(main_keypair: Keypair, network: &str) -> Result<Arc<Self>> {
+    pub async fn new(cashier_wallet: Arc<CashierDb>, network: &str, keypair_path: &str) -> Result<Arc<Self>> {
         let notify_channel = async_channel::unbounded();
 
+        let main_keypair: Keypair;
+
+        let main_keypairs = cashier_wallet.get_main_keys(&NetworkName::Solana).await?;
+
+        if keypair_path.is_empty() {
+            if main_keypairs.is_empty() {
+                main_keypair = Keypair::new();
+                cashier_wallet
+                    .put_main_keys(
+                        &TokenKey {
+                            secret_key: serialize(&main_keypair),
+                            public_key: serialize(&main_keypair.pubkey()),
+                        },
+                        &NetworkName::Solana,
+                    )
+                    .await?;
+                } else {
+                    main_keypair =
+                        deserialize(&main_keypairs[main_keypairs.len() - 1].secret_key)?;
+            }
+        } else {
+            let keypair_str =
+                load_keypair_to_str(expand_path(keypair_path)?)?;
+
+            let keypair_bytes: Vec<u8> = serde_json::from_str(&keypair_str)?;
+            main_keypair = Keypair::from_bytes(&keypair_bytes)
+                .map_err(|e| SolFailed::Signature(e.to_string()))?;
+            }
+
         info!(target: "SOL BRIDGE", "Main SOL wallet pubkey: {:?}", &main_keypair.pubkey());
 
         let (rpc_server, wss_server) = match network {
@@ -206,8 +240,8 @@ impl SolClient {
                             .unwrap()
                             .parse()
                             .map_err(Error::from)?;
-                    } else {
-                        cur_balance = params["lamports"].as_u64().unwrap();
+                        } else {
+                            cur_balance = params["lamports"].as_u64().unwrap();
                     }
                     break
                 }
@@ -236,7 +270,7 @@ impl SolClient {
                     received_balance: amnt,
                     decimals: decimals as u16,
                 })
-                .await
+            .await
                 .map_err(Error::from)?;
 
             info!(target: "SOL BRIDGE", "Received {} {:?} tokens", ui_amnt, mint.unwrap());
@@ -252,7 +286,7 @@ impl SolClient {
                     received_balance: amnt,
                     decimals: decimals as u16,
                 })
-                .await
+            .await
                 .map_err(Error::from)?;
 
             info!(target: "SOL BRIDGE", "Received {} SOL", ui_amnt);
@@ -421,7 +455,7 @@ impl NetworkClient for SolClient {
                     error!(target: "SOL BRIDGE SUBSCRIPTION","{}", e.to_string());
                 }
             })
-            .detach();
+        .detach();
 
         Ok(TokenSubscribtion { private_key, public_key })
     }
@@ -454,7 +488,7 @@ impl NetworkClient for SolClient {
                     error!(target: "SOL BRIDGE SUBSCRIPTION","{}", e.to_string());
                 }
             })
-            .detach();
+        .detach();
 
         Ok(public_key)
     }
@@ -555,12 +589,13 @@ impl Decodable for Keypair {
     fn decode<D: std::io::Read>(mut d: D) -> Result<Self> {
         let key: Vec<u8> = Decodable::decode(&mut d)?;
         let key = Keypair::from_bytes(key.as_slice()).map_err(|_| {
-            crate::Error::from(SolFailed::DecodeAndEncodeError("load keypair from slice".into()))
+            darkfi::Error::from(SolFailed::DecodeAndEncodeError("load keypair from slice".into()))
         })?;
         Ok(key)
     }
 }
 
+
 impl Encodable for Pubkey {
     fn encode<S: std::io::Write>(&self, s: S) -> Result<usize> {
         let key = self.to_string();
@@ -573,7 +608,7 @@ impl Decodable for Pubkey {
     fn decode<D: std::io::Read>(mut d: D) -> Result<Self> {
         let key: String = Decodable::decode(&mut d)?;
         let key = Pubkey::try_from(key.as_str()).map_err(|_| {
-            crate::Error::from(SolFailed::DecodeAndEncodeError("load public key from slice".into()))
+            darkfi::Error::from(SolFailed::DecodeAndEncodeError("load public key from slice".into()))
         })?;
         Ok(key)
     }
@@ -608,7 +643,7 @@ pub enum SolFailed {
     #[error("Signature Error: `{0}`")]
     Signature(String),
     #[error(transparent)]
-    Darkfi(#[from] crate::error::Error),
+    Darkfi(#[from] darkfi::error::Error),
 }
 
 pub type SolResult<T> = std::result::Result<T, SolFailed>;

+ 3 - 0
bin/drk/.gitignore

@@ -0,0 +1,3 @@
+
+/target
+Cargo.lock

+ 25 - 0
bin/drk/Cargo.toml

@@ -0,0 +1,25 @@
+[package]
+name = "drk"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+darkfi = {path= "../../"}
+
+# Async
+async-std = "1.10.0"
+async-channel = "1.6.1"
+easy-parallel = "3.1.0"
+async-executor = "1.4.1"
+futures = "0.3.17"
+smol = "1.2.5"
+
+# Utilities
+clap = { version = "3.0.0", features = ["derive"] }
+log = "0.4.14"
+num_cpus = "1.13.0"
+simplelog = "0.11.1"
+thiserror = "1.0.30"
+prettytable-rs = "0.8.0"

+ 3 - 0
bin/drk/src/main.rs

@@ -0,0 +1,3 @@
+fn main() {
+    println!("Hello, world!");
+}

+ 3 - 0
bin/gateway/.gitignore

@@ -0,0 +1,3 @@
+
+/target
+Cargo.lock

+ 29 - 0
bin/gateway/Cargo.toml

@@ -0,0 +1,29 @@
+[package]
+name = "gateway"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+darkfi = {path= "../../"}
+
+# Async
+async-std = "1.10.0"
+async-channel = "1.6.1"
+easy-parallel = "3.1.0"
+async-executor = "1.4.1"
+futures = "0.3.17"
+smol = "1.2.5"
+
+# Utilities
+clap = { version = "3.0.0", features = ["derive"] }
+log = "0.4.14"
+num_cpus = "1.13.0"
+simplelog = "0.11.1"
+thiserror = "1.0.30"
+rand = "0.8.4"
+
+# Encoding and parsing
+bytes = "1.1.0"
+url = "2.2.2"

+ 4 - 3
src/bin/gatewayd.rs → bin/gateway/src/main.rs

@@ -6,14 +6,15 @@ use easy_parallel::Parallel;
 use log::debug;
 use simplelog::{ColorChoice, LevelFilter, TermLogger, TerminalMode};
 
-use drk::{
+use darkfi::{
     blockchain::{rocks::columns, Rocks, RocksColumn},
     cli::{CliGatewayd, Config, GatewaydConfig},
-    service::GatewayService,
     util::{expand_path, join_config_path},
     Result,
+    service::gateway::GatewayService,
 };
 
+
 async fn start(executor: Arc<Executor<'_>>, config: &GatewaydConfig) -> Result<()> {
     let rocks = Rocks::new(&expand_path(&config.database_path)?)?;
     let rocks_slabstore_column = RocksColumn::<columns::Slabs>::new(rocks);
@@ -70,7 +71,7 @@ async fn main() -> Result<()> {
             smol::future::block_on(async move {
                 start(ex2, &config).await?;
                 drop(signal);
-                Ok::<(), drk::Error>(())
+                Ok::<(), darkfi::Error>(())
             })
         });
 

+ 4 - 4
src/bin/darkfid.rs

@@ -11,7 +11,7 @@ use serde_json::{json, Value};
 use simplelog::{ColorChoice, LevelFilter, TermLogger, TerminalMode};
 use url::Url;
 
-use drk::{
+use darkfi::{
     blockchain::{rocks::columns, Rocks, RocksColumn},
     circuit::{MintContract, SpendContract},
     cli::{CliDarkfid, Config, DarkfidConfig},
@@ -713,7 +713,7 @@ async fn start(
     config: &DarkfidConfig,
 ) -> Result<()> {
     let wallet_path = format!("sqlite://{}", expand_path(&config.wallet_path)?.to_str().unwrap());
-    let wallet = WalletDb::new(&wallet_path, config.wallet_password.clone()).await?;
+    let wallet = WalletDb::new(&wallet_path, &config.wallet_password).await?;
 
     let rocks = Rocks::new(expand_path(&config.database_path.clone())?.as_path())?;
 
@@ -821,7 +821,7 @@ async fn main() -> Result<()> {
         info!(target: "DARKFI DAEMON", "Refresh the wallet and the database");
         let wallet_path =
             format!("sqlite://{}", expand_path(&config.wallet_path)?.to_str().unwrap());
-        let wallet = WalletDb::new(&wallet_path, config.wallet_password.clone()).await?;
+        let wallet = WalletDb::new(&wallet_path, &config.wallet_password).await?;
 
         wallet.remove_own_coins().await?;
 
@@ -850,7 +850,7 @@ async fn main() -> Result<()> {
             smol::future::block_on(async move {
                 start(ex2, args.cashier, &config).await?;
                 drop(signal);
-                Ok::<(), drk::Error>(())
+                Ok::<(), darkfi::Error>(())
             })
         });
 

+ 0 - 151
src/bin/darkpulse.rs

@@ -1,151 +0,0 @@
-use async_executor::Executor;
-use async_std::sync::{Arc, Mutex};
-use easy_parallel::Parallel;
-use log::*;
-use smol::Unblock;
-
-use drk::{
-    darkpulse::{
-        dbsql, messages, utility, CiphertextHash, CliOption, ControlCommand, MemPool, SlabsManager,
-    },
-    net::P2p,
-    Result,
-};
-
-async fn on_receive_slab(
-    p2p: Arc<P2p>,
-    slab_rx: async_channel::Receiver<CiphertextHash>,
-) -> Result<()> {
-    loop {
-        let slab = slab_rx.recv().await?;
-        p2p.broadcast(messages::InvMessage { slabs_hash: vec![slab] }).await?;
-    }
-}
-
-async fn start(executor: Arc<Executor<'_>>, options: CliOption, db: dbsql::Dbsql) -> Result<()> {
-    let p2p = P2p::new(options.network_settings);
-
-    p2p.clone().start(executor.clone()).await?;
-
-    let p2p_run_task = executor.spawn(p2p.clone().run(executor.clone()));
-
-    let _mem_pool: MemPool = Arc::new(Mutex::new(vec![]));
-
-    // choose a channel
-    if let Some(new_channel) = options.new_channel {
-        info!("channel added with the name {}", new_channel.get_channel_name());
-        db.add_channel(&new_channel).unwrap();
-    }
-    let main_channel = utility::choose_channel(&db, options.channel_name)?;
-    let channels = db.get_channels()?;
-    let username = utility::setup_username(options.username, &db)?;
-
-    let (slab_sx, slab_rx) = async_channel::unbounded::<CiphertextHash>();
-
-    let slabman = SlabsManager::new(db, slab_sx, main_channel.clone()).await;
-
-    let subscribtion = p2p.subscribe_channel().await;
-
-    let executor2 = executor.clone();
-    let setup_channels_task = executor2.clone().spawn(async move {
-        loop {
-            let network_channel = subscribtion.receive().await.unwrap();
-            utility::setup_network_channel(executor2.clone(), network_channel, slabman.clone())
-                .await;
-        }
-    });
-
-    let receive_slab = executor.spawn(on_receive_slab(p2p.clone(), slab_rx.clone()));
-
-    p2p.broadcast(messages::SyncMessage {}).await?;
-
-    let stdin = Unblock::new(std::io::stdin());
-    let mut stdin = futures::io::BufReader::new(stdin);
-
-    loop {
-        println!("[1] Send Message");
-        println!("[2] Send Sync");
-        println!("[3] list available channels");
-        println!("[4] show the channel address");
-        println!("[5] Quit");
-
-        let buf = utility::read_line(&mut stdin).await?;
-
-        match &buf[..] {
-            "1" => {
-                let slab = utility::pack_slab(
-                    &main_channel.get_channel_secret(),
-                    username.clone(),
-                    String::from("Hello"),
-                    ControlCommand::Message,
-                )
-                .await?;
-
-                p2p.broadcast(slab).await?;
-            }
-            "2" => {
-                p2p.broadcast(messages::SyncMessage {}).await?;
-            }
-            "3" => {
-                println!("------------------");
-                println!("Available channels:");
-                for channel in channels.iter() {
-                    println!("- {}", channel.get_channel_name());
-                }
-                println!("NOTE: switch with one of the available channels by using --channel flag");
-                println!("------------------");
-            }
-            "4" => {
-                println!("------------------");
-                println!("Address: {}", main_channel.get_channel_address());
-                println!("------------------");
-            }
-            "5" => break,
-            _ => {}
-        }
-    }
-
-    setup_channels_task.cancel().await;
-    p2p_run_task.cancel().await;
-    receive_slab.cancel().await;
-    Ok(())
-}
-
-pub fn main() -> Result<()> {
-    use simplelog::*;
-
-    let cli_option = CliOption::get()?;
-
-    let debug_level = if cli_option.verbose { LevelFilter::Debug } else { LevelFilter::Off };
-
-    CombinedLogger::init(vec![
-        TermLogger::new(debug_level, Config::default(), TerminalMode::Mixed, ColorChoice::Always),
-        WriteLogger::new(
-            LevelFilter::Debug,
-            Config::default(),
-            std::fs::File::create("/tmp/darkpulsenode.log").unwrap(),
-        ),
-    ])
-    .unwrap();
-
-    let mut db = dbsql::Dbsql::new()?;
-    db.start()?;
-
-    let ex = Arc::new(Executor::new());
-    let (signal, shutdown) = async_channel::unbounded::<()>();
-    let ex2 = ex.clone();
-
-    let (_, result) = Parallel::new()
-        // Run four executor threads.
-        .each(0..3, |_| smol::future::block_on(ex.run(shutdown.recv())))
-        // Run the main future on the current thread.
-        .finish(|| {
-            smol::future::block_on(async move {
-                start(ex2, cli_option, db).await?;
-                drop(signal);
-                Ok::<(), drk::Error>(())
-            })
-        });
-
-    result
-}

+ 0 - 379
src/bin/drk.rs

@@ -1,379 +0,0 @@
-use std::{path::PathBuf, str::FromStr};
-
-#[macro_use]
-extern crate prettytable;
-use clap::{IntoApp, Parser};
-use log::debug;
-use prettytable::{format, Table};
-use serde_json::{json, Value};
-use simplelog::{ColorChoice, LevelFilter, TermLogger, TerminalMode};
-
-use drk::{
-    cli::{CliDrk, CliDrkSubCommands, Config, DrkConfig},
-    rpc::{jsonrpc, jsonrpc::JsonResult},
-    util::{join_config_path, path::expand_path, NetworkName},
-    Error, Result,
-};
-
-struct Drk {
-    url: String,
-}
-
-impl Drk {
-    pub fn new(url: String) -> Self {
-        Self { url }
-    }
-
-    // Retrieve cashier features and error if they
-    // don't support the network
-    async fn check_network(&self, network: &NetworkName) -> Result<()> {
-        let features = self.features().await?;
-
-        if features.as_object().is_none() &&
-            features.as_object().unwrap()["networks"].as_array().is_none() &&
-            features.as_object().unwrap()["networks"].as_array().unwrap().is_empty()
-        {
-            return Err(Error::NotSupportedNetwork)
-        }
-
-        for nets in features.as_object().unwrap()["networks"].as_array().unwrap() {
-            for (net, _) in nets.as_object().unwrap() {
-                if network == &NetworkName::from_str(net.as_str())? {
-                    return Ok(())
-                }
-            }
-        }
-
-        Err(Error::NotSupportedNetwork)
-    }
-
-    async fn request(&self, r: jsonrpc::JsonRequest) -> Result<Value> {
-        let reply: JsonResult = match jsonrpc::send_raw_request(&self.url, json!(r)).await {
-            Ok(v) => v,
-            Err(e) => return Err(e),
-        };
-
-        match reply {
-            JsonResult::Resp(r) => {
-                debug!(target: "RPC", "<-- {}", serde_json::to_string(&r)?);
-                Ok(r.result)
-            }
-
-            JsonResult::Err(e) => {
-                debug!(target: "RPC", "<-- {}", serde_json::to_string(&e)?);
-                Err(Error::JsonRpcError(e.error.message.to_string()))
-            }
-
-            JsonResult::Notif(n) => {
-                debug!(target: "RPC", "<-- {}", serde_json::to_string(&n)?);
-                Err(Error::JsonRpcError("Unexpected reply".to_string()))
-            }
-        }
-    }
-
-    // --> {"jsonrpc": "2.0", "method": "say_hello", "params": [], "id": 42}
-    // <-- {"jsonrpc": "2.0", "result": "hello world", "id": 42}
-    async fn say_hello(&self) -> Result<Value> {
-        let req = jsonrpc::request(json!("say_hello"), json!([]));
-        Ok(self.request(req).await?)
-    }
-
-    // --> {"jsonrpc": "2.0", "method": "create_wallet", "params": [], "id": 42}
-    // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
-    async fn create_wallet(&self) -> Result<Value> {
-        let req = jsonrpc::request(json!("create_wallet"), json!([]));
-        Ok(self.request(req).await?)
-    }
-
-    // --> {"jsonrpc": "2.0", "method": "key_gen", "params": [], "id": 42}
-    // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
-    async fn key_gen(&self) -> Result<Value> {
-        let req = jsonrpc::request(json!("key_gen"), json!([]));
-        Ok(self.request(req).await?)
-    }
-
-    // --> {"jsonrpc": "2.0", "method": "get_key", "params": [], "id": 42}
-    // <-- {"jsonrpc": "2.0", "result": "vdNS7oBj7KvsMWWmo9r96SV4SqATLrGsH2a3PGpCfJC", "id": 42}
-    async fn get_key(&self) -> Result<Value> {
-        let req = jsonrpc::request(json!("get_key"), json!([]));
-        Ok(self.request(req).await?)
-    }
-
-    // --> {"jsonrpc": "2.0", "method": "get_keys", "params": [], "id": 42}
-    // <-- {"jsonrpc": "2.0", "result": "[vdNS7oBj7KvsMWWmo9r96SV4SqATLrGsH2a3PGpCfJC, ...]", "id":
-    // 42}
-    async fn get_keys(&self) -> Result<Value> {
-        let req = jsonrpc::request(json!("get_keys"), json!([]));
-        Ok(self.request(req).await?)
-    }
-
-    // --> {"jsonrpc": "2.0", "method": "set_default_address", "params":
-    // "[vdNS7oBj7KvsMWWmo9r96SV4SqATLrGsH2a3PGpCfJC]", "id": 42}
-    // <-- {"jsonrpc": "2.0", "result":
-    // true, "id": 42}
-    async fn set_default_address(&self, address: &str) -> Result<Value> {
-        let req = jsonrpc::request(json!("set_default_address"), json!([address]));
-        Ok(self.request(req).await?)
-    }
-
-    // --> {"jsonrpc": "2.0", "method": "export_keypair", "params": "[path/]", "id": 42}
-    // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
-    async fn export_keypair(&self, path: &str) -> Result<Value> {
-        let req = jsonrpc::request(json!("export_keypair"), json!([path]));
-        Ok(self.request(req).await?)
-    }
-
-    // --> {"jsonrpc": "2.0", "method": "import_keypair", "params": "[path/]", "id": 42}
-    // <-- {"jsonrpc": "2.0", "result": true, "id": 42}
-    async fn import_keypair(&self, path: &str) -> Result<Value> {
-        let req = jsonrpc::request(json!("import_keypair"), json!([path]));
-        Ok(self.request(req).await?)
-    }
-
-    // --> {"jsonrpc": "2.0", "method": "get_key", "params": ["solana", "usdc"], "id": 42}
-    // <-- {"jsonrpc": "2.0", "result": "vdNS7oBj7KvsMWWmo9r96SV4SqATLrGsH2a3PGpCfJC", "id": 42}
-    async fn get_token_id(&self, network: &str, token: &str) -> Result<Value> {
-        let req = jsonrpc::request(json!("get_token_id"), json!([network, token]));
-        Ok(self.request(req).await?)
-    }
-
-    // --> {"method": "get_balances", "params": []}
-    // <-- {"result": "get_balances": "[ {"btc": (value, network)}, .. ]"}
-    async fn get_balances(&self) -> Result<Value> {
-        let req = jsonrpc::request(json!("get_balances"), json!([]));
-        Ok(self.request(req).await?)
-    }
-
-    // --> {"jsonrpc": "2.0", "method": "features", "params": [], "id": 42}
-    // <-- {"jsonrpc": "2.0", "result": ["network": "btc", "sol"], "id": 42}
-    async fn features(&self) -> Result<Value> {
-        let req = jsonrpc::request(json!("features"), json!([]));
-        Ok(self.request(req).await?)
-    }
-
-    // --> {"jsonrpc": "2.0", "method": "deposit", "params": ["solana", "usdc"], "id": 42}
-    // <-- {"jsonrpc": "2.0", "result": "Ht5G1RhkcKnpLVLMhqJc5aqZ4wYUEbxbtZwGCVbgU7DL", "id": 42}
-    async fn deposit(&self, network: &str, token: &str) -> Result<Value> {
-        let req = jsonrpc::request(json!("deposit"), json!([network, token]));
-        Ok(self.request(req).await?)
-    }
-
-    // --> {"jsonrpc": "2.0", "method": "withdraw",
-    //      "params": ["solana", "usdc", "Ht5G1RhkcKnpLVLMhqJc5aqZ4wYUEbxbtZwGCVbgU7DL", 13.37"],
-    // "id": 42} <-- {"jsonrpc": "2.0", "result": "txID", "id": 42}
-    async fn withdraw(
-        &self,
-        network: &str,
-        token: &str,
-        address: &str,
-        amount: &str,
-    ) -> Result<Value> {
-        let req = jsonrpc::request(json!("withdraw"), json!([network, token, address, amount]));
-        Ok(self.request(req).await?)
-    }
-
-    // --> {"jsonrpc": "2.0", "method": "transfer",
-    //      "params": ["dusdc", "vdNS7oBj7KvsMWWmo9r96SV4SqATLrGsH2a3PGpCfJC", 13.37], "id": 42}
-    // <-- {"jsonrpc": "2.0", "result": "txID", "id": 42}
-    async fn transfer(
-        &self,
-        network: &str,
-        token: &str,
-        address: &str,
-        amount: &str,
-    ) -> Result<Value> {
-        let req = jsonrpc::request(json!("transfer"), json!([network, token, address, amount]));
-        Ok(self.request(req).await?)
-    }
-}
-
-async fn start(config: &DrkConfig, options: CliDrk) -> Result<()> {
-    let client = Drk::new(config.darkfid_rpc_url.clone());
-
-    match options.command {
-        Some(CliDrkSubCommands::Hello {}) => {
-            let reply = client.say_hello().await?;
-            println!("Server replied: {}", &reply.to_string());
-            return Ok(())
-        }
-        Some(CliDrkSubCommands::Features {}) => {
-            let reply = client.features().await?;
-            println!("Features: {}", &reply.to_string());
-            return Ok(())
-        }
-        Some(CliDrkSubCommands::Wallet {
-            create,
-            keygen,
-            address,
-            balances,
-            addresses,
-            export_keypair,
-            import_keypair,
-            set_default_address,
-        }) => {
-            if create {
-                let reply = client.create_wallet().await?;
-                if reply.as_bool().unwrap() {
-                    println!("Wallet created successfully.")
-                } else {
-                    println!("Server replied: {}", &reply.to_string());
-                }
-                return Ok(())
-            }
-
-            if keygen {
-                let reply = client.key_gen().await?;
-                if reply.as_bool().unwrap() {
-                    println!("Key generation successful.")
-                } else {
-                    println!("Server replied: {}", &reply.to_string());
-                }
-                return Ok(())
-            }
-
-            if address {
-                let reply = client.get_key().await?;
-                println!("Wallet address: {}", &reply.to_string());
-                return Ok(())
-            }
-
-            if addresses {
-                let reply = client.get_keys().await?;
-                println!("Wallet addresses: ");
-                if reply.as_array().is_some() {
-                    for (i, address) in reply.as_array().unwrap().iter().enumerate() {
-                        if i == 0 {
-                            println!("- [X] {}", address);
-                        } else {
-                            println!("- [ ] {}", address);
-                        }
-                    }
-                } else {
-                    println!("Empty!!",);
-                }
-                return Ok(())
-            }
-
-            if balances {
-                let reply = client.get_balances().await?;
-
-                if reply.as_object().is_some() && !reply.as_object().unwrap().is_empty() {
-                    let mut table = Table::new();
-                    table.set_format(*format::consts::FORMAT_NO_LINESEP_WITH_TITLE);
-                    table.set_titles(row!["token", "amount", "network"]);
-
-                    for (tkn, data) in reply.as_object().unwrap() {
-                        table.add_row(row![
-                            tkn,
-                            data[0].as_str().unwrap(),
-                            data[1].as_str().unwrap()
-                        ]);
-                    }
-
-                    table.printstd();
-                } else {
-                    println!("Balances: {}", 0);
-                }
-
-                return Ok(())
-            }
-
-            if set_default_address.is_some() {
-                let default_address = set_default_address.unwrap();
-                client.set_default_address(&default_address).await?;
-                return Ok(())
-            }
-
-            if export_keypair.is_some() {
-                let path = export_keypair.unwrap();
-                client.export_keypair(&path).await?;
-                return Ok(())
-            }
-
-            if import_keypair.is_some() {
-                let path = import_keypair.unwrap();
-                client.import_keypair(&path).await?;
-                return Ok(())
-            }
-        }
-        Some(CliDrkSubCommands::Id { network, token }) => {
-            let network = network.to_lowercase();
-            client.check_network(&NetworkName::from_str(&network)?).await?;
-
-            let reply = client.get_token_id(&network, &token).await?;
-
-            println!("Token ID: {}", &reply.to_string());
-            return Ok(())
-        }
-        Some(CliDrkSubCommands::Deposit { network, token_sym }) => {
-            let network = network.to_lowercase();
-
-            client.check_network(&NetworkName::from_str(&network)?).await?;
-
-            let reply = client.deposit(&network, &token_sym).await?;
-
-            println!("Deposit your coins to the following address: {}", &reply.to_string());
-
-            return Ok(())
-        }
-        Some(CliDrkSubCommands::Transfer { network, token_sym, address, amount }) => {
-            let network = network.to_lowercase();
-
-            client.check_network(&NetworkName::from_str(&network)?).await?;
-
-            client.transfer(&network, &token_sym, &address, &amount.to_string()).await?;
-
-            println!("{} {} Transfered successfully", amount, token_sym.to_uppercase(),);
-
-            return Ok(())
-        }
-
-        Some(CliDrkSubCommands::Withdraw { network, token_sym, address, amount }) => {
-            let network = network.to_lowercase();
-
-            client.check_network(&NetworkName::from_str(&network)?).await?;
-
-            let reply =
-                client.withdraw(&network, &token_sym, &address, &amount.to_string()).await?;
-
-            println!("{}", &reply.to_string());
-
-            return Ok(())
-        }
-        None => {}
-    }
-
-    println!("Please run 'drk help' to see usage.");
-    Err(Error::MissingParams)
-}
-
-#[async_std::main]
-async fn main() -> Result<()> {
-    let args = CliDrk::parse();
-    let matches = CliDrk::into_app().get_matches();
-
-    let config_path = if args.config.is_some() {
-        expand_path(&args.config.clone().unwrap())?
-    } else {
-        join_config_path(&PathBuf::from("drk.toml"))?
-    };
-
-    let mut verbosity_level = 0;
-    verbosity_level += matches.occurrences_of("verbose");
-    let loglevel = match verbosity_level {
-        0 => LevelFilter::Info,
-        1 => LevelFilter::Debug,
-        _ => LevelFilter::Trace,
-    };
-
-    TermLogger::init(
-        loglevel,
-        simplelog::Config::default(),
-        TerminalMode::Mixed,
-        ColorChoice::Auto,
-    )?;
-
-    let config = Config::<DrkConfig>::load(config_path)?;
-
-    start(&config, args).await
-}

+ 1 - 1
src/bin/tree.rs

@@ -2,7 +2,7 @@ use incrementalmerkletree::{bridgetree::BridgeTree, Frontier, Tree};
 use pasta_curves::{arithmetic::Field, pallas};
 use rand::rngs::OsRng;
 
-use drk::{crypto::merkle_node::MerkleNode, Result};
+use darkfi::{crypto::merkle_node::MerkleNode, Result};
 
 fn main() -> Result<()> {
     let mut tree = BridgeTree::<MerkleNode, 32>::new(100);

+ 1 - 1
src/bin/tui_ex.rs

@@ -1,4 +1,4 @@
-use drk::{
+use darkfi::{
     tui::{App, HBox, VBox, Widget},
     Result,
 };

+ 1 - 1
src/bin/tx.rs

@@ -1,7 +1,7 @@
 use incrementalmerkletree::{bridgetree::BridgeTree, Frontier, Tree};
 use rand::rngs::OsRng;
 
-use drk::{
+use darkfi::{
     circuit::{mint_contract::MintContract, spend_contract::SpendContract},
     crypto::{
         coin::Coin,

+ 1 - 1
src/bin/vm.rs

@@ -11,7 +11,7 @@ use pasta_curves::{
 use rand::rngs::OsRng;
 use std::{collections::HashMap, fs::File, time::Instant};
 
-use drk::{
+use darkfi::{
     crypto::{
         constants::OrchardFixedBases,
         proof::{Proof, ProvingKey, VerifyingKey},

+ 1 - 1
src/bin/vm_burn.rs

@@ -17,7 +17,7 @@ use pasta_curves::{
 use rand::rngs::OsRng;
 use std::{collections::HashMap, fs::File, time::Instant};
 
-use drk::{
+use darkfi::{
     crypto::{
         constants::{
             sinsemilla::{i2lebsp, MERKLE_CRH_PERSONALIZATION},

+ 0 - 11
src/cli/cli_config.rs

@@ -10,17 +10,6 @@ use serde::{de::DeserializeOwned, Deserialize, Serialize};
 
 use crate::{Error, Result};
 
-pub fn load_keypair_to_str(path: PathBuf) -> Result<String> {
-    if Path::new(&path).exists() {
-        let key = fs::read(&path)?;
-        let str_buff = str::from_utf8(&key)?;
-        Ok(str_buff.to_string())
-    } else {
-        println!("Could not parse keypair path");
-        Err(Error::KeypairPathNotFound)
-    }
-}
-
 #[derive(Clone, Default)]
 pub struct Config<T> {
     config: PhantomData<T>,

+ 1 - 0
src/cli/mod.rs

@@ -2,4 +2,5 @@ pub mod cli_config;
 pub mod cli_parser;
 
 pub use cli_config::{CashierdConfig, Config, DarkfidConfig, DrkConfig, GatewaydConfig};
+
 pub use cli_parser::{CliCashierd, CliDarkfid, CliDrk, CliDrkSubCommands, CliGatewayd};

+ 0 - 53
src/darkpulse/aes.rs

@@ -1,53 +0,0 @@
-use aes_gcm::{
-    aead::{generic_array::GenericArray, Aead, NewAead},
-    Aes256Gcm,
-};
-
-pub type AesKey = [u8; 32];
-pub type Plaintext = Vec<u8>;
-pub type Ciphertext = Vec<u8>;
-
-pub fn aes_encrypt(
-    shared_secret: &AesKey,
-    nonce: &[u8; 12],
-    plaintext: &[u8],
-) -> Option<Ciphertext> {
-    // Rust is gay, I need to convert to 'GenericArray' whatever the fuck that is...
-    let key = GenericArray::from_slice(&shared_secret[..]);
-    let cipher = Aes256Gcm::new(key);
-
-    let nonce = GenericArray::from_slice(nonce);
-    let ciphertext = cipher.encrypt(nonce, plaintext);
-    ciphertext.ok()
-}
-
-pub fn aes_decrypt(
-    shared_secret: &AesKey,
-    nonce: &[u8; 12],
-    ciphertext: Ciphertext,
-) -> Option<Plaintext> {
-    // Rust is gay, I need to convert to 'GenericArray' whatever the fuck that is...
-    let key = GenericArray::from_slice(&shared_secret[..]);
-    let cipher = Aes256Gcm::new(key);
-
-    let nonce = GenericArray::from_slice(nonce);
-
-    let plaintext = cipher.decrypt(nonce, ciphertext.as_ref());
-    plaintext.ok()
-}
-
-#[test]
-fn test_aes() {
-    let sh_secret = "e02e56a41320d8ebefa946753e9f69587c16d43876cf5bbac86c0ea0e9253d14".as_bytes();
-
-    let mut channel_secret = [0u8; 32];
-    channel_secret.copy_from_slice(&sh_secret[0..32]);
-
-    let nonce = [3; 12];
-
-    let ciphertext = aes_encrypt(&channel_secret, &nonce, b"plaintext message").unwrap();
-
-    let plaintext = aes_decrypt(&channel_secret, &nonce, ciphertext).unwrap();
-    // OK it works!
-    assert_eq!(&plaintext, b"plaintext message");
-}

+ 0 - 89
src/darkpulse/channel.rs

@@ -1,89 +0,0 @@
-use bs58;
-use rand::Rng;
-use sha2::{Digest, Sha256};
-
-use crate::Result;
-
-#[derive(Clone, Debug)]
-pub struct Channel {
-    channel_secret: [u8; 32],
-    channel_name: String,
-    address: String,
-    id: Option<u32>,
-}
-
-impl Channel {
-    pub fn new(
-        channel_name: String,
-        channel_secret: [u8; 32],
-        address: String,
-        id: u32,
-    ) -> Channel {
-        Channel { channel_secret, channel_name, address, id: Some(id) }
-    }
-
-    pub fn gen_new(channel_name: String) -> Channel {
-        let channel_secret = rand::thread_rng().gen::<[u8; 32]>();
-        let address = Self::gen_address(channel_secret);
-        Channel { channel_secret, channel_name, address, id: None }
-    }
-
-    pub fn gen_new_with_addr(channel_name: String, channel_address: String) -> Result<Channel> {
-        let decoded = bs58::decode(channel_address.clone()).into_vec()?;
-        let mut channel_secret: [u8; 32] = [0; 32];
-        channel_secret.copy_from_slice(&decoded[4..36]);
-        Ok(Channel { channel_secret, channel_name, address: channel_address, id: None })
-    }
-
-    pub fn gen_address(channel_secret: [u8; 32]) -> String {
-        let mut hasher = Sha256::new();
-
-        let version: u32 = 1;
-        let mut payload = version.to_be_bytes().to_vec();
-        let mut channel_secret = channel_secret.to_vec();
-        payload.append(&mut channel_secret);
-        hasher.update(payload.clone());
-        let result = hasher.finalize();
-
-        let mut checksum: [u8; 4] = [0; 4];
-        checksum.copy_from_slice(&result[..4]);
-
-        payload.append(&mut checksum.to_vec());
-
-        let encoded = bs58::encode(payload).into_string();
-
-        encoded
-    }
-
-    pub fn get_channel_secret(&self) -> [u8; 32] {
-        self.channel_secret
-    }
-
-    pub fn get_channel_name(&self) -> &String {
-        &self.channel_name
-    }
-
-    pub fn get_channel_id(&self) -> &Option<u32> {
-        &self.id
-    }
-
-    pub fn get_channel_address(&self) -> &String {
-        &self.address
-    }
-}
-
-#[cfg(test)]
-mod tests {
-    use super::Channel;
-    use crate::Result;
-
-    #[test]
-    fn create_channel_form_address() -> Result<()> {
-        let channel = Channel::gen_new(String::from("test"));
-        let channel_address = channel.get_channel_address();
-        let channel2 = Channel::gen_new_with_addr(String::from("test"), channel_address.clone())?;
-        assert_eq!(channel.get_channel_secret(), channel2.get_channel_secret());
-        assert_eq!(channel.get_channel_address(), channel2.get_channel_address());
-        Ok(())
-    }
-}

+ 0 - 176
src/darkpulse/cli_option.rs

@@ -1,176 +0,0 @@
-use std::net::SocketAddr;
-
-use clap::{App, Arg};
-
-use super::Channel;
-use crate::{net::Settings, Result};
-
-pub struct CliOption {
-    pub network_settings: Settings,
-    pub username: Option<String>,
-    pub channel_name: Option<String>,
-    pub new_channel: Option<Channel>,
-    pub verbose: bool,
-    pub log_path: Box<std::path::PathBuf>,
-}
-
-impl CliOption {
-    pub fn get() -> Result<CliOption> {
-        let mat = App::new("DarkPulse")
-            .version("0.0.1")
-            .author("Dark Renaissance Technologies")
-            .about("An anonymous p2p chat application")
-            .arg(
-                Arg::new("accept")
-                    .short('a')
-                    .value_name("ADDRESSES")
-                    .help("accept address")
-                    .long("accept")
-                    .required(true),
-            )
-            .arg(Arg::new("slots").value_name("SLOTS").long("slots").help("Connection slots"))
-            .arg(Arg::new("verbose").takes_value(false).long("verbose").help("increase verbosity"))
-            .arg(
-                Arg::new("connects")
-                    .value_name("MANUAL_CONNECTS")
-                    .multiple_occurrences(true)
-                    .takes_value(true)
-                    .short('c')
-                    .long("connects")
-                    .help("Manual connections"),
-            )
-            .arg(
-                Arg::new("seed")
-                    .value_name("ADDRESSES")
-                    .multiple_occurrences(true)
-                    .takes_value(true)
-                    .short('s')
-                    .long("seed")
-                    .help("Connect to the seed node"),
-            )
-            .arg(
-                Arg::new("log")
-                    .value_name("LOG_PATH")
-                    .takes_value(true)
-                    .long("log")
-                    .help("Log file path"),
-            )
-            .arg(
-                Arg::new("username")
-                    .value_name("USERNAME")
-                    .short('u')
-                    .long("username")
-                    .help("node's username"),
-            )
-            .arg(
-                Arg::new("channel")
-                    .value_name("CHANNEL")
-                    .short('h')
-                    .long("channel")
-                    .help("switch to one of available channels"),
-            )
-            .subcommand(
-                App::new("newchannel")
-                    .about("add new channel")
-                    .arg(
-                        Arg::new("name")
-                            .long("channelname")
-                            .required(true)
-                            .value_name("CHANNELNAME")
-                            .help("name for the new channel"),
-                    )
-                    .arg(
-                        Arg::new("address")
-                            .long("channeladdress")
-                            .required(true)
-                            .value_name("CHANNELADDRESS")
-                            .help("address for the new channel"),
-                    ),
-            )
-            .get_matches();
-
-        let mut accept_addr: Option<SocketAddr> = None;
-        if let Some(addr) = mat.value_of("accept") {
-            accept_addr = Some(addr.parse()?);
-        }
-
-        let mut connection_slots = 0;
-        if let Some(slots) = mat.value_of("slots") {
-            connection_slots = slots.parse()?;
-        };
-
-        let mut seed_addresses: Vec<SocketAddr> = vec![];
-        if let Some(seed_addrs) = mat.values_of("seed") {
-            seed_addresses = Self::collect_addrs(seed_addrs.collect::<Vec<&str>>());
-        };
-
-        let mut manual_connects: Vec<SocketAddr> = vec![];
-        if let Some(man_connects) = mat.values_of("connects") {
-            manual_connects = Self::collect_addrs(man_connects.collect::<Vec<&str>>());
-        };
-
-        let mut username = None;
-
-        if let Some(uname) = mat.value_of("username") {
-            username = Some(String::from(uname));
-        }
-
-        let mut channel_name = None;
-
-        if let Some(chan) = mat.value_of("channel") {
-            channel_name = Some(String::from(chan));
-        }
-
-        let mut new_channel: Option<Channel> = None;
-
-        if let Some(newch) = mat.subcommand_matches("newchannel") {
-            let mut new_channel_name = String::new();
-            let mut new_channel_address = String::new();
-            if let Some(channelname) = newch.value_of("name") {
-                new_channel_name = String::from(channelname);
-            }
-            if let Some(channeladdress) = newch.value_of("address") {
-                new_channel_address = String::from(channeladdress);
-            }
-            new_channel = Some(Channel::gen_new_with_addr(new_channel_name, new_channel_address)?);
-        }
-
-        let verbose = mat.is_present("verbose");
-
-        let log_path = Box::new(
-            if let Some(log_path) = mat.value_of("log") {
-                std::path::Path::new(log_path)
-            } else {
-                std::path::Path::new("/tmp/darkpulsenode.log")
-            }
-            .to_path_buf(),
-        );
-
-        let network_settings = Settings {
-            inbound: accept_addr,
-            outbound_connections: connection_slots,
-            seed_query_timeout_seconds: 8,
-            connect_timeout_seconds: 10,
-            channel_handshake_seconds: 4,
-            channel_heartbeat_seconds: 10,
-            external_addr: accept_addr,
-            peers: manual_connects,
-            seeds: seed_addresses,
-            manual_attempt_limit: 10,
-        };
-
-        Ok(CliOption { network_settings, username, channel_name, new_channel, verbose, log_path })
-    }
-
-    fn collect_addrs(addrs: Vec<&str>) -> Vec<SocketAddr> {
-        let addrs: Vec<SocketAddr> = addrs
-            .iter()
-            .map(|addr| {
-                let addr: SocketAddr = addr.parse().expect("unable to parse on of the addresses");
-                addr
-            })
-            .collect();
-
-        addrs
-    }
-}

+ 0 - 64
src/darkpulse/control_message.rs

@@ -1,64 +0,0 @@
-use std::io;
-
-use crate::{
-    serial::{Decodable, Encodable},
-    Result,
-};
-
-#[derive(Copy, Clone)]
-pub enum ControlCommand {
-    Join = 0,
-    Leave = 1,
-    Message = 2,
-}
-
-pub struct MessagePayload {
-    pub nickname: String,
-    pub text: String,
-    pub timestamp: i64,
-}
-
-pub struct ControlMessage {
-    pub control: ControlCommand,
-    pub payload: MessagePayload,
-}
-
-impl Encodable for MessagePayload {
-    fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
-        let mut len = 0;
-        len += self.nickname.encode(&mut s)?;
-        len += self.text.encode(&mut s)?;
-        len += self.timestamp.encode(&mut s)?;
-        Ok(len)
-    }
-}
-
-impl Decodable for MessagePayload {
-    fn decode<D: io::Read>(mut d: D) -> Result<Self> {
-        Ok(Self {
-            nickname: Decodable::decode(&mut d)?,
-            text: Decodable::decode(&mut d)?,
-            timestamp: Decodable::decode(&mut d)?,
-        })
-    }
-}
-impl Encodable for ControlMessage {
-    fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
-        let mut len = 0;
-        len += (self.control as u8).encode(&mut s)?;
-        len += self.payload.encode(&mut s)?;
-        Ok(len)
-    }
-}
-
-impl Decodable for ControlMessage {
-    fn decode<D: io::Read>(mut d: D) -> Result<Self> {
-        let control_code: u8 = Decodable::decode(&mut d)?;
-        let control = match control_code {
-            0 => ControlCommand::Join,
-            1 => ControlCommand::Leave,
-            _ => ControlCommand::Message,
-        };
-        Ok(Self { control, payload: Decodable::decode(&mut d)? })
-    }
-}

+ 0 - 156
src/darkpulse/dbsql.rs

@@ -1,156 +0,0 @@
-use std::{collections::HashMap, convert::TryInto, fs::File, io::prelude::*};
-
-use rusqlite::{params, Connection};
-
-use super::{utility::default_config_dir, Channel, CiphertextHash, SlabMessage};
-use crate::Result;
-
-#[allow(dead_code)]
-#[derive(Debug)]
-pub struct Dbsql {
-    connection: Connection,
-    username: String,
-}
-
-impl Dbsql {
-    pub fn new() -> Result<Dbsql> {
-        let path = default_config_dir()?.join("data.db");
-        let connection = Connection::open(path)?;
-        let username = String::new();
-        Ok(Dbsql { connection, username })
-    }
-
-    pub fn start(&mut self) -> Result<()> {
-        let schemas = Self::read_schemas_from_file("../../sql/darkpulse_schema.sql")?;
-        self.connection.execute_batch(schemas.as_str())?;
-
-        Ok(())
-    }
-
-    pub fn add_slab(&self, slab: &SlabMessage, channel_id: &u32) -> Result<()> {
-        self.connection.execute(
-            "INSERT OR IGNORE INTO slab (nonce, cipher_text, cipher_text_hash, channel_id) VALUES (?1, ?2, ?3, ?4)",
-            params![&slab.nonce[..], &slab.ciphertext[..], &slab.cipher_hash()[..], channel_id],
-        )?;
-        Ok(())
-    }
-
-    pub fn add_username(&self, username: &str) -> Result<()> {
-        self.connection
-            .execute("INSERT OR IGNORE INTO node (username) VALUES (?1)", params![username])?;
-        Ok(())
-    }
-
-    pub fn get_channel_slabs(&self, id: u32) -> Result<HashMap<CiphertextHash, SlabMessage>> {
-        let stmt = format!("SELECT * FROM slab WHERE channel_id={}", id);
-        let mut stmt = self.connection.prepare(&stmt)?;
-
-        let mut slabs: HashMap<CiphertextHash, SlabMessage> = HashMap::new();
-        let slab_iter = stmt.query_map(params![], |row| {
-            let nonce: Vec<u8> = row.get(1)?;
-            let nonce = nonce
-                .as_slice()
-                .try_into()
-                .expect("error when converting vector to slice with size [u8; 12]");
-
-            let ciphertext = row.get(2)?;
-
-            Ok(SlabMessage { nonce, ciphertext })
-        })?;
-
-        for slab in slab_iter {
-            let slab = slab?;
-            slabs.insert(slab.cipher_hash(), slab);
-        }
-        Ok(slabs)
-    }
-
-    pub fn add_channel(&self, channel: &Channel) -> Result<()> {
-        self.connection.execute(
-            "INSERT OR IGNORE INTO channel (channel_name, channel_secret, address) VALUES (?1, ?2, ?3)",
-            params![
-            &channel.get_channel_name(),
-            &channel.get_channel_secret()[..],
-            &channel.get_channel_address()
-            ],
-        )?;
-        Ok(())
-    }
-
-    pub fn delete_channel(&self, channel_name: &str) -> Result<()> {
-        self.connection
-            .execute("DELETE FROM channel WHERE channel_name = (?1)", params![channel_name,])?;
-        Ok(())
-    }
-
-    fn read_schemas_from_file(path: &str) -> Result<String> {
-        let mut file = File::open(path)?;
-        let mut schemas = String::new();
-        file.read_to_string(&mut schemas)?;
-        Ok(schemas)
-    }
-
-    pub fn get_slabs(&mut self) -> Result<HashMap<CiphertextHash, SlabMessage>> {
-        let mut slabs = HashMap::new();
-        let mut stmt = self.connection.prepare("SELECT * FROM slab")?;
-        let slab_iter = stmt.query_map(params![], |row| {
-            let nonce: Vec<u8> = row.get(1)?;
-
-            let nonce: [u8; 12] = nonce
-                .as_slice()
-                .try_into()
-                .expect("error when converting vector to slice with size [u8; 12]");
-
-            let ciphertext = row.get(2)?;
-
-            Ok(SlabMessage { nonce, ciphertext })
-        })?;
-
-        for slab in slab_iter {
-            let slab = slab?;
-            slabs.insert(slab.cipher_hash(), slab);
-        }
-
-        Ok(slabs)
-    }
-
-    pub fn get_channels(&self) -> Result<Vec<Channel>> {
-        let mut channels = Vec::new();
-        let mut stmt = self.connection.prepare("SELECT * FROM channel")?;
-        let channel_iter = stmt.query_map(params![], |row| {
-            let channel_id = row.get(0)?;
-            let channel_name = row.get(1)?;
-            let channel_secret: Vec<u8> = row.get(2)?;
-
-            let channel_secret: [u8; 32] = channel_secret
-                .as_slice()
-                .try_into()
-                .expect("error when converting vector to slice with size [u8; 32]");
-
-            let address = row.get(3)?;
-            Ok(Channel::new(channel_name, channel_secret, address, channel_id))
-        })?;
-
-        for channel in channel_iter {
-            let channel = channel?;
-            channels.push(channel);
-        }
-
-        Ok(channels.clone())
-    }
-
-    pub fn get_username(&self) -> Result<String> {
-        let mut username = String::new();
-        let mut stmt3 = self.connection.prepare("SELECT * FROM node")?;
-        let uname_iter = stmt3.query_map(params![], |row| {
-            let username: String = row.get(1)?;
-            Ok(username)
-        })?;
-
-        for name in uname_iter {
-            username = name?;
-        }
-
-        Ok(username)
-    }
-}

+ 0 - 21
src/darkpulse/mod.rs

@@ -1,21 +0,0 @@
-pub mod aes;
-pub mod channel;
-pub mod cli_option;
-pub mod control_message;
-pub mod dbsql;
-pub mod net;
-pub mod slabs_manager;
-pub mod utility;
-
-use async_std::sync::{Arc, Mutex};
-
-pub type CiphertextHash = [u8; 32];
-pub type MemPool = Arc<Mutex<Vec<(CiphertextHash, net::messages::SlabMessage)>>>;
-
-pub use aes::{aes_decrypt, aes_encrypt, Ciphertext, Plaintext};
-pub use channel::Channel;
-pub use cli_option::CliOption;
-pub use control_message::{ControlCommand, ControlMessage, MessagePayload};
-pub use dbsql::Dbsql;
-pub use net::{messages, messages::SlabMessage, protocol_slab::ProtocolSlab};
-pub use slabs_manager::{SlabsManager, SlabsManagerSafe};

+ 0 - 104
src/darkpulse/net/messages.rs

@@ -1,104 +0,0 @@
-use std::io;
-
-use crate::{
-    darkpulse::Ciphertext,
-    net::messages::Message,
-    serial::{Decodable, Encodable},
-    Result,
-};
-
-#[derive(Clone)]
-pub struct GetSlabsMessage {
-    pub slabs_hash: Vec<[u8; 32]>,
-}
-
-#[derive(Clone)]
-pub struct InvMessage {
-    pub slabs_hash: Vec<[u8; 32]>,
-}
-
-#[derive(Clone)]
-pub struct SlabMessage {
-    pub nonce: [u8; 12],
-    pub ciphertext: Ciphertext,
-}
-
-#[derive(Clone)]
-pub struct SyncMessage {}
-
-impl Message for SlabMessage {
-    fn name() -> &'static str {
-        "slab"
-    }
-}
-
-impl Message for GetSlabsMessage {
-    fn name() -> &'static str {
-        "getslabs"
-    }
-}
-impl Message for InvMessage {
-    fn name() -> &'static str {
-        "inv"
-    }
-}
-impl Message for SyncMessage {
-    fn name() -> &'static str {
-        "sync"
-    }
-}
-
-impl Encodable for GetSlabsMessage {
-    fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
-        let mut len = 0;
-        len += self.slabs_hash.encode(&mut s)?;
-        Ok(len)
-    }
-}
-
-impl Decodable for GetSlabsMessage {
-    fn decode<D: io::Read>(mut d: D) -> Result<Self> {
-        Ok(Self { slabs_hash: Decodable::decode(&mut d)? })
-    }
-}
-
-impl Encodable for SlabMessage {
-    fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
-        let mut len = 0;
-        len += self.nonce.encode(&mut s)?;
-        len += self.ciphertext.encode(&mut s)?;
-        Ok(len)
-    }
-}
-
-impl Decodable for SlabMessage {
-    fn decode<D: io::Read>(mut d: D) -> Result<Self> {
-        Ok(Self { nonce: Decodable::decode(&mut d)?, ciphertext: Decodable::decode(&mut d)? })
-    }
-}
-
-impl Encodable for InvMessage {
-    fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
-        let mut len = 0;
-        len += self.slabs_hash.encode(&mut s)?;
-        Ok(len)
-    }
-}
-
-impl Decodable for InvMessage {
-    fn decode<D: io::Read>(mut d: D) -> Result<Self> {
-        Ok(Self { slabs_hash: Decodable::decode(&mut d)? })
-    }
-}
-
-impl Encodable for SyncMessage {
-    fn encode<S: io::Write>(&self, _s: S) -> Result<usize> {
-        Ok(0)
-    }
-}
-
-impl Decodable for SyncMessage {
-    fn decode<D: io::Read>(_d: D) -> Result<Self> {
-        Ok(Self {})
-    }
-}

+ 0 - 2
src/darkpulse/net/mod.rs

@@ -1,2 +0,0 @@
-pub mod messages;
-pub mod protocol_slab;

+ 0 - 175
src/darkpulse/net/protocol_slab.rs

@@ -1,175 +0,0 @@
-use std::sync::Arc;
-
-use log::*;
-use smol::Executor;
-
-use crate::{
-    darkpulse::{
-        aes_decrypt, messages, CiphertextHash, ControlCommand, ControlMessage, SlabsManagerSafe,
-    },
-    error::Result as NetResult,
-    net::{
-        message_subscriber::MessageSubscription,
-        protocols::{ProtocolJobsManager, ProtocolJobsManagerPtr},
-        ChannelPtr,
-    },
-    serial::deserialize,
-};
-
-pub struct ProtocolSlab {
-    channel: ChannelPtr,
-    slabman: SlabsManagerSafe,
-
-    sync_sub: MessageSubscription<messages::SyncMessage>,
-    inv_sub: MessageSubscription<messages::InvMessage>,
-    get_slabs_sub: MessageSubscription<messages::GetSlabsMessage>,
-    slab_sub: MessageSubscription<messages::SlabMessage>,
-
-    jobsman: ProtocolJobsManagerPtr,
-}
-
-impl ProtocolSlab {
-    pub async fn new(slabman: SlabsManagerSafe, channel: ChannelPtr) -> Arc<Self> {
-        let sync_sub = channel
-            .clone()
-            .subscribe_msg::<messages::SyncMessage>()
-            .await
-            .expect("Missing sync  dispatcher!");
-
-        let inv_sub = channel
-            .clone()
-            .subscribe_msg::<messages::InvMessage>()
-            .await
-            .expect("Missing inv  dispatcher!");
-
-        let get_slabs_sub = channel
-            .clone()
-            .subscribe_msg::<messages::GetSlabsMessage>()
-            .await
-            .expect("Missing getslabs  dispatcher!");
-
-        let slab_sub = channel
-            .clone()
-            .subscribe_msg::<messages::SlabMessage>()
-            .await
-            .expect("Missing slab  dispatcher!");
-
-        Arc::new(Self {
-            channel: channel.clone(),
-            slabman,
-            sync_sub,
-            inv_sub,
-            get_slabs_sub,
-            slab_sub,
-            jobsman: ProtocolJobsManager::new("ProtocolSlab", channel),
-        })
-    }
-
-    pub async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) {
-        debug!(target: "net", "ProtocolSlab::start() [START]");
-        self.jobsman.clone().start(executor.clone());
-
-        self.jobsman.clone().spawn(self.clone().handle_receive_sync(), executor.clone()).await;
-        self.jobsman.clone().spawn(self.clone().handle_receive_inv(), executor.clone()).await;
-
-        self.jobsman.clone().spawn(self.clone().handle_receive_get_slabs(), executor.clone()).await;
-        self.jobsman.clone().spawn(self.clone().handle_receive_slab(), executor).await;
-
-        let _ = self.channel.send(messages::SyncMessage {}).await;
-
-        debug!(target: "net", "ProtocolSlab::start() [END]");
-    }
-
-    async fn handle_receive_sync(self: Arc<Self>) -> NetResult<()> {
-        debug!(target: "net", "ProtocolSlab::handle_receive_sync() [START]");
-        loop {
-            let _sync_msg = self.sync_sub.receive().await?;
-            let slab_hashs = self.slabman.lock().await.get_slabs_hash();
-            let inv_msg = messages::InvMessage { slabs_hash: slab_hashs.clone() };
-            self.channel.send(inv_msg).await?;
-            info!("receive sync message!");
-        }
-    }
-
-    async fn handle_receive_inv(self: Arc<Self>) -> NetResult<()> {
-        debug!(target: "net", "ProtocolSlab::handle_receive_inv() [START]");
-        loop {
-            let inv_msg = self.inv_sub.receive().await?;
-            let mut list_of_hash: Vec<CiphertextHash> = vec![];
-            let slabs_hash = self.slabman.lock().await.get_slabs_hash();
-            for slab in inv_msg.slabs_hash.iter() {
-                if !slabs_hash.contains(slab) {
-                    list_of_hash.push(*slab);
-                }
-            }
-            let getslabs_msg = messages::GetSlabsMessage { slabs_hash: list_of_hash };
-            self.channel.send(getslabs_msg).await?;
-            info!("receive inv message!");
-        }
-    }
-
-    async fn handle_receive_get_slabs(self: Arc<Self>) -> NetResult<()> {
-        debug!(target: "net", "ProtocolSlab::handle_receive_get_slabs() [START]");
-        loop {
-            let get_slabs_msg = self.get_slabs_sub.receive().await?;
-            for slab_hash in get_slabs_msg.slabs_hash.iter() {
-                let slabman = self.slabman.lock().await;
-                let slab = slabman.get_slab(slab_hash);
-                if let Some(slab) = slab {
-                    self.channel.send(slab.clone()).await?;
-                }
-            }
-            info!("receive getslabs message!");
-        }
-    }
-
-    async fn handle_receive_slab(self: Arc<Self>) -> NetResult<()> {
-        debug!(target: "net", "ProtocolSlab::handle_receive_slab() [START]");
-        loop {
-            let slab_msg = self.slab_sub.receive().await?;
-            info!("receive slab message!");
-
-            let channels = self.slabman.lock().await.get_channels().unwrap_or_default();
-
-            let slab = messages::SlabMessage {
-                nonce: slab_msg.nonce,
-                ciphertext: slab_msg.ciphertext.clone(),
-            };
-
-            for channel in channels.iter() {
-                if let Some(plaintext) = aes_decrypt(
-                    &channel.get_channel_secret(),
-                    &slab_msg.nonce,
-                    slab_msg.ciphertext.clone(),
-                ) {
-                    self.slabman
-                        .lock()
-                        .await
-                        .add_new_slab(slab.clone())
-                        .await
-                        .expect("error during adding new slab to database");
-
-                    let des_plaintext: ControlMessage = deserialize(&plaintext[..])
-                        .expect("error during deserializing the message");
-
-                    match des_plaintext.control {
-                        ControlCommand::Join => {
-                            info!("{} joined the group", des_plaintext.payload.nickname);
-                        }
-                        ControlCommand::Leave => {
-                            info!("{} left the group", des_plaintext.payload.nickname);
-                        }
-                        ControlCommand::Message => {
-                            info!(
-                                "{} -> {}: {}",
-                                des_plaintext.payload.timestamp,
-                                des_plaintext.payload.nickname,
-                                des_plaintext.payload.text
-                            );
-                        }
-                    }
-                }
-            }
-        }
-    }
-}

+ 0 - 1
src/darkpulse/net/protocols/mod.rs

@@ -1 +0,0 @@
-pub mod protocol_slab;

+ 0 - 119
src/darkpulse/slabs_manager.rs

@@ -1,119 +0,0 @@
-use std::{collections::HashMap, sync::Arc};
-
-use log::*;
-use sha2::{Digest, Sha256};
-
-use super::{aes::Ciphertext, channel::Channel, dbsql, net::messages::SlabMessage, CiphertextHash};
-use crate::Result;
-
-pub fn cipher_hash(ciphertext: Ciphertext) -> CiphertextHash {
-    let mut cipher_hash = [0u8; 32];
-    let mut hasher = Sha256::new();
-    for chunk in ciphertext.chunks(32) {
-        hasher.update(chunk);
-    }
-    cipher_hash.copy_from_slice(&hasher.finalize());
-    cipher_hash
-}
-
-impl SlabMessage {
-    pub fn cipher_hash(&self) -> CiphertextHash {
-        cipher_hash(self.ciphertext.clone())
-    }
-}
-
-pub type SlabsManagerSafe = Arc<async_std::sync::Mutex<SlabsManager>>;
-
-pub struct SlabsManager {
-    slabs: HashMap<CiphertextHash, SlabMessage>,
-    notify_update: async_channel::Sender<CiphertextHash>,
-    main_channel: Channel,
-    db: dbsql::Dbsql,
-}
-
-impl SlabsManager {
-    pub async fn new(
-        db: dbsql::Dbsql,
-        notify_update: async_channel::Sender<CiphertextHash>,
-        main_channel: Channel,
-    ) -> SlabsManagerSafe {
-        let mut slabs: HashMap<CiphertextHash, SlabMessage> = HashMap::new();
-
-        if let Some(channel_id) = main_channel.get_channel_id() {
-            slabs = db.get_channel_slabs(*channel_id).unwrap_or(slabs);
-        }
-
-        Arc::new(async_std::sync::Mutex::new(SlabsManager {
-            slabs,
-            notify_update,
-            main_channel,
-            db,
-        }))
-    }
-
-    pub fn get_slabs_hash(&self) -> Vec<CiphertextHash> {
-        self.slabs.keys().cloned().collect()
-    }
-    pub fn height(&self) -> u32 {
-        self.slabs.len() as u32
-    }
-    pub fn has_cipher_hash(&self, cipher_hash: &CiphertextHash) -> bool {
-        self.slabs.contains_key(cipher_hash)
-    }
-
-    pub async fn add_new_slab(&mut self, slab: SlabMessage) -> Result<()> {
-        info!("received Slab message.");
-        self.slabs.insert(slab.cipher_hash(), slab.clone());
-
-        if let Some(channel_id) = self.main_channel.get_channel_id() {
-            self.db.add_slab(&slab, channel_id)?;
-        }
-
-        self.notify_update.send(slab.cipher_hash()).await?;
-        Ok(())
-    }
-
-    pub fn set_main_channel(&mut self, main_channel: Channel) {
-        self.main_channel = main_channel;
-        self.switch_main_channel();
-    }
-
-    pub fn switch_main_channel(&mut self) {
-        let default_slabs: HashMap<CiphertextHash, SlabMessage> = HashMap::new();
-
-        if let Some(channel_id) = self.main_channel.get_channel_id() {
-            self.slabs = self.db.get_channel_slabs(*channel_id).unwrap_or(default_slabs);
-        }
-    }
-
-    pub fn get_channels(&mut self) -> Result<Vec<Channel>> {
-        self.db.get_channels()
-    }
-
-    pub fn add_new_channel(&mut self, new_channel: &Channel) -> Result<()> {
-        self.db.add_channel(new_channel)?;
-        Ok(())
-    }
-
-    pub fn delete_channel(&mut self, channel_id: &str) -> Result<()> {
-        self.db.delete_channel(channel_id)?;
-        Ok(())
-    }
-
-    pub fn add_username(&mut self, username: &str) -> Result<()> {
-        self.db.add_username(username)?;
-        Ok(())
-    }
-
-    pub fn get_main_channel(&self) -> Channel {
-        self.main_channel.clone()
-    }
-
-    pub fn get_slab(&self, cipher_hash: &CiphertextHash) -> Option<&SlabMessage> {
-        self.slabs.get(cipher_hash)
-    }
-
-    pub fn get_slabs(&self) -> &HashMap<CiphertextHash, SlabMessage> {
-        &self.slabs
-    }
-}

+ 0 - 164
src/darkpulse/utility.rs

@@ -1,164 +0,0 @@
-use std::{
-    fs::OpenOptions,
-    io::prelude::*,
-    net::SocketAddr,
-    path::PathBuf,
-    sync::{atomic::AtomicU64, Arc},
-    time::{SystemTime, UNIX_EPOCH},
-};
-
-use async_executor::Executor;
-use futures::prelude::*;
-use log::*;
-
-use super::{
-    aes_encrypt, messages, Channel, ControlCommand, ControlMessage, Dbsql, MessagePayload,
-    ProtocolSlab, SlabsManagerSafe,
-};
-
-use crate::{
-    net::ChannelPtr,
-    serial::{deserialize, serialize},
-    Result,
-};
-
-pub type AddrsStorage = Arc<async_std::sync::Mutex<Vec<SocketAddr>>>;
-
-pub type Clock = Arc<AtomicU64>;
-
-pub fn get_current_time() -> u64 {
-    let start = SystemTime::now();
-    let since_the_epoch =
-        start.duration_since(UNIX_EPOCH).expect("Incorrect system clock: time went backwards");
-
-    since_the_epoch.as_secs() * 1000 + since_the_epoch.subsec_nanos() as u64 / 1_000_000
-}
-
-pub fn save_to_addrs_store(stored_addrs: &[SocketAddr]) -> Result<()> {
-    let path = default_config_dir()?.join("addrs.add");
-    let mut writer = OpenOptions::new().write(true).create(true).open(path)?;
-    let buffer = serialize(&stored_addrs.to_vec());
-    writer.write_all(&buffer)?;
-    Ok(())
-}
-
-pub fn default_config_dir() -> Result<PathBuf> {
-    let mut path = PathBuf::new();
-
-    if let Some(home_dir) = dirs::home_dir() {
-        path = home_dir;
-    };
-
-    let path = path.join(".darkpulse/");
-    if !path.exists() {
-        match std::fs::create_dir(&path) {
-            Err(err) => {
-                eprintln!("error: Creating config dir: {}", err);
-                std::process::exit(-1);
-            }
-            Ok(()) => (),
-        }
-    }
-
-    Ok(path)
-}
-
-pub fn load_stored_addrs() -> Result<Vec<SocketAddr>> {
-    let path = default_config_dir()?.join("addrs.add");
-    println!("{:?}", path);
-    let mut reader = OpenOptions::new().read(true).write(true).create(true).open(path)?;
-    let mut buffer = Vec::new();
-    reader.read_to_end(&mut buffer)?;
-    if !buffer.is_empty() {
-        let addrs: Vec<SocketAddr> = deserialize(&buffer)?;
-        Ok(addrs)
-    } else {
-        Ok(vec![])
-    }
-}
-
-pub async fn pack_slab(
-    channel_secret: &[u8; 32],
-    username: String,
-    message: String,
-    control_command: ControlCommand,
-) -> Result<messages::SlabMessage> {
-    let nonce: [u8; 12] = rand::random();
-    let timestamp = chrono::offset::Utc::now();
-    let timestamp: i64 = timestamp.timestamp_millis() / 1000;
-
-    let msg_payload = MessagePayload { nickname: username, text: message, timestamp };
-
-    let control_message = ControlMessage { control: control_command, payload: msg_payload };
-
-    let ser_message = serialize(&control_message);
-
-    let ciphertext = aes_encrypt(channel_secret, &nonce, &ser_message[..])
-        .expect("error during encrypting the message");
-
-    let slab = messages::SlabMessage { nonce, ciphertext };
-
-    Ok(slab)
-}
-
-pub fn setup_username(newname: Option<String>, db: &Dbsql) -> Result<String> {
-    let mut _username: String = String::new();
-    match newname {
-        Some(nm) => {
-            _username = nm.clone();
-            db.add_username(&nm).unwrap();
-        }
-        None => {
-            _username = db.get_username()?;
-            if _username.is_empty() {
-                _username = String::from("username");
-            }
-        }
-    }
-    Ok(_username)
-}
-
-pub async fn read_line<R: AsyncBufRead + Unpin>(reader: &mut R) -> Result<String> {
-    let mut buf = String::new();
-    let _ = reader.read_line(&mut buf).await?;
-    Ok(buf.trim().to_string())
-}
-
-pub fn choose_channel(db: &Dbsql, channel_name: Option<String>) -> Result<Channel> {
-    let channels = db.get_channels()?;
-    let mut main_channel = Channel::gen_new(String::from("test_channel"));
-    if !channels.is_empty() {
-        match channel_name {
-            Some(name) => {
-                main_channel = channels
-                    .iter()
-                    .find(|ch| ch.get_channel_name() == &name)
-                    .unwrap_or_else(|| panic!("there is no channel with the name {}: ", name))
-                    .clone();
-            }
-            None => {
-                main_channel = channels.first().unwrap().clone();
-            }
-        }
-    } else {
-        error!("there are no channels available");
-        db.add_channel(&main_channel)?;
-    }
-    Ok(main_channel)
-}
-
-pub async fn setup_network_channel(
-    executor: Arc<Executor<'_>>,
-    channel: ChannelPtr,
-    slabman: SlabsManagerSafe,
-) {
-    let message_subsytem = channel.get_message_subsystem();
-
-    message_subsytem.add_dispatch::<messages::SyncMessage>().await;
-    message_subsytem.add_dispatch::<messages::InvMessage>().await;
-    message_subsytem.add_dispatch::<messages::GetSlabsMessage>().await;
-    message_subsytem.add_dispatch::<messages::SlabMessage>().await;
-
-    let protocol_slab = ProtocolSlab::new(slabman, channel.clone()).await;
-    protocol_slab.clone().start(executor.clone()).await;
-}

+ 0 - 3
src/lib.rs

@@ -22,7 +22,4 @@ pub mod wallet;
 #[cfg(feature = "tui")]
 pub mod tui;
 
-#[cfg(feature = "darkpulse")]
-pub mod darkpulse;
-
 pub use crate::error::{Error, Result};

+ 0 - 16
src/service/mod.rs

@@ -1,20 +1,4 @@
-pub mod bridge;
 pub mod gateway;
 pub mod reqrep;
 
-#[cfg(feature = "btc")]
-pub mod btc;
-#[cfg(feature = "btc")]
-pub use btc::{Account, BtcFailed, BtcResult, Keypair, PubAddress};
-
-#[cfg(feature = "sol")]
-pub mod sol;
-#[cfg(feature = "sol")]
-pub use sol::{SolClient, SolFailed, SolResult};
-
-#[cfg(feature = "eth")]
-pub mod eth;
-#[cfg(feature = "eth")]
-pub use eth::{EthClient, EthFailed, EthResult};
-
 pub use gateway::{GatewayClient, GatewayService, GatewaySlabsSubscriber};

+ 1 - 1
src/util/mod.rs

@@ -10,7 +10,7 @@ pub use async_util::sleep;
 pub use loader::ContractLoader;
 pub use net_name::NetworkName;
 pub use parse::{assign_id, decode_base10, encode_base10, generate_id, generate_id2};
-pub use path::{expand_path, join_config_path};
+pub use path::{expand_path, join_config_path, load_keypair_to_str};
 pub use token_list::{DrkTokenList, TokenList};
 
 pub use address::Address;

+ 17 - 2
src/util/path.rs

@@ -1,5 +1,9 @@
-use crate::Result;
-use std::path::{Path, PathBuf};
+use std::{
+    fs,
+    path::{Path, PathBuf},
+};
+
+use crate::{Error, Result};
 
 pub fn expand_path(path: &str) -> Result<PathBuf> {
     let ret: PathBuf;
@@ -30,3 +34,14 @@ pub fn join_config_path(file: &Path) -> Result<PathBuf> {
 
     Ok(path)
 }
+
+pub fn load_keypair_to_str(path: PathBuf) -> Result<String> {
+    if Path::new(&path).exists() {
+        let key = fs::read(&path)?;
+        let str_buff = std::str::from_utf8(&key)?;
+        Ok(str_buff.to_string())
+    } else {
+        println!("Could not parse keypair path");
+        Err(Error::KeypairPathNotFound)
+    }
+}

+ 3 - 3
src/wallet/cashierdb.rs

@@ -49,7 +49,7 @@ pub struct CashierDb {
 impl WalletApi for CashierDb {}
 
 impl CashierDb {
-    pub async fn new(path: &str, password: String) -> Result<CashierDbPtr> {
+    pub async fn new(path: &str, password: &str) -> Result<CashierDbPtr> {
         debug!("new() Constructor called");
         if password.trim().is_empty() {
             error!("Password is empty. You must set a password to use the wallet.");
@@ -65,7 +65,7 @@ impl CashierDb {
         }
 
         let mut connect_opts = SqliteConnectOptions::from_str(path)?
-            .pragma("key", password)
+            .pragma("key", password.to_string())
             .create_if_missing(true)
             .journal_mode(SqliteJournalMode::Off);
 
@@ -486,7 +486,7 @@ mod tests {
 
     #[async_std::test]
     async fn test_cashierdb() -> Result<()> {
-        let wallet = CashierDb::new("sqlite::memory:", WPASS.to_string()).await?;
+        let wallet = CashierDb::new("sqlite::memory:", WPASS).await?;
 
         // init_db()
         wallet.init_db().await?;

+ 3 - 3
src/wallet/walletdb.rs

@@ -46,7 +46,7 @@ pub struct WalletDb {
 impl WalletApi for WalletDb {}
 
 impl WalletDb {
-    pub async fn new(path: &str, password: String) -> Result<WalletPtr> {
+    pub async fn new(path: &str, password: &str) -> Result<WalletPtr> {
         if password.trim().is_empty() {
             error!("Password is empty. You must set a password to use the wallet.");
             return Err(Error::from(ClientFailed::EmptyPassword))
@@ -61,7 +61,7 @@ impl WalletDb {
         }
 
         let mut connect_opts = SqliteConnectOptions::from_str(path)?
-            .pragma("key", password)
+            .pragma("key", password.to_string())
             .create_if_missing(true)
             .journal_mode(SqliteJournalMode::Off);
 
@@ -404,7 +404,7 @@ mod tests {
 
     #[async_std::test]
     async fn test_walletdb() -> Result<()> {
-        let wallet = WalletDb::new("sqlite::memory:", WPASS.to_string()).await?;
+        let wallet = WalletDb::new("sqlite::memory:", WPASS).await?;
         let keypair = Keypair::random(&mut OsRng);
 
         // init_db()

Některé soubory nejsou zobrazeny, neboť je v těchto rozdílových datech změněno mnoho souborů