diff --git a/src/bin/cashierd.rs b/src/bin/cashierd.rs index 20271ccc8..8ae7ece5b 100644 --- a/src/bin/cashierd.rs +++ b/src/bin/cashierd.rs @@ -262,7 +262,7 @@ impl Cashierd { &serialize(&token_pub), &network, &token_id, - &mint_address, + mint_address, )?; return Ok(token_pub); @@ -303,7 +303,6 @@ impl Cashierd { let network = NetworkName::from_str(args[0].as_str().unwrap()).unwrap(); - if mint_address.as_str().is_none() { return JsonResult::Err(jsonerr(InvalidTokenIdParam, None, id)); } @@ -316,7 +315,6 @@ impl Cashierd { let address = address.as_str().unwrap(); - if amount.as_u64().is_none() { return JsonResult::Err(jsonerr(InvalidAmountParam, None, id)); } @@ -361,7 +359,7 @@ impl Cashierd { &cashier_secret, &network, &token_id, - &mint_address, + mint_address, )?; } diff --git a/src/bin/darkfid.rs b/src/bin/darkfid.rs index f961c25dd..255616242 100644 --- a/src/bin/darkfid.rs +++ b/src/bin/darkfid.rs @@ -14,7 +14,7 @@ use drk::{ client::Client, rpc::{ jsonrpc::{error as jsonerr, request as jsonreq, response as jsonresp, send_request}, - jsonrpc::{ErrorCode::*, JsonError, JsonRequest, JsonResult}, + jsonrpc::{ErrorCode::*, JsonRequest, JsonResult}, rpcserver::{listen_and_serve, RequestHandler, RpcServerConfig}, }, serial::serialize, diff --git a/src/client/client.rs b/src/client/client.rs index 754e55718..c2ce3f35e 100644 --- a/src/client/client.rs +++ b/src/client/client.rs @@ -51,7 +51,7 @@ impl Client { wallet.init_db().await?; - if wallet.get_keypairs()?.len() == 0 { + if wallet.get_keypairs()?.is_empty() { wallet.key_gen()?; } @@ -104,7 +104,7 @@ impl Client { pub_key: jubjub::SubgroupPoint, amount: u64, ) -> Result<()> { - if amount <= 0 { + if amount == 0 { return Err(ClientFailed::InvalidAmount(amount as u64).into()); } @@ -268,7 +268,6 @@ impl Client { let (notify, _) = async_channel::unbounded::<(jubjub::SubgroupPoint, u64)>(); - let secret_key = self.main_keypair.private; let state = self.state.clone(); diff --git a/src/client/mod.rs b/src/client/mod.rs index 660c7b8df..2911967fa 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -37,7 +37,9 @@ impl fmt::Display for ClientFailed { ClientFailed::UnableToGetWithdrawAddress => { f.write_str("Unable to get withdraw address") } - ClientFailed::DoesNotHaveCashierPublicKey => f.write_str("Does not have cashier public key"), + ClientFailed::DoesNotHaveCashierPublicKey => { + f.write_str("Does not have cashier public key") + } ClientFailed::DoesNotHaveKeypair => f.write_str("Does not have keypair"), ClientFailed::EmptyPassword => f.write_str("Password is empty. Cannot create database"), ClientFailed::WalletInitialized => f.write_str("Wallet already initalized"), diff --git a/src/crypto/note.rs b/src/crypto/note.rs index 457465cd3..6092ff48f 100644 --- a/src/crypto/note.rs +++ b/src/crypto/note.rs @@ -7,12 +7,11 @@ use super::diffie_hellman::{kdf_sapling, sapling_ka_agree}; use crate::error::{Error, Result}; use crate::serial::{Decodable, Encodable, ReadExt, WriteExt}; -pub const NOTE_PLAINTEXT_SIZE: usize = - 32 + // serial +pub const NOTE_PLAINTEXT_SIZE: usize = 32 + // serial 8 + // value 32 + // asset_id 32 + // coin_blind - 32; // valcom_blind + 32; // valcom_blind pub const AEAD_TAG_SIZE: usize = 16; pub const ENC_CIPHERTEXT_SIZE: usize = NOTE_PLAINTEXT_SIZE + AEAD_TAG_SIZE; diff --git a/src/net/protocols/protocol_version.rs b/src/net/protocols/protocol_version.rs index 4538bbe4d..dbf05cc6c 100644 --- a/src/net/protocols/protocol_version.rs +++ b/src/net/protocols/protocol_version.rs @@ -67,7 +67,9 @@ impl ProtocolVersion { let send = executor.spawn(self.clone().send_version()); let recv = executor.spawn(self.recv_version()); - send.await.and(recv.await)?; + send.await?; + recv.await?; + debug!(target: "net", "ProtocolVersion::exchange_versions() [END]"); Ok(()) } diff --git a/src/service/bridge.rs b/src/service/bridge.rs index 4aef9d30c..3c014e48a 100644 --- a/src/service/bridge.rs +++ b/src/service/bridge.rs @@ -93,7 +93,11 @@ impl Bridge { .map(|o| o.map_err(Error::from)) } - pub async fn subscribe(self: Arc, drk_pub_key: jubjub::SubgroupPoint, mint: Option) -> BridgeSubscribtion { + pub async fn subscribe( + self: Arc, + drk_pub_key: jubjub::SubgroupPoint, + mint: Option, + ) -> BridgeSubscribtion { debug!(target: "BRIDGE", "Start new subscription"); let (sender, req) = async_channel::unbounded(); let (rep, receiver) = async_channel::unbounded(); @@ -126,10 +130,8 @@ impl Bridge { let mut mint_address: Option = mint.clone(); - if mint.is_some() { - if mint.unwrap().is_empty() { - mint_address = None; - } + if mint.is_some() && mint.unwrap().is_empty() { + mint_address = None; } let client: Arc; @@ -176,7 +178,11 @@ impl Bridge { #[async_trait] pub trait NetworkClient { - async fn subscribe(self: Arc, drk_pub_key: jubjub::SubgroupPoint, mint: Option) -> Result; + async fn subscribe( + self: Arc, + drk_pub_key: jubjub::SubgroupPoint, + mint: Option, + ) -> Result; // should check if the keypair in not already subscribed async fn subscribe_with_keypair( diff --git a/src/service/btc.rs b/src/service/btc.rs index 3c4c1f2f7..0851fd91b 100644 --- a/src/service/btc.rs +++ b/src/service/btc.rs @@ -1,7 +1,6 @@ use super::bridge::{NetworkClient, TokenNotification, TokenSubscribtion}; -use crate::serial::{serialize, deserialize, Decodable, Encodable}; +use crate::serial::{deserialize, serialize, Decodable, Encodable}; use crate::{Error, Result}; -use std::convert::From; use async_trait::async_trait; use bitcoin::blockdata::script::Script; use bitcoin::hash_types::{PubkeyHash as BtcPubKeyHash, Txid}; @@ -10,9 +9,10 @@ use bitcoin::util::address::Address; use bitcoin::util::ecdsa::{PrivateKey as BtcPrivKey, PublicKey as BtcPubKey}; use electrum_client::{Client as ElectrumClient, ElectrumApi}; use log::*; +use std::convert::From; +use secp256k1::constants::{PUBLIC_KEY_SIZE, SECRET_KEY_SIZE}; use secp256k1::key::{PublicKey, SecretKey}; -use secp256k1::constants::{SECRET_KEY_SIZE, PUBLIC_KEY_SIZE}; use secp256k1::{rand::rngs::OsRng, Secp256k1}; use async_std::sync::Arc; @@ -35,20 +35,18 @@ impl Keypair { let mut rng = OsRng::new().expect("OsRng"); let (secret, public) = secp.generate_keypair(&mut rng); - Self { - secret, - public, - } + Self { secret, public } } + pub fn to_bytes(&self) -> [u8; KEYPAIR_LENGTH] { let mut bytes: [u8; KEYPAIR_LENGTH] = [0u8; KEYPAIR_LENGTH]; bytes[..SECRET_KEY_SIZE].copy_from_slice(self.secret.as_ref()); bytes[SECRET_KEY_SIZE..].copy_from_slice(&self.public.serialize()); bytes - } - pub fn from_bytes<'a>(bytes: &'a [u8]) -> Result { + + pub fn from_bytes(bytes: &[u8]) -> Result { if bytes.len() != KEYPAIR_LENGTH { return Err(Error::BtcFailed("Not right size".to_string())); } @@ -56,12 +54,20 @@ impl Keypair { let secret = SecretKey::from_slice(&bytes[..SECRET_KEY_SIZE]).unwrap(); let public = PublicKey::from_slice(&bytes[SECRET_KEY_SIZE..]).unwrap(); - Ok(Keypair{ secret: secret, public: public }) + Ok(Keypair { secret, public }) } + pub fn pubkey(&self) -> PublicKey { self.public } } + +impl Default for Keypair { + fn default() -> Self { + Self::new() + } +} + pub struct BitcoinKeys { _secret_key: SecretKey, public_key: PublicKey, @@ -94,18 +100,23 @@ impl BitcoinKeys { pub fn pubkey(&self) -> &PublicKey { &self.public_key } + pub fn btc_privkey(&self) -> &BtcPrivKey { &self.btc_privkey } + pub fn btc_pubkey(&self) -> &BtcPubKey { &self.btc_pubkey } + pub fn btc_pubkey_hash(&self) -> BtcPubKeyHash { self.btc_pubkey.pubkey_hash() } + pub fn derive_btc_address(btc_pubkey: BtcPubKey, network: Network) -> Address { Address::p2pkh(&btc_pubkey, network) } + pub fn derive_script(btc_pubkey_hash: BtcPubKeyHash) -> Script { Script::new_p2pkh(&btc_pubkey_hash) } @@ -330,7 +341,7 @@ pub enum BtcFailed { ElectrumError(String), BtcError(String), DecodeAndEncodeError(String), - KeypairError(String) + KeypairError(String), } impl std::error::Error for BtcFailed {} diff --git a/src/service/mod.rs b/src/service/mod.rs index a955db5ef..bae2cf08f 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -14,6 +14,3 @@ pub mod sol; pub use sol::{SolClient, SolFailed, SolResult}; pub use gateway::{GatewayClient, GatewayService, GatewaySlabsSubscriber}; - - - diff --git a/src/service/reqrep.rs b/src/service/reqrep.rs index 1a64690b9..32146423d 100644 --- a/src/service/reqrep.rs +++ b/src/service/reqrep.rs @@ -16,6 +16,11 @@ use zeromq::*; pub type PeerId = Vec; +pub type Channels = ( + async_channel::Sender<(PeerId, Reply)>, + async_channel::Receiver<(PeerId, Request)>, +); + enum NetEvent { Receive(zeromq::ZmqMessage), Send((PeerId, Reply)), @@ -31,10 +36,7 @@ pub struct RepProtocol { socket: zeromq::RouterSocket, recv_queue: async_channel::Receiver<(PeerId, Reply)>, send_queue: async_channel::Sender<(PeerId, Request)>, - channels: ( - async_channel::Sender<(PeerId, Reply)>, - async_channel::Receiver<(PeerId, Request)>, - ), + channels: Channels, service_name: String, } diff --git a/src/service/sol.rs b/src/service/sol.rs index 3943a8ee0..ce8753912 100644 --- a/src/service/sol.rs +++ b/src/service/sol.rs @@ -345,12 +345,12 @@ impl SolClient { let rpc = RpcClient::new(self.rpc_server.to_string()); if !account_is_initialized_mint(&rpc, &pubkey) { - return Err(SolFailed::MintIsNotValid(mint_addr.to_string())); + return Err(SolFailed::MintIsNotValid(mint_addr)); } - return Ok(Some(pubkey)); + Ok(Some(pubkey)) } else { - return Ok(None); + Ok(None) } } } diff --git a/src/util/parse.rs b/src/util/parse.rs index 46417ed08..87a3ffa40 100644 --- a/src/util/parse.rs +++ b/src/util/parse.rs @@ -12,7 +12,6 @@ use crate::{ // hash the external token ID and NetworkName param. // if fails, change the last 4 bytes and hash it again. keep repeating until it works. pub fn generate_id(tkn_str: &str, network: &NetworkName) -> Result { - let mut id_string = network.to_string(); id_string.push_str(tkn_str); diff --git a/src/wallet/cashierdb.rs b/src/wallet/cashierdb.rs index a97116705..eb63cd0b8 100644 --- a/src/wallet/cashierdb.rs +++ b/src/wallet/cashierdb.rs @@ -123,7 +123,7 @@ impl CashierDb { d_key_private: &jubjub::Fr, network: &NetworkName, token_id: &jubjub::Fr, - mint_address: &String, + mint_address: String, ) -> Result<()> { debug!(target: "CASHIERDB", "Put withdraw keys"); @@ -132,7 +132,7 @@ impl CashierDb { let network = self.get_value_serialized(network)?; let token_id = self.get_value_serialized(token_id)?; let confirm = self.get_value_serialized(&false)?; - let mint_address = self.get_value_serialized(mint_address)?; + let mint_address = self.get_value_serialized(&mint_address)?; // open connection let conn = Connection::open(&self.path)?; @@ -164,7 +164,7 @@ impl CashierDb { token_key_public: &[u8], network: &NetworkName, token_id: &jubjub::Fr, - mint_address: &String, + mint_address: String, ) -> Result<()> { debug!(target: "CASHIERDB", "Put exchange keys"); @@ -178,7 +178,7 @@ impl CashierDb { let network = self.get_value_serialized(network)?; let confirm = self.get_value_serialized(&false)?; - let mint_address = self.get_value_serialized(mint_address)?; + let mint_address = self.get_value_serialized(&mint_address)?; conn.execute( "INSERT INTO deposit_keypairs @@ -226,6 +226,7 @@ impl CashierDb { } // return token public key, network name, and token_id as tuple + #[allow(clippy::type_complexity)] pub fn get_withdraw_token_public_key_by_dkey_public( &self, pub_key: &jubjub::SubgroupPoint, @@ -306,6 +307,7 @@ impl CashierDb { } // return drk_pub_key, private key, public key, token_id, and mint_address as a tuple + #[allow(clippy::type_complexity)] pub fn get_deposit_token_keys_by_network( &self, network: &NetworkName, @@ -325,9 +327,15 @@ impl CashierDb { WHERE network = :network AND confirm = :confirm ;", )?; - let keys_iter = stmt - .query_map(&[(":network", &network), (":confirm", &confirm)], |row| { - Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?)) + let keys_iter = + stmt.query_map(&[(":network", &network), (":confirm", &confirm)], |row| { + Ok(( + row.get(0)?, + row.get(1)?, + row.get(2)?, + row.get(3)?, + row.get(4)?, + )) })?; let mut keys = vec![]; diff --git a/src/wallet/mod.rs b/src/wallet/mod.rs index b018a6760..9abde8812 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -4,4 +4,4 @@ pub mod walletdb; pub use cashierdb::{CashierDb, CashierDbPtr}; pub use wallet_api::WalletApi; -pub use walletdb::{WalletDb, WalletPtr, Keypair}; +pub use walletdb::{Keypair, WalletDb, WalletPtr};