Some more cleanups and formatting.

This commit is contained in:
parazyd
2021-10-01 14:10:30 +02:00
parent 606b06b89e
commit b77da89ce6
14 changed files with 72 additions and 49 deletions

View File

@@ -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,
)?;
}

View File

@@ -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,

View File

@@ -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();

View File

@@ -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"),

View File

@@ -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;

View File

@@ -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(())
}

View File

@@ -93,7 +93,11 @@ impl Bridge {
.map(|o| o.map_err(Error::from))
}
pub async fn subscribe(self: Arc<Self>, drk_pub_key: jubjub::SubgroupPoint, mint: Option<String>) -> BridgeSubscribtion {
pub async fn subscribe(
self: Arc<Self>,
drk_pub_key: jubjub::SubgroupPoint,
mint: Option<String>,
) -> 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<String> = 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<dyn NetworkClient + Send + Sync>;
@@ -176,7 +178,11 @@ impl Bridge {
#[async_trait]
pub trait NetworkClient {
async fn subscribe(self: Arc<Self>, drk_pub_key: jubjub::SubgroupPoint, mint: Option<String>) -> Result<TokenSubscribtion>;
async fn subscribe(
self: Arc<Self>,
drk_pub_key: jubjub::SubgroupPoint,
mint: Option<String>,
) -> Result<TokenSubscribtion>;
// should check if the keypair in not already subscribed
async fn subscribe_with_keypair(

View File

@@ -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<Keypair> {
pub fn from_bytes(bytes: &[u8]) -> Result<Keypair> {
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 {}

View File

@@ -14,6 +14,3 @@ pub mod sol;
pub use sol::{SolClient, SolFailed, SolResult};
pub use gateway::{GatewayClient, GatewayService, GatewaySlabsSubscriber};

View File

@@ -16,6 +16,11 @@ use zeromq::*;
pub type PeerId = Vec<u8>;
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,
}

View File

@@ -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)
}
}
}

View File

@@ -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<jubjub::Fr> {
let mut id_string = network.to_string();
id_string.push_str(tkn_str);

View File

@@ -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![];

View File

@@ -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};