ghassmo 4 лет назад
Родитель
Сommit
70f28dc79c

+ 35 - 30
bin/cashier/src/main.rs

@@ -27,10 +27,7 @@ use darkfi::{
     state::State,
     state::State,
     types::DrkTokenId,
     types::DrkTokenId,
     util::{expand_path, generate_id2, join_config_path, parse::truncate, Address, NetworkName},
     util::{expand_path, generate_id2, join_config_path, parse::truncate, Address, NetworkName},
-    wallet::{
-        cashierdb::CashierDb, 
-        walletdb::WalletDb,
-    },
+    wallet::{cashierdb::CashierDb, walletdb::WalletDb},
     Error, Result,
     Error, Result,
 };
 };
 
 
@@ -111,10 +108,8 @@ impl Cashierd {
         state: Arc<Mutex<State>>,
         state: Arc<Mutex<State>>,
         executor: Arc<Executor<'_>>,
         executor: Arc<Executor<'_>>,
     ) -> Result<(smol::Task<Result<()>>, smol::Task<Result<()>>)> {
     ) -> Result<(smol::Task<Result<()>>, smol::Task<Result<()>>)> {
-
         self.cashier_wallet.init_db().await?;
         self.cashier_wallet.init_db().await?;
 
 
-
         for network in self.networks.iter() {
         for network in self.networks.iter() {
             match network.name {
             match network.name {
                 #[cfg(feature = "sol")]
                 #[cfg(feature = "sol")]
@@ -124,7 +119,12 @@ impl Cashierd {
 
 
                     let _bridge = self.bridge.clone();
                     let _bridge = self.bridge.clone();
 
 
-                    let sol_client = SolClient::new(self.cashier_wallet.clone(), &network.blockchain, &network.keypair).await?;
+                    let sol_client = SolClient::new(
+                        self.cashier_wallet.clone(),
+                        &network.blockchain,
+                        &network.keypair,
+                    )
+                    .await?;
 
 
                     _bridge.add_clients(NetworkName::Solana, sol_client).await?;
                     _bridge.add_clients(NetworkName::Solana, sol_client).await?;
                 }
                 }
@@ -157,7 +157,12 @@ impl Cashierd {
 
 
                     let _bridge = self.bridge.clone();
                     let _bridge = self.bridge.clone();
 
 
-                    let btc_client = BtcClient::new(self.cashier_wallet.clone(), &network.blockchain, &network.keypair).await?;
+                    let btc_client = BtcClient::new(
+                        self.cashier_wallet.clone(),
+                        &network.blockchain,
+                        &network.keypair,
+                    )
+                    .await?;
 
 
                     _bridge.add_clients(NetworkName::Bitcoin, btc_client).await?;
                     _bridge.add_clients(NetworkName::Bitcoin, btc_client).await?;
                 }
                 }
@@ -190,8 +195,8 @@ impl Cashierd {
                     recv_coin.clone(),
                     recv_coin.clone(),
                     ex2.clone(),
                     ex2.clone(),
                 )
                 )
-                    .await?;
-                }
+                .await?;
+            }
         });
         });
 
 
         let bridge2 = self.bridge.clone();
         let bridge2 = self.bridge.clone();
@@ -217,7 +222,7 @@ impl Cashierd {
                             state.clone(),
                             state.clone(),
                         )
                         )
                         .await?;
                         .await?;
-                    }
+                }
                 Ok(())
                 Ok(())
             });
             });
 
 
@@ -257,7 +262,7 @@ impl Cashierd {
                         amount,
                         amount,
                     ),
                     ),
                 })
                 })
-            .await?;
+                .await?;
 
 
             // receive a response
             // receive a response
             let res = bridge_subscribtion.receiver.recv().await?;
             let res = bridge_subscribtion.receiver.recv().await?;
@@ -277,7 +282,7 @@ impl Cashierd {
                             &withdraw_token.network,
                             &withdraw_token.network,
                         )
                         )
                         .await?;
                         .await?;
-                    }
+                }
                 _ => {
                 _ => {
                     return Err(Error::BridgeError("Receive unknown value from Subscription".into()))
                     return Err(Error::BridgeError("Receive unknown value from Subscription".into()))
                 }
                 }
@@ -341,9 +346,9 @@ impl Cashierd {
         // Check if the features list contains this network
         // Check if the features list contains this network
         if !self.networks.iter().any(|net| net.name == network) {
         if !self.networks.iter().any(|net| net.name == network) {
             return JsonResult::Err(jsonerr(
             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,
             ))
             ))
         }
         }
 
 
@@ -388,15 +393,15 @@ impl Cashierd {
                         network: network.clone(),
                         network: network.clone(),
                         payload: bridge::BridgeRequestsPayload::Watch(None),
                         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?;
                     .await?;
             }
             }
 
 
@@ -466,9 +471,9 @@ impl Cashierd {
         // Check if the features list contains this network
         // Check if the features list contains this network
         if !self.networks.iter().any(|net| net.name == network) {
         if !self.networks.iter().any(|net| net.name == network) {
             return JsonResult::Err(jsonerr(
             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,
             ))
             ))
         }
         }
 
 
@@ -488,8 +493,8 @@ impl Cashierd {
 
 
             if let Some(addr) = self
             if let Some(addr) = self
                 .cashier_wallet
                 .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;
                 cashier_public = addr.public;
             } else {
             } else {

+ 20 - 22
bin/cashier/src/service/btc.rs

@@ -44,7 +44,7 @@ use super::bridge::{NetworkClient, TokenNotification, TokenSubscribtion};
 use darkfi::{
 use darkfi::{
     crypto::keypair::PublicKey as DrkPublicKey,
     crypto::keypair::PublicKey as DrkPublicKey,
     serial::{deserialize, serialize, Decodable, Encodable},
     serial::{deserialize, serialize, Decodable, Encodable},
-    util::{generate_id2, NetworkName, load_keypair_to_str, expand_path},
+    util::{expand_path, generate_id2, load_keypair_to_str, NetworkName},
     wallet::cashierdb::{CashierDb, TokenKey},
     wallet::cashierdb::{CashierDb, TokenKey},
     Error, Result,
     Error, Result,
 };
 };
@@ -241,9 +241,9 @@ impl Client {
             subscriptions: Vec::new(),
             subscriptions: Vec::new(),
             latest_block_height: BlockHeight::try_from(latest_block)
             latest_block_height: BlockHeight::try_from(latest_block)
                 .map_err(|_| darkfi::Error::TryFromError)?,
                 .map_err(|_| darkfi::Error::TryFromError)?,
-                last_sync: Instant::now(),
-                sync_interval: interval,
-                script_history: Default::default(),
+            last_sync: Instant::now(),
+            sync_interval: interval,
+            script_history: Default::default(),
         })
         })
     }
     }
     fn update_state(&mut self) -> Result<()> {
     fn update_state(&mut self) -> Result<()> {
@@ -307,8 +307,8 @@ impl Client {
                     Ok(ScriptStatus::InMempool)
                     Ok(ScriptStatus::InMempool)
                 } else {
                 } else {
                     Ok(ScriptStatus::Confirmed(Confirmed::from_inclusion_and_latest_block(
                     Ok(ScriptStatus::Confirmed(Confirmed::from_inclusion_and_latest_block(
-                                u32::try_from(last.height).map_err(|_| darkfi::Error::TryFromError)?,
-                                u32::from(self.latest_block_height),
+                        u32::try_from(last.height).map_err(|_| darkfi::Error::TryFromError)?,
+                        u32::from(self.latest_block_height),
                     )))
                     )))
                 }
                 }
             }
             }
@@ -320,15 +320,17 @@ pub struct BtcClient {
     client: Arc<Mutex<Client>>,
     client: Arc<Mutex<Client>>,
     notify_channel:
     notify_channel:
         (async_channel::Sender<TokenNotification>, async_channel::Receiver<TokenNotification>),
         (async_channel::Sender<TokenNotification>, async_channel::Receiver<TokenNotification>),
-        network: Network,
+    network: Network,
 }
 }
 impl BtcClient {
 impl BtcClient {
-    pub async fn new(cashier_wallet: Arc<CashierDb>, network: &str, keypair_path: &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_keypair: Keypair;
 
 
-        let main_keypairs =
-            cashier_wallet.get_main_keys(&NetworkName::Bitcoin).await?;
+        let main_keypairs = cashier_wallet.get_main_keys(&NetworkName::Bitcoin).await?;
 
 
         if keypair_path.is_empty() {
         if keypair_path.is_empty() {
             if main_keypairs.is_empty() {
             if main_keypairs.is_empty() {
@@ -342,19 +344,15 @@ impl BtcClient {
                         &NetworkName::Bitcoin,
                         &NetworkName::Bitcoin,
                     )
                     )
                     .await?;
                     .await?;
-                } else {
-                    main_keypair =
-                        deserialize(&main_keypairs[main_keypairs.len() - 1].secret_key)?;
+            } else {
+                main_keypair = deserialize(&main_keypairs[main_keypairs.len() - 1].secret_key)?;
             }
             }
         } else {
         } else {
-            let keypair_str = load_keypair_to_str(expand_path(
-                    &keypair_path,
-            )?)?;
+            let keypair_str = load_keypair_to_str(expand_path(&keypair_path)?)?;
             let keypair_bytes: Vec<u8> = serde_json::from_str(&keypair_str)?;
             let keypair_bytes: Vec<u8> = serde_json::from_str(&keypair_str)?;
             main_keypair = Keypair::from_bytes(&keypair_bytes)
             main_keypair = Keypair::from_bytes(&keypair_bytes)
                 .map_err(|e| BtcFailed::DecodeAndEncodeError(e.to_string()))?;
                 .map_err(|e| BtcFailed::DecodeAndEncodeError(e.to_string()))?;
-            }
-
+        }
 
 
         let notify_channel = async_channel::unbounded();
         let notify_channel = async_channel::unbounded();
 
 
@@ -450,7 +448,7 @@ impl BtcClient {
                 received_balance: amnt as u64,
                 received_balance: amnt as u64,
                 decimals: 8,
                 decimals: 8,
             })
             })
-        .await
+            .await
             .map_err(Error::from)?;
             .map_err(Error::from)?;
 
 
         info!(target: "BTC BRIDGE", "Received {} btc", ui_amnt);
         info!(target: "BTC BRIDGE", "Received {} btc", ui_amnt);
@@ -556,7 +554,7 @@ impl NetworkClient for BtcClient {
                     error!(target: "BTC BRIDGE SUBSCRIPTION","{}", e.to_string());
                     error!(target: "BTC BRIDGE SUBSCRIPTION","{}", e.to_string());
                 }
                 }
             })
             })
-        .detach();
+            .detach();
 
 
         Ok(TokenSubscribtion { private_key, public_key })
         Ok(TokenSubscribtion { private_key, public_key })
     }
     }
@@ -580,7 +578,7 @@ impl NetworkClient for BtcClient {
                     error!(target: "BTC BRIDGE SUBSCRIPTION","{}", e.to_string());
                     error!(target: "BTC BRIDGE SUBSCRIPTION","{}", e.to_string());
                 }
                 }
             })
             })
-        .detach();
+            .detach();
 
 
         Ok(public_key)
         Ok(public_key)
     }
     }

+ 21 - 31
bin/cashier/src/service/eth.rs

@@ -200,13 +200,11 @@ pub struct EthClient {
 
 
 impl EthClient {
 impl EthClient {
     pub fn new(_network: &str, socket_path: &str, passphrase: &str) -> Self {
     pub fn new(_network: &str, socket_path: &str, passphrase: &str) -> Self {
-
         let notify_channel = async_channel::unbounded();
         let notify_channel = async_channel::unbounded();
 
 
         let subscriptions = Arc::new(Mutex::new(Vec::new()));
         let subscriptions = Arc::new(Mutex::new(Vec::new()));
 
 
-
-        let main_keypair = Keypair{ public_key: "".into(), private_key: "".into()};
+        let main_keypair = Keypair { public_key: "".into(), private_key: "".into() };
 
 
         Self {
         Self {
             main_keypair,
             main_keypair,
@@ -219,23 +217,17 @@ impl EthClient {
 
 
     pub async fn setup_keypair(
     pub async fn setup_keypair(
         &mut self,
         &mut self,
-        cashier_wallet: Arc<CashierDb>, 
-        _keypair_path: &str
+        cashier_wallet: Arc<CashierDb>,
+        _keypair_path: &str,
     ) -> Result<()> {
     ) -> Result<()> {
-
         let main_keypair: Keypair;
         let main_keypair: Keypair;
 
 
-        let main_keypairs =
-            cashier_wallet.get_main_keys(&NetworkName::Ethereum).await?;
+        let main_keypairs = cashier_wallet.get_main_keys(&NetworkName::Ethereum).await?;
 
 
         if main_keypairs.is_empty() {
         if main_keypairs.is_empty() {
             let main_private_key = generate_privkey();
             let main_private_key = generate_privkey();
-            let main_public_key = self
-                .import_privkey(&main_private_key)
-                .await?
-                .as_str()
-                .unwrap()
-                .to_string();
+            let main_public_key =
+                self.import_privkey(&main_private_key).await?.as_str().unwrap().to_string();
 
 
             cashier_wallet
             cashier_wallet
                 .put_main_keys(
                 .put_main_keys(
@@ -247,9 +239,7 @@ impl EthClient {
                 )
                 )
                 .await?;
                 .await?;
 
 
-            main_keypair =
-                Keypair { private_key: main_private_key, public_key: main_public_key };
-
+            main_keypair = Keypair { private_key: main_private_key, public_key: main_public_key };
         } else {
         } else {
             let last_keypair = &main_keypairs[main_keypairs.len() - 1];
             let last_keypair = &main_keypairs[main_keypairs.len() - 1];
 
 
@@ -316,7 +306,7 @@ impl EthClient {
 
 
         if current_balance < prev_balance {
         if current_balance < prev_balance {
             return Err(darkfi::Error::ClientFailed(
             return Err(darkfi::Error::ClientFailed(
-                    "New balance is less than previous balance".into(),
+                "New balance is less than previous balance".into(),
             ))
             ))
         }
         }
 
 
@@ -333,7 +323,7 @@ impl EthClient {
                 received_balance: received_balance.to_u64_digits()[0],
                 received_balance: received_balance.to_u64_digits()[0],
                 decimals: decimals as u16,
                 decimals: decimals as u16,
             })
             })
-        .await
+            .await
             .map_err(Error::from)?;
             .map_err(Error::from)?;
 
 
         self.send_eth_to_main_wallet(&addr, received_balance).await?;
         self.send_eth_to_main_wallet(&addr, received_balance).await?;
@@ -357,10 +347,10 @@ impl EthClient {
         let reply: JsonResult = match jsonrpc::send_unix_request(&self.socket_path, json!(r))
         let reply: JsonResult = match jsonrpc::send_unix_request(&self.socket_path, json!(r))
             .await
             .await
             .map_err(EthFailed::from)
             .map_err(EthFailed::from)
-            {
-                Ok(v) => v,
-                Err(e) => return Err(e),
-            };
+        {
+            Ok(v) => v,
+            Err(e) => return Err(e),
+        };
 
 
         match reply {
         match reply {
             JsonResult::Resp(r) => {
             JsonResult::Resp(r) => {
@@ -380,17 +370,17 @@ impl EthClient {
         }
         }
     }
     }
 
 
-    pub async fn import_privkey(&self, key: &str,) -> EthResult<Value> {
+    pub async fn import_privkey(&self, key: &str) -> EthResult<Value> {
         let req = jsonrpc::request(json!("personal_importRawKey"), json!([key, self.passphrase]));
         let req = jsonrpc::request(json!("personal_importRawKey"), json!([key, self.passphrase]));
         Ok(self.request(req).await?)
         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> {
     pub async fn block_number(&self) -> EthResult<Value> {
         let req = jsonrpc::request(json!("eth_blockNumber"), json!([]));
         let req = jsonrpc::request(json!("eth_blockNumber"), json!([]));
@@ -453,7 +443,7 @@ impl NetworkClient for EthClient {
                     error!(target: "ETH BRIDGE SUBSCRIPTION","{}", e.to_string());
                     error!(target: "ETH BRIDGE SUBSCRIPTION","{}", e.to_string());
                 }
                 }
             })
             })
-        .detach();
+            .detach();
 
 
         let private_key: Vec<u8> = serialize(&private_key);
         let private_key: Vec<u8> = serialize(&private_key);
 
 
@@ -478,7 +468,7 @@ impl NetworkClient for EthClient {
                     error!(target: "ETH BRIDGE SUBSCRIPTION","{}", e.to_string());
                     error!(target: "ETH BRIDGE SUBSCRIPTION","{}", e.to_string());
                 }
                 }
             })
             })
-        .detach();
+            .detach();
 
 
         Ok(public_key)
         Ok(public_key)
     }
     }

+ 22 - 20
bin/cashier/src/service/sol.rs

@@ -27,14 +27,13 @@ use darkfi::{
     crypto::keypair::PublicKey,
     crypto::keypair::PublicKey,
     rpc::{jsonrpc, jsonrpc::JsonResult, websockets, websockets::WsStream},
     rpc::{jsonrpc, jsonrpc::JsonResult, websockets, websockets::WsStream},
     serial::{deserialize, serialize, Decodable, Encodable},
     serial::{deserialize, serialize, Decodable, Encodable},
-    util::{generate_id2, parse::truncate, sleep, NetworkName, expand_path, load_keypair_to_str},
+    util::{expand_path, generate_id2, load_keypair_to_str, parse::truncate, sleep, NetworkName},
+    wallet::cashierdb::{CashierDb, TokenKey},
     Error, Result,
     Error, Result,
-    wallet::cashierdb::{TokenKey, CashierDb},
 };
 };
 
 
 pub const SOL_NATIVE_TOKEN_ID: &str = "So11111111111111111111111111111111111111112";
 pub const SOL_NATIVE_TOKEN_ID: &str = "So11111111111111111111111111111111111111112";
 
 
-
 struct Keypair(SolKeypair);
 struct Keypair(SolKeypair);
 struct Pubkey(SolPubkey);
 struct Pubkey(SolPubkey);
 
 
@@ -50,12 +49,16 @@ pub struct SolClient {
     subscriptions: Arc<Mutex<Vec<Pubkey>>>,
     subscriptions: Arc<Mutex<Vec<Pubkey>>>,
     notify_channel:
     notify_channel:
         (async_channel::Sender<TokenNotification>, async_channel::Receiver<TokenNotification>),
         (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 {
 impl SolClient {
-    pub async fn new(cashier_wallet: Arc<CashierDb>, network: &str, keypair_path: &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 notify_channel = async_channel::unbounded();
 
 
         let main_keypair: Keypair;
         let main_keypair: Keypair;
@@ -74,18 +77,16 @@ impl SolClient {
                         &NetworkName::Solana,
                         &NetworkName::Solana,
                     )
                     )
                     .await?;
                     .await?;
-                } else {
-                    main_keypair =
-                        deserialize(&main_keypairs[main_keypairs.len() - 1].secret_key)?;
+            } else {
+                main_keypair = deserialize(&main_keypairs[main_keypairs.len() - 1].secret_key)?;
             }
             }
         } else {
         } else {
-            let keypair_str =
-                load_keypair_to_str(expand_path(keypair_path)?)?;
+            let keypair_str = load_keypair_to_str(expand_path(keypair_path)?)?;
 
 
             let keypair_bytes: Vec<u8> = serde_json::from_str(&keypair_str)?;
             let keypair_bytes: Vec<u8> = serde_json::from_str(&keypair_str)?;
             main_keypair = Keypair::from_bytes(&keypair_bytes)
             main_keypair = Keypair::from_bytes(&keypair_bytes)
                 .map_err(|e| SolFailed::Signature(e.to_string()))?;
                 .map_err(|e| SolFailed::Signature(e.to_string()))?;
-            }
+        }
 
 
         info!(target: "SOL BRIDGE", "Main SOL wallet pubkey: {:?}", &main_keypair.pubkey());
         info!(target: "SOL BRIDGE", "Main SOL wallet pubkey: {:?}", &main_keypair.pubkey());
 
 
@@ -240,8 +241,8 @@ impl SolClient {
                             .unwrap()
                             .unwrap()
                             .parse()
                             .parse()
                             .map_err(Error::from)?;
                             .map_err(Error::from)?;
-                        } else {
-                            cur_balance = params["lamports"].as_u64().unwrap();
+                    } else {
+                        cur_balance = params["lamports"].as_u64().unwrap();
                     }
                     }
                     break
                     break
                 }
                 }
@@ -270,7 +271,7 @@ impl SolClient {
                     received_balance: amnt,
                     received_balance: amnt,
                     decimals: decimals as u16,
                     decimals: decimals as u16,
                 })
                 })
-            .await
+                .await
                 .map_err(Error::from)?;
                 .map_err(Error::from)?;
 
 
             info!(target: "SOL BRIDGE", "Received {} {:?} tokens", ui_amnt, mint.unwrap());
             info!(target: "SOL BRIDGE", "Received {} {:?} tokens", ui_amnt, mint.unwrap());
@@ -286,7 +287,7 @@ impl SolClient {
                     received_balance: amnt,
                     received_balance: amnt,
                     decimals: decimals as u16,
                     decimals: decimals as u16,
                 })
                 })
-            .await
+                .await
                 .map_err(Error::from)?;
                 .map_err(Error::from)?;
 
 
             info!(target: "SOL BRIDGE", "Received {} SOL", ui_amnt);
             info!(target: "SOL BRIDGE", "Received {} SOL", ui_amnt);
@@ -455,7 +456,7 @@ impl NetworkClient for SolClient {
                     error!(target: "SOL BRIDGE SUBSCRIPTION","{}", e.to_string());
                     error!(target: "SOL BRIDGE SUBSCRIPTION","{}", e.to_string());
                 }
                 }
             })
             })
-        .detach();
+            .detach();
 
 
         Ok(TokenSubscribtion { private_key, public_key })
         Ok(TokenSubscribtion { private_key, public_key })
     }
     }
@@ -488,7 +489,7 @@ impl NetworkClient for SolClient {
                     error!(target: "SOL BRIDGE SUBSCRIPTION","{}", e.to_string());
                     error!(target: "SOL BRIDGE SUBSCRIPTION","{}", e.to_string());
                 }
                 }
             })
             })
-        .detach();
+            .detach();
 
 
         Ok(public_key)
         Ok(public_key)
     }
     }
@@ -595,7 +596,6 @@ impl Decodable for Keypair {
     }
     }
 }
 }
 
 
-
 impl Encodable for Pubkey {
 impl Encodable for Pubkey {
     fn encode<S: std::io::Write>(&self, s: S) -> Result<usize> {
     fn encode<S: std::io::Write>(&self, s: S) -> Result<usize> {
         let key = self.to_string();
         let key = self.to_string();
@@ -608,7 +608,9 @@ impl Decodable for Pubkey {
     fn decode<D: std::io::Read>(mut d: D) -> Result<Self> {
     fn decode<D: std::io::Read>(mut d: D) -> Result<Self> {
         let key: String = Decodable::decode(&mut d)?;
         let key: String = Decodable::decode(&mut d)?;
         let key = Pubkey::try_from(key.as_str()).map_err(|_| {
         let key = Pubkey::try_from(key.as_str()).map_err(|_| {
-            darkfi::Error::from(SolFailed::DecodeAndEncodeError("load public key from slice".into()))
+            darkfi::Error::from(SolFailed::DecodeAndEncodeError(
+                "load public key from slice".into(),
+            ))
         })?;
         })?;
         Ok(key)
         Ok(key)
     }
     }

+ 1 - 2
bin/gateway/src/main.rs

@@ -9,12 +9,11 @@ use simplelog::{ColorChoice, LevelFilter, TermLogger, TerminalMode};
 use darkfi::{
 use darkfi::{
     blockchain::{rocks::columns, Rocks, RocksColumn},
     blockchain::{rocks::columns, Rocks, RocksColumn},
     cli::{CliGatewayd, Config, GatewaydConfig},
     cli::{CliGatewayd, Config, GatewaydConfig},
+    service::gateway::GatewayService,
     util::{expand_path, join_config_path},
     util::{expand_path, join_config_path},
     Result,
     Result,
-    service::gateway::GatewayService,
 };
 };
 
 
-
 async fn start(executor: Arc<Executor<'_>>, config: &GatewaydConfig) -> Result<()> {
 async fn start(executor: Arc<Executor<'_>>, config: &GatewaydConfig) -> Result<()> {
     let rocks = Rocks::new(&expand_path(&config.database_path)?)?;
     let rocks = Rocks::new(&expand_path(&config.database_path)?)?;
     let rocks_slabstore_column = RocksColumn::<columns::Slabs>::new(rocks);
     let rocks_slabstore_column = RocksColumn::<columns::Slabs>::new(rocks);

+ 8 - 13
bin/ircd/src/irc_server.rs

@@ -1,17 +1,10 @@
-use std::{
-    net::{TcpStream},
-};
-use rand::{RngCore, rngs::OsRng};
-use futures::{
-    io::{WriteHalf}, AsyncWriteExt,
-};
+use futures::{io::WriteHalf, AsyncWriteExt};
 use log::{debug, info};
 use log::{debug, info};
+use rand::{rngs::OsRng, RngCore};
 use smol::Async;
 use smol::Async;
+use std::net::TcpStream;
 
 
-use drk::{
-    net,
-    Error, Result,
-};
+use drk::{net, Error, Result};
 
 
 use crate::privmsg::{PrivMsg, SeenPrivMsgIdsPtr};
 use crate::privmsg::{PrivMsg, SeenPrivMsgIdsPtr};
 
 
@@ -43,7 +36,10 @@ pub struct IrcServerConnection {
 }
 }
 
 
 impl IrcServerConnection {
 impl IrcServerConnection {
-    pub fn new(write_stream: WriteHalf<Async<TcpStream>>, seen_privmsg_ids: SeenPrivMsgIdsPtr) -> Self {
+    pub fn new(
+        write_stream: WriteHalf<Async<TcpStream>>,
+        seen_privmsg_ids: SeenPrivMsgIdsPtr,
+    ) -> Self {
         Self {
         Self {
             write_stream,
             write_stream,
             seen_privmsg_ids,
             seen_privmsg_ids,
@@ -140,4 +136,3 @@ impl IrcServerConnection {
         Ok(())
         Ok(())
     }
     }
 }
 }
-

+ 23 - 20
bin/ircd/src/main.rs

@@ -1,23 +1,20 @@
 #[macro_use]
 #[macro_use]
 extern crate clap;
 extern crate clap;
-use async_trait::async_trait;
-use std::{
-    net::{SocketAddr, TcpListener, TcpStream},
-    sync::Arc,
-};
 use async_executor::Executor;
 use async_executor::Executor;
 use async_std::io::BufReader;
 use async_std::io::BufReader;
-use futures::{
-    AsyncBufReadExt, AsyncReadExt, FutureExt,
-};
-use serde_json::{json, Value};
+use async_trait::async_trait;
+use futures::{AsyncBufReadExt, AsyncReadExt, FutureExt};
 use log::{debug, error, info, warn};
 use log::{debug, error, info, warn};
+use serde_json::{json, Value};
 use simplelog::{ColorChoice, LevelFilter, TermLogger, TerminalMode};
 use simplelog::{ColorChoice, LevelFilter, TermLogger, TerminalMode};
 use smol::Async;
 use smol::Async;
+use std::{
+    net::{SocketAddr, TcpListener, TcpStream},
+    sync::Arc,
+};
 
 
 use drk::{
 use drk::{
     net,
     net,
-    util::expand_path,
     rpc::{
     rpc::{
         jsonrpc::{
         jsonrpc::{
             error as jsonerr, request as jsonreq, response as jsonresp, send_raw_request,
             error as jsonerr, request as jsonreq, response as jsonresp, send_raw_request,
@@ -25,19 +22,20 @@ use drk::{
         },
         },
         rpcserver::{listen_and_serve, RequestHandler, RpcServerConfig},
         rpcserver::{listen_and_serve, RequestHandler, RpcServerConfig},
     },
     },
+    util::expand_path,
     Error, Result,
     Error, Result,
 };
 };
 
 
+mod irc_server;
 mod privmsg;
 mod privmsg;
 mod program_options;
 mod program_options;
 mod protocol_privmsg;
 mod protocol_privmsg;
-mod irc_server;
 
 
 use crate::{
 use crate::{
+    irc_server::IrcServerConnection,
     privmsg::{PrivMsg, PrivMsgId, SeenPrivMsgIds, SeenPrivMsgIdsPtr},
     privmsg::{PrivMsg, PrivMsgId, SeenPrivMsgIds, SeenPrivMsgIdsPtr},
     program_options::ProgramOptions,
     program_options::ProgramOptions,
     protocol_privmsg::ProtocolPrivMsg,
     protocol_privmsg::ProtocolPrivMsg,
-    irc_server::IrcServerConnection,
 };
 };
 
 
 async fn process(
 async fn process(
@@ -117,7 +115,9 @@ async fn channel_loop(
 
 
         debug!("NEWCHANNEL");
         debug!("NEWCHANNEL");
 
 
-        let protocol_privmsg = ProtocolPrivMsg::new(channel, sender.clone(), seen_privmsg_ids.clone(), p2p.clone()).await;
+        let protocol_privmsg =
+            ProtocolPrivMsg::new(channel, sender.clone(), seen_privmsg_ids.clone(), p2p.clone())
+                .await;
         protocol_privmsg.start(executor.clone()).await;
         protocol_privmsg.start(executor.clone()).await;
     }
     }
 }
 }
@@ -167,14 +167,16 @@ async fn start(executor: Arc<Executor<'_>>, options: ProgramOptions) -> Result<(
     let (sender, recvr) = async_channel::unbounded();
     let (sender, recvr) = async_channel::unbounded();
     // for now the p2p and channel sub sessions just run forever
     // for now the p2p and channel sub sessions just run forever
     // so detach them as background processes.
     // so detach them as background processes.
-    executor.spawn(channel_loop(p2p.clone(), sender, seen_privmsg_ids.clone(), executor.clone())).detach();
+    executor
+        .spawn(channel_loop(p2p.clone(), sender, seen_privmsg_ids.clone(), executor.clone()))
+        .detach();
 
 
     let ex2 = executor.clone();
     let ex2 = executor.clone();
     let ex3 = ex2.clone();
     let ex3 = ex2.clone();
     let rpc_interface = Arc::new(JsonRpcInterface {});
     let rpc_interface = Arc::new(JsonRpcInterface {});
-    executor.spawn(async move {
-        listen_and_serve(server_config, rpc_interface, ex3).await
-    }).detach();
+    executor
+        .spawn(async move { listen_and_serve(server_config, rpc_interface, ex3).await })
+        .detach();
 
 
     loop {
     loop {
         let (stream, peer_addr) = match listener.accept().await {
         let (stream, peer_addr) = match listener.accept().await {
@@ -188,12 +190,13 @@ async fn start(executor: Arc<Executor<'_>>, options: ProgramOptions) -> Result<(
 
 
         let p2p2 = p2p.clone();
         let p2p2 = p2p.clone();
         let ex2 = executor.clone();
         let ex2 = executor.clone();
-        executor.spawn(process(recvr.clone(), stream, peer_addr, p2p2, seen_privmsg_ids.clone(), ex2)).detach();
+        executor
+            .spawn(process(recvr.clone(), stream, peer_addr, p2p2, seen_privmsg_ids.clone(), ex2))
+            .detach();
     }
     }
 }
 }
 
 
-struct JsonRpcInterface {
-}
+struct JsonRpcInterface {}
 
 
 #[async_trait]
 #[async_trait]
 impl RequestHandler for JsonRpcInterface {
 impl RequestHandler for JsonRpcInterface {

+ 3 - 7
bin/ircd/src/privmsg.rs

@@ -1,13 +1,10 @@
 use async_std::sync::Mutex;
 use async_std::sync::Mutex;
-use std::{
-    collections::HashSet,
-    io,
-    sync::Arc,
-};
 use drk::{
 use drk::{
     net,
     net,
-    serial::{Decodable, Encodable}, Result,
+    serial::{Decodable, Encodable},
+    Result,
 };
 };
+use std::{collections::HashSet, io, sync::Arc};
 
 
 pub type PrivMsgId = u32;
 pub type PrivMsgId = u32;
 
 
@@ -66,4 +63,3 @@ impl SeenPrivMsgIds {
         self.privmsg_ids.lock().await.contains(&id)
         self.privmsg_ids.lock().await.contains(&id)
     }
     }
 }
 }
-

+ 2 - 14
bin/ircd/src/program_options.rs

@@ -1,17 +1,6 @@
-use std::{
-    net::{SocketAddr},
-};
+use std::net::SocketAddr;
 
 
-
-
-
-
-
-
-
-use drk::{
-    net, Result,
-};
+use drk::{net, Result};
 
 
 pub struct ProgramOptions {
 pub struct ProgramOptions {
     pub network_settings: net::Settings,
     pub network_settings: net::Settings,
@@ -96,4 +85,3 @@ impl ProgramOptions {
         })
         })
     }
     }
 }
 }
-

+ 4 - 10
bin/ircd/src/protocol_privmsg.rs

@@ -1,15 +1,10 @@
+use async_executor::Executor;
 use async_std::sync::Mutex;
 use async_std::sync::Mutex;
-use std::{
-    sync::Arc,
-    collections::HashSet,
-};
+use drk::{net, Result};
 use log::debug;
 use log::debug;
-use async_executor::Executor;
-use drk::{
-    net, Result,
-};
+use std::{collections::HashSet, sync::Arc};
 
 
-use crate::privmsg::{PrivMsgId, PrivMsg, SeenPrivMsgIdsPtr};
+use crate::privmsg::{PrivMsg, PrivMsgId, SeenPrivMsgIdsPtr};
 
 
 pub struct ProtocolPrivMsg {
 pub struct ProtocolPrivMsg {
     notify_queue_sender: async_channel::Sender<Arc<PrivMsg>>,
     notify_queue_sender: async_channel::Sender<Arc<PrivMsg>>,
@@ -76,4 +71,3 @@ impl ProtocolPrivMsg {
         }
         }
     }
     }
 }
 }
-