فهرست منبع

added mutex lock to zmq socket. finished client side deposit().

ran cargo fmt
lunar-mining 5 سال پیش
والد
کامیت
8a6f14571a

+ 0 - 2
src/bin/cashierd.rs

@@ -63,8 +63,6 @@ fn main() -> Result<()> {
         .unwrap();
     }
 
-
-
     let ex2 = ex.clone();
 
     let (_, result) = Parallel::new()

+ 0 - 3
src/bin/darkfid.rs

@@ -280,7 +280,6 @@ async fn start(executor: Arc<Executor<'_>>, config: Arc<&DarkfidConfig>) -> Resu
 }
 
 fn main() -> Result<()> {
-
     let options = Arc::new(DarkfidCli::load()?);
 
     let config_path: PathBuf;
@@ -294,14 +293,12 @@ fn main() -> Result<()> {
         }
     }
 
-
     let config: DarkfidConfig = if Path::new(&config_path).exists() {
         Config::<DarkfidConfig>::load(config_path)?
     } else {
         Config::<DarkfidConfig>::load_default(config_path)?
     };
 
-
     let config_ptr = Arc::new(&config);
 
     let ex = Arc::new(Executor::new());

+ 2 - 8
src/blockchain/rocks.rs

@@ -51,16 +51,10 @@ impl Rocks {
         // nullifiers column family
         let nullifiers_cf = ColumnFamilyDescriptor::new(columns::Nullifiers::NAME, cf_opts.clone());
         // merkleroots column family
-        let merkleroots_cf =
-            ColumnFamilyDescriptor::new(columns::MerkleRoots::NAME, cf_opts);
+        let merkleroots_cf = ColumnFamilyDescriptor::new(columns::MerkleRoots::NAME, cf_opts);
 
         // column families
-        let cfs = vec![
-            default_cf,
-            slab_cf,
-            nullifiers_cf,
-            merkleroots_cf,
-        ];
+        let cfs = vec![default_cf, slab_cf, nullifiers_cf, merkleroots_cf];
 
         // database options
         let mut opt = Options::default();

+ 6 - 8
src/cli/darkfid_cli.rs

@@ -31,16 +31,14 @@ impl DarkfidCli {
             )
             .get_matches();
 
-        let config = Box::new(
-            if let Some(config_path) = app.value_of("config") {
-                Some(std::path::Path::new(config_path).to_path_buf())
-            } else {
-                None
-            }
-        );
+        let config = Box::new(if let Some(config_path) = app.value_of("config") {
+            Some(std::path::Path::new(config_path).to_path_buf())
+        } else {
+            None
+        });
 
         let verbose = app.is_present("verbose");
 
-        Ok(Self { verbose , config})
+        Ok(Self { verbose, config })
     }
 }

+ 1 - 3
src/cli/gatewayd_cli.rs

@@ -16,8 +16,6 @@ impl GatewaydCli {
 
         let verbose = app.is_present("VERBOSE");
 
-        Ok(Self {
-            verbose,
-        })
+        Ok(Self { verbose })
     }
 }

+ 1 - 1
src/cli/mod.rs

@@ -5,7 +5,7 @@ pub mod drk_cli;
 pub mod gatewayd_cli;
 
 pub use cashierd_cli::CashierdCli;
-pub use cli_config::{CashierdConfig, DarkfidConfig, DrkConfig, GatewaydConfig, Config};
+pub use cli_config::{CashierdConfig, Config, DarkfidConfig, DrkConfig, GatewaydConfig};
 pub use darkfid_cli::DarkfidCli;
 pub use drk_cli::DrkCli;
 pub use drk_cli::{TransferParams, WithdrawParams};

+ 2 - 6
src/crypto/merkle.rs

@@ -264,8 +264,6 @@ impl<Node: Hashable> Encodable for IncrementalWitness<Node> {
     }
 }
 
-
-
 impl<Node: Hashable> Decodable for IncrementalWitness<Node> {
     fn decode<D: io::Read>(mut d: D) -> Result<Self> {
         Ok(Self {
@@ -277,8 +275,6 @@ impl<Node: Hashable> Decodable for IncrementalWitness<Node> {
     }
 }
 
-
-
 impl<Node: Hashable> IncrementalWitness<Node> {
     /// Creates an `IncrementalWitness` for the most recent commitment added to
     /// the given [`CommitmentTree`].
@@ -357,8 +353,8 @@ impl<Node: Hashable> IncrementalWitness<Node> {
             if cursor.is_complete(self.cursor_depth) {
                 self.filled
                     .push(cursor.root_inner(self.cursor_depth, PathFiller::empty()));
-                } else {
-                    self.cursor = Some(cursor);
+            } else {
+                self.cursor = Some(cursor);
             }
         } else {
             self.cursor_depth = self.next_depth();

+ 0 - 1
src/crypto/merkle_node.rs

@@ -143,4 +143,3 @@ lazy_static! {
         v
     };
 }
-

+ 11 - 6
src/rpc/adapter.rs

@@ -1,9 +1,10 @@
+use crate::cli::TransferParams;
+use crate::cli::WithdrawParams;
+use crate::serial::serialize;
 use crate::service::btc::PubAddress;
 use crate::service::cashier::CashierClient;
 use crate::wallet::WalletDb;
 use crate::{Error, Result};
-use crate::cli::TransferParams;
-use crate::serial::serialize;
 
 use log::*;
 
@@ -11,7 +12,7 @@ use async_std::sync::Arc;
 use std::net::SocketAddr;
 
 pub type AdapterPtr = Arc<RpcAdapter>;
-// Dummy adapter for now
+
 pub struct RpcAdapter {
     pub wallet: Arc<WalletDb>,
     pub cashier_client: CashierClient,
@@ -32,7 +33,7 @@ impl RpcAdapter {
             wallet,
             cashier_client,
             connect_url,
-            publish_tx_send
+            publish_tx_send,
         })
     }
 
@@ -66,7 +67,7 @@ impl RpcAdapter {
 
     pub fn get_key(&self) -> Result<String> {
         debug!(target: "adapter", "get_key() [START]");
-        let key_public = self.wallet.get_public()?; 
+        let key_public = self.wallet.get_public()?;
         let bs58_address = bs58::encode(serialize(&key_public)).into_string();
         Ok(bs58_address)
     }
@@ -84,7 +85,7 @@ impl RpcAdapter {
         Ok(())
     }
 
-    pub async fn deposit(&mut self) -> Result<PubAddress> {
+    pub async fn deposit(&self) -> Result<PubAddress> {
         debug!(target: "deposit", "deposit: START");
         let (public, private) = self.wallet.key_gen();
         self.wallet.put_keypair(public, private)?;
@@ -100,6 +101,10 @@ impl RpcAdapter {
         Ok(())
     }
 
+    //pub async fn withdraw(&self, withdraw_params: WithdrawParams) -> Result<()> {
+    //    Ok(())
+    //}
+
     pub fn get_info(&self) {}
 
     pub fn say_hello(&self) {}

+ 13 - 8
src/rpc/jsonserver.rs

@@ -1,7 +1,7 @@
 use crate::cli::DarkfidConfig;
+use crate::cli::{TransferParams, WithdrawParams};
 use crate::rpc::adapter::RpcAdapter;
 use crate::{Error, Result};
-use crate::cli::{TransferParams, WithdrawParams};
 
 use async_executor::Executor;
 use async_native_tls::TlsAcceptor;
@@ -13,8 +13,6 @@ use smol::Async;
 use std::net::TcpListener;
 use std::sync::Arc;
 
-
-
 /// Listens for incoming connections and serves them.
 pub async fn listen(
     executor: Arc<Executor<'_>>,
@@ -240,13 +238,17 @@ impl RpcInterface {
             }
         });
 
-        //let mut self1 = self.clone();
+        // put adapter inside of mutex
+        let self1 = self.clone();
         io.add_method("deposit", move |_| {
-            //let self2 = self1.clone();
+            let self2 = self1.clone();
             async move {
                 println!("Deposit initiated");
-                //let btckey = self2.adapter.deposit().await?;
-                Ok(jsonrpc_core::Value::String("Initiating deposit... ".into()))
+                let btckey = self2.adapter.deposit().await?;
+                Ok(jsonrpc_core::Value::String(format!(
+                    "Send testnet BTC to: {}",
+                    btckey
+                )))
             }
         });
 
@@ -257,7 +259,10 @@ impl RpcInterface {
                 let parsed: TransferParams = params.parse().unwrap();
                 let address = parsed.pub_key.clone();
                 self2.adapter.transfer(parsed).await?;
-                Ok(jsonrpc_core::Value::String(format!("Transfer To: {}", address)))
+                Ok(jsonrpc_core::Value::String(format!(
+                    "Transfer To: {}",
+                    address
+                )))
             }
         });
 

+ 4 - 9
src/service/btc.rs

@@ -1,15 +1,14 @@
 use crate::{serial::deserialize, serial::serialize, Error, Result};
 
-use rand::{thread_rng, Rng};
 use rand::distributions::Alphanumeric;
+use rand::{thread_rng, Rng};
 
-use secp256k1::key::SecretKey;
-use bitcoin::util::ecdsa::{PrivateKey, PublicKey};
 use bitcoin::util::address::Address;
+use bitcoin::util::ecdsa::{PrivateKey, PublicKey};
+use secp256k1::key::SecretKey;
 
 use bitcoin::network::constants::Network;
 
-
 // Swap out these types for any future non bitcoin-rs types
 pub type PubAddress = Address;
 pub type PubKey = PublicKey;
@@ -23,10 +22,7 @@ pub struct BitcoinKeys {
 }
 
 impl BitcoinKeys {
-    pub fn new(
-
-    ) -> Result<BitcoinKeys> {
-
+    pub fn new() -> Result<BitcoinKeys> {
         let context = secp256k1::Secp256k1::new();
 
         // Probably not good enough for release
@@ -75,5 +71,4 @@ impl BitcoinKeys {
     pub fn get_privkey(&self) -> &PrivateKey {
         &self.bitcoin_private_key
     }
-
 }

+ 11 - 25
src/service/cashier.rs

@@ -2,19 +2,19 @@ use super::reqrep::{PeerId, RepProtocol, Reply, ReqProtocol, Request};
 
 use super::btc::{BitcoinKeys, PubAddress};
 
-use crate::{Error, Result};
-use crate::serial::{Decodable, Encodable, deserialize, serialize};
-use crate::wallet::CashierDbPtr;
-use crate::tx;
 use crate::crypto::load_params;
+use crate::serial::{deserialize, serialize, Decodable, Encodable};
+use crate::tx;
+use crate::wallet::CashierDbPtr;
+use crate::{Error, Result};
 
 use bellman::groth16;
 use bls12_381::Bls12;
 
-use std::net::SocketAddr;
-use async_std::sync::Arc;
 use async_executor::Executor;
+use async_std::sync::Arc;
 use log::*;
+use std::net::SocketAddr;
 
 #[repr(u8)]
 enum CashierError {
@@ -38,10 +38,7 @@ pub struct CashierService {
 }
 
 impl CashierService {
-    pub fn new(
-        addr: SocketAddr,
-        wallet: CashierDbPtr,
-    )-> Result<Arc<CashierService>> {
+    pub fn new(addr: SocketAddr, wallet: CashierDbPtr) -> Result<Arc<CashierService>> {
         // Load trusted setup parameters
         let (mint_params, mint_pvk) = load_params("mint.params")?;
         let (spend_params, spend_pvk) = load_params("spend.params")?;
@@ -56,7 +53,6 @@ impl CashierService {
         }))
     }
     pub async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
-
         debug!(target: "Cashier", "Start Cashier");
         let service_name = String::from("CASHIER DAEMON");
 
@@ -64,11 +60,8 @@ impl CashierService {
 
         let (send, recv) = protocol.start().await?;
 
-        let handle_request_task = executor.spawn(self.handle_request_loop(
-            send.clone(),
-            recv.clone(),
-            executor.clone(),
-        ));
+        let handle_request_task =
+            executor.spawn(self.handle_request_loop(send.clone(), recv.clone(), executor.clone()));
 
         protocol.run(executor.clone()).await?;
 
@@ -77,7 +70,6 @@ impl CashierService {
     }
 
     fn mint_dbtc(&self, dkey_pub: jubjub::SubgroupPoint, value: u64) -> Result<Vec<u8>> {
-
         let cashier_secret = self.wallet.get_cashier_private().unwrap();
 
         let builder = tx::TransactionBuilder {
@@ -164,9 +156,7 @@ impl CashierService {
 
                 // add to watchlist
 
-
                 info!("Received dkey->btc msg");
-
             }
             1 => {
                 // Withdraw
@@ -188,9 +178,7 @@ impl CashierClient {
     pub fn new(addr: SocketAddr) -> Result<Self> {
         let protocol = ReqProtocol::new(addr, String::from("CASHIER CLIENT"));
 
-        Ok(CashierClient {
-            protocol
-        })
+        Ok(CashierClient { protocol })
     }
 
     pub async fn start(&mut self) -> Result<()> {
@@ -200,7 +188,7 @@ impl CashierClient {
         Ok(())
     }
 
-    pub async fn get_address(&mut self, index: jubjub::SubgroupPoint) -> Result<Option<PubAddress>> {
+    pub async fn get_address(&self, index: jubjub::SubgroupPoint) -> Result<Option<PubAddress>> {
         let handle_error = Arc::new(handle_error);
         let rep = self
             .protocol
@@ -219,8 +207,6 @@ impl CashierClient {
         }
         Ok(None)
     }
-
-
 }
 
 fn handle_error(status_code: u32) {

+ 8 - 8
src/service/reqrep.rs

@@ -1,4 +1,4 @@
-use async_std::sync::Arc;
+use async_std::sync::{Arc, Mutex};
 use std::convert::TryFrom;
 use std::io;
 use std::net::SocketAddr;
@@ -123,13 +123,13 @@ impl RepProtocol {
 
 pub struct ReqProtocol {
     addr: SocketAddr,
-    socket: zeromq::DealerSocket,
+    socket: Mutex<zeromq::DealerSocket>,
     service_name: String,
 }
 
 impl ReqProtocol {
     pub fn new(addr: SocketAddr, service_name: String) -> ReqProtocol {
-        let socket = zeromq::DealerSocket::new();
+        let socket = Mutex::new(zeromq::DealerSocket::new());
         ReqProtocol {
             addr,
             socket,
@@ -137,15 +137,15 @@ impl ReqProtocol {
         }
     }
 
-    pub async fn start(&mut self) -> Result<()> {
+    pub async fn start(&self) -> Result<()> {
         let addr = addr_to_string(self.addr);
-        self.socket.connect(addr.as_str()).await?;
+        self.socket.lock().await.connect(addr.as_str()).await?;
         info!("{} SERVICE: Connected To {}", self.service_name, self.addr);
         Ok(())
     }
 
     pub async fn request(
-        &mut self,
+        &self,
         command: u8,
         data: Vec<u8>,
         handle_error: Arc<dyn Fn(u32) + Send + Sync>,
@@ -155,13 +155,13 @@ impl ReqProtocol {
         let req = bytes::Bytes::from(req);
         let req: zeromq::ZmqMessage = req.into();
 
-        self.socket.send(req).await?;
+        self.socket.lock().await.send(req).await?;
         info!(
             "{} SERVICE: Sent Request {{ command: {} }}",
             self.service_name, command
         );
 
-        let rep: zeromq::ZmqMessage = self.socket.recv().await?;
+        let rep: zeromq::ZmqMessage = self.socket.lock().await.recv().await?;
         if let Some(reply) = rep.get(0) {
             let reply: Vec<u8> = reply.to_vec();
 

+ 1 - 1
src/vm_serial.rs

@@ -108,7 +108,7 @@ impl Decodable for (AllocType, VariableIndex) {
 impl_vec!((AllocType, VariableIndex));
 
 impl Encodable for VariableIndex {
-    fn encode<S: io::Write>(&self,s: S) -> Result<usize> {
+    fn encode<S: io::Write>(&self, s: S) -> Result<usize> {
         let len = Encodable::encode(&((*self) as u64), s)?;
         Ok(len)
     }

+ 1 - 1
src/wallet/cashierdb.rs

@@ -1,8 +1,8 @@
 use crate::serial;
 use crate::serial::{deserialize, serialize, Decodable, Encodable};
+use crate::service::btc::{PrivKey, PubKey};
 use crate::util::join_config_path;
 use crate::{Error, Result};
-use crate::service::btc::{PrivKey, PubKey};
 
 use async_std::sync::Arc;
 use ff::Field;

+ 2 - 2
src/wallet/mod.rs

@@ -1,5 +1,5 @@
-pub mod walletdb;
 pub mod cashierdb;
+pub mod walletdb;
 
-pub use walletdb::{WalletDb, WalletPtr};
 pub use cashierdb::{CashierDb, CashierDbPtr};
+pub use walletdb::{WalletDb, WalletPtr};