Просмотр исходного кода

Merge branch 'halo2-integration' of github.com:darkrenaissance/darkfi into halo2-integration

narodnik 4 лет назад
Родитель
Сommit
6c69db1099
4 измененных файлов с 102 добавлено и 76 удалено
  1. 2 1
      src/crypto/mod.rs
  2. 20 0
      src/crypto/types.rs
  3. 29 29
      src/wallet/cashierdb.rs
  4. 51 46
      src/wallet/walletdb.rs

+ 2 - 1
src/crypto/mod.rs

@@ -8,6 +8,7 @@ pub mod note;
 pub mod nullifier;
 pub mod schnorr;
 pub mod spend_proof;
+pub mod types;
 pub mod util;
 
 use bellman::groth16;
@@ -25,7 +26,7 @@ pub struct OwnCoin {
     pub note: note::Note,
     pub secret: jubjub::Fr,
     pub witness: merkle::IncrementalWitness<merkle_node::MerkleNode>,
-    pub nullifier: nullifier::Nullifier 
+    pub nullifier: nullifier::Nullifier,
 }
 
 pub type OwnCoins = Vec<OwnCoin>;

+ 20 - 0
src/crypto/types.rs

@@ -0,0 +1,20 @@
+//! Type aliases used in the codebase.
+// Helpful for changing the curve and crypto we're using.
+
+pub type PublicKey = jubjub::SubgroupPoint;
+
+pub type SecretKey = jubjub::Fr;
+
+pub fn derive_publickey(secret: SecretKey) -> PublicKey {
+    zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret
+}
+
+pub type TokenId = jubjub::Fr;
+
+pub type NullifierSerial = jubjub::Fr;
+
+pub type CoinBlind = jubjub::Fr;
+
+pub type ValueCommitBlind = jubjub::Fr;
+
+pub type TokenCommitBlind = jubjub::Fr;

+ 29 - 29
src/wallet/cashierdb.rs

@@ -1,11 +1,12 @@
 use async_std::sync::{Arc, Mutex};
 use std::path::{Path, PathBuf};
 
-use log::*;
+use log::debug;
 use rusqlite::{named_params, params, Connection};
 
 use super::{Keypair, WalletApi};
 use crate::client::ClientFailed;
+use crate::crypto::types::{PublicKey, SecretKey, TokenId};
 use crate::util::NetworkName;
 use crate::{Error, Result};
 
@@ -26,14 +27,14 @@ pub struct TokenKey {
 pub struct WithdrawToken {
     pub token_public_key: Vec<u8>,
     pub network: NetworkName,
-    pub token_id: jubjub::Fr,
+    pub token_id: TokenId,
     pub mint_address: String,
 }
 
 pub struct DepositToken {
-    pub drk_public_key: jubjub::SubgroupPoint,
+    pub drk_public_key: PublicKey,
     pub token_key: TokenKey,
-    pub token_id: jubjub::Fr,
+    pub token_id: TokenId,
     pub mint_address: String,
 }
 
@@ -148,15 +149,13 @@ impl CashierDb {
         Ok(())
     }
 
-
-
     pub fn put_withdraw_keys(
         &self,
         token_key_public: &[u8],
-        d_key_public: &jubjub::SubgroupPoint,
-        d_key_private: &jubjub::Fr,
+        d_key_public: &PublicKey,
+        d_key_private: &SecretKey,
         network: &NetworkName,
-        token_id: &jubjub::Fr,
+        token_id: &TokenId,
         mint_address: String,
     ) -> Result<()> {
         debug!(target: "CASHIERDB", "Put withdraw keys");
@@ -193,11 +192,11 @@ impl CashierDb {
 
     pub fn put_deposit_keys(
         &self,
-        d_key_public: &jubjub::SubgroupPoint,
+        d_key_public: &PublicKey,
         token_key_private: &[u8],
         token_key_public: &[u8],
         network: &NetworkName,
-        token_id: &jubjub::Fr,
+        token_id: &TokenId,
         mint_address: String,
     ) -> Result<()> {
         debug!(target: "CASHIERDB", "Put exchange keys");
@@ -232,7 +231,7 @@ impl CashierDb {
         Ok(())
     }
 
-    pub fn get_withdraw_private_keys(&self) -> Result<Vec<jubjub::Fr>> {
+    pub fn get_withdraw_private_keys(&self) -> Result<Vec<SecretKey>> {
         debug!(target: "CASHIERDB", "Get withdraw private keys");
         // open connection
         let conn = Connection::open(&self.path)?;
@@ -249,10 +248,10 @@ impl CashierDb {
 
         let keys = stmt.query_map(&[(":confirm", &confirm)], |row| Ok(row.get(0)))?;
 
-        let mut private_keys: Vec<jubjub::Fr> = vec![];
+        let mut private_keys: Vec<SecretKey> = vec![];
 
         for k in keys {
-            let private_key: jubjub::Fr = self.get_value_deserialized(k??)?;
+            let private_key: SecretKey = self.get_value_deserialized(k??)?;
             private_keys.push(private_key);
         }
 
@@ -261,7 +260,7 @@ impl CashierDb {
 
     pub fn get_withdraw_token_public_key_by_dkey_public(
         &self,
-        pub_key: &jubjub::SubgroupPoint,
+        pub_key: &PublicKey,
     ) -> Result<Option<WithdrawToken>> {
         debug!(target: "CASHIERDB", "Get token address by pub_key");
         // open connection
@@ -289,7 +288,7 @@ impl CashierDb {
             let addr = addr?;
             let token_public_key = addr.0;
             let network: NetworkName = self.get_value_deserialized(addr.1)?;
-            let token_id: jubjub::Fr = self.get_value_deserialized(addr.2)?;
+            let token_id: TokenId = self.get_value_deserialized(addr.2)?;
             let mint_address: String = self.get_value_deserialized(addr.3)?;
             token_addresses.push(WithdrawToken {
                 token_public_key,
@@ -304,7 +303,7 @@ impl CashierDb {
 
     pub fn get_deposit_token_keys_by_dkey_public(
         &self,
-        d_key_public: &jubjub::SubgroupPoint,
+        d_key_public: &PublicKey,
         network: &NetworkName,
     ) -> Result<Vec<TokenKey>> {
         debug!(target: "CASHIERDB", "Check for existing dkey");
@@ -380,10 +379,10 @@ impl CashierDb {
 
         for key in keys_iter {
             let key = key?;
-            let drk_public_key: jubjub::SubgroupPoint = self.get_value_deserialized(key.0)?;
+            let drk_public_key: PublicKey = self.get_value_deserialized(key.0)?;
             let private_key = key.1;
             let public_key = key.2;
-            let token_id: jubjub::Fr = self.get_value_deserialized(key.3)?;
+            let token_id: TokenId = self.get_value_deserialized(key.3)?;
             let mint_address: String = self.get_value_deserialized(key.4)?;
             keys.push(DepositToken {
                 drk_public_key,
@@ -434,8 +433,8 @@ impl CashierDb {
 
         for kp in keypair_iter {
             let kp = kp?;
-            let public: jubjub::SubgroupPoint = self.get_value_deserialized(kp.1)?;
-            let private: jubjub::Fr = self.get_value_deserialized(kp.0)?;
+            let public: PublicKey = self.get_value_deserialized(kp.1)?;
+            let private: SecretKey = self.get_value_deserialized(kp.0)?;
             let keypair = Keypair { public, private };
             keypairs.push(keypair);
         }
@@ -471,7 +470,7 @@ impl CashierDb {
 
     pub fn confirm_deposit_key_record(
         &self,
-        d_key_public: &jubjub::SubgroupPoint,
+        d_key_public: &PublicKey,
         network: &NetworkName,
     ) -> Result<()> {
         debug!(target: "CASHIERDB", "Confirm withdraw keys");
@@ -501,6 +500,7 @@ impl CashierDb {
 mod tests {
 
     use super::*;
+    use crate::crypto::types::derive_publickey;
     use crate::serial::serialize;
     use crate::util::join_config_path;
 
@@ -567,9 +567,9 @@ mod tests {
 
         let network = NetworkName::Bitcoin;
 
-        let secret2: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
-        let public2 = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret2;
-        let token_id: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
+        let secret2 = SecretKey::random(&mut OsRng);
+        let public2 = derive_publickey(secret2);
+        let token_id = TokenId::random(&mut OsRng);
 
         wallet.put_deposit_keys(
             &public2,
@@ -612,9 +612,9 @@ mod tests {
         let wallet = CashierDb::new(&walletdb_path, password.clone())?;
         init_db(&walletdb_path, password)?;
 
-        let secret2: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
-        let public2 = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret2;
-        let token_id: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
+        let secret2: SecretKey = SecretKey::random(&mut OsRng);
+        let public2 = derive_publickey(secret2);
+        let token_id: TokenId = TokenId::random(&mut OsRng);
 
         // btc addr testnet
         let token_addr = serialize(&String::from("mxVFsFW5N4mu1HPkxPttorvocvzeZ7KZyk"));
@@ -652,7 +652,7 @@ mod tests {
         let addr = wallet.get_withdraw_keys_by_token_public_key(&token_addr, &network)?;
 
         assert!(addr.is_some());
-        
+
         wallet.remove_withdraw_and_deposit_keys()?;
 
         std::fs::remove_file(walletdb_path)?;

+ 51 - 46
src/wallet/walletdb.rs

@@ -10,8 +10,13 @@ use rusqlite::{named_params, params, Connection};
 use super::WalletApi;
 use crate::client::ClientFailed;
 use crate::crypto::{
-    coin::Coin, merkle::IncrementalWitness, merkle_node::MerkleNode, note::Note,
-    nullifier::Nullifier, OwnCoin, OwnCoins,
+    coin::Coin,
+    merkle::IncrementalWitness,
+    merkle_node::MerkleNode,
+    note::Note,
+    nullifier::Nullifier,
+    types::{PublicKey, SecretKey, TokenId},
+    OwnCoin, OwnCoins,
 };
 use crate::serial;
 use crate::{Error, Result};
@@ -20,13 +25,13 @@ pub type WalletPtr = Arc<WalletDb>;
 
 #[derive(Debug, Clone)]
 pub struct Keypair {
-    pub public: jubjub::SubgroupPoint,
-    pub private: jubjub::Fr,
+    pub public: PublicKey,
+    pub private: SecretKey,
 }
 
 #[derive(Debug, Clone)]
 pub struct Balance {
-    pub token_id: jubjub::Fr,
+    pub token_id: TokenId,
     pub value: u64,
     pub nullifier: Nullifier,
 }
@@ -98,8 +103,8 @@ impl WalletDb {
         let mut stmt = conn.prepare("SELECT * FROM keys WHERE key_id > ?")?;
         let key_check = stmt.exists(params!["0"])?;
         if !key_check {
-            let secret: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
-            let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
+            let secret: SecretKey = SecretKey::random(&mut OsRng);
+            let public: PublicKey = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
             self.put_keypair(&public, &secret)?;
         } else {
             debug!(target: "WALLETDB", "Keys already exist.");
@@ -108,11 +113,7 @@ impl WalletDb {
         Ok(())
     }
 
-    pub fn put_keypair(
-        &self,
-        key_public: &jubjub::SubgroupPoint,
-        key_private: &jubjub::Fr,
-    ) -> Result<()> {
+    pub fn put_keypair(&self, key_public: &PublicKey, key_private: &SecretKey) -> Result<()> {
         let conn = Connection::open(&self.path)?;
 
         conn.pragma_update(None, "key", &self.password)?;
@@ -140,8 +141,8 @@ impl WalletDb {
             let key = key?;
             let public = key.0;
             let private = key.1;
-            let public: jubjub::SubgroupPoint = self.get_value_deserialized(public)?;
-            let private: jubjub::Fr = self.get_value_deserialized(private)?;
+            let public: PublicKey = self.get_value_deserialized(public)?;
+            let private: SecretKey = self.get_value_deserialized(private)?;
             keypairs.push(Keypair { public, private });
         }
 
@@ -194,7 +195,7 @@ impl WalletDb {
             };
 
             let witness = self.get_value_deserialized(row.6)?;
-            let secret: jubjub::Fr = self.get_value_deserialized(row.7)?;
+            let secret: SecretKey = self.get_value_deserialized(row.7)?;
             let nullifier: Nullifier = self.get_value_deserialized(row.8)?;
 
             let oc = OwnCoin {
@@ -353,7 +354,7 @@ impl WalletDb {
         for row in rows {
             let row = row?;
             let value: u64 = row.0;
-            let token_id: jubjub::Fr = self.get_value_deserialized(row.1)?;
+            let token_id: TokenId = self.get_value_deserialized(row.1)?;
             let nullifier: Nullifier = self.get_value_deserialized(row.2)?;
             balances.add(&Balance {
                 token_id,
@@ -365,7 +366,7 @@ impl WalletDb {
         Ok(balances)
     }
 
-    pub fn get_token_id(&self) -> Result<Vec<jubjub::Fr>> {
+    pub fn get_token_id(&self) -> Result<Vec<TokenId>> {
         debug!(target: "WALLETDB", "Get token ID...");
         let conn = Connection::open(&self.path)?;
         conn.pragma_update(None, "key", &self.password)?;
@@ -386,7 +387,7 @@ impl WalletDb {
         Ok(token_ids)
     }
 
-    pub fn token_id_exists(&self, token_id: &jubjub::Fr) -> Result<bool> {
+    pub fn token_id_exists(&self, token_id: &TokenId) -> Result<bool> {
         debug!(target: "WALLETDB", "Check tokenID exists");
         let conn = Connection::open(&self.path)?;
         conn.pragma_update(None, "key", &self.password)?;
@@ -410,9 +411,13 @@ impl WalletDb {
 
 #[cfg(test)]
 mod tests {
-
+    // TODO: Clean up, there's a lot of duplicated code here.
     use super::*;
-    use crate::crypto::{coin::Coin, OwnCoin};
+    use crate::crypto::{
+        coin::Coin,
+        types::{derive_publickey, CoinBlind, NullifierSerial, ValueCommitBlind},
+        OwnCoin,
+    };
     use crate::util::join_config_path;
     use ff::PrimeField;
 
@@ -439,19 +444,19 @@ mod tests {
         let wallet = WalletDb::new(&walletdb_path, password.clone())?;
         init_db(&walletdb_path, password)?;
 
-        let secret: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
-        let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
+        let secret = SecretKey::random(&mut OsRng);
+        let public = derive_publickey(secret);
 
         wallet.put_keypair(&public, &secret)?;
 
-        let token_id = jubjub::Fr::random(&mut OsRng);
+        let token_id = TokenId::random(&mut OsRng);
 
         let note = Note {
-            serial: jubjub::Fr::random(&mut OsRng),
+            serial: NullifierSerial::random(&mut OsRng),
             value: 110,
             token_id,
-            coin_blind: jubjub::Fr::random(&mut OsRng),
-            valcom_blind: jubjub::Fr::random(&mut OsRng),
+            coin_blind: CoinBlind::random(&mut OsRng),
+            valcom_blind: ValueCommitBlind::random(&mut OsRng),
         };
 
         let coin = Coin::new(bls12_381::Scalar::random(&mut OsRng).to_repr());
@@ -497,19 +502,19 @@ mod tests {
         let wallet = WalletDb::new(&walletdb_path, password.clone())?;
         init_db(&walletdb_path, password)?;
 
-        let secret: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
-        let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
+        let secret = SecretKey::random(&mut OsRng);
+        let public = derive_publickey(secret);
 
         wallet.put_keypair(&public, &secret)?;
 
-        let token_id = jubjub::Fr::random(&mut OsRng);
+        let token_id = TokenId::random(&mut OsRng);
 
         let note = Note {
-            serial: jubjub::Fr::random(&mut OsRng),
+            serial: NullifierSerial::random(&mut OsRng),
             value: 110,
             token_id,
-            coin_blind: jubjub::Fr::random(&mut OsRng),
-            valcom_blind: jubjub::Fr::random(&mut OsRng),
+            coin_blind: CoinBlind::random(&mut OsRng),
+            valcom_blind: ValueCommitBlind::random(&mut OsRng),
         };
 
         let coin = Coin::new(bls12_381::Scalar::random(&mut OsRng).to_repr());
@@ -552,8 +557,8 @@ mod tests {
         let wallet = WalletDb::new(&walletdb_path, password.clone())?;
         init_db(&walletdb_path, password)?;
 
-        let secret: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
-        let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
+        let secret = SecretKey::random(&mut OsRng);
+        let public = derive_publickey(secret);
 
         wallet.put_keypair(&public, &secret)?;
 
@@ -574,17 +579,17 @@ mod tests {
         let wallet = WalletDb::new(&walletdb_path, password.clone())?;
         init_db(&walletdb_path, password)?;
 
-        let secret: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
-        let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
+        let secret = SecretKey::random(&mut OsRng);
+        let public = derive_publickey(secret);
 
         wallet.put_keypair(&public, &secret)?;
 
         let note = Note {
-            serial: jubjub::Fr::random(&mut OsRng),
+            serial: NullifierSerial::random(&mut OsRng),
             value: 110,
-            token_id: jubjub::Fr::random(&mut OsRng),
-            coin_blind: jubjub::Fr::random(&mut OsRng),
-            valcom_blind: jubjub::Fr::random(&mut OsRng),
+            token_id: TokenId::random(&mut OsRng),
+            coin_blind: CoinBlind::random(&mut OsRng),
+            valcom_blind: ValueCommitBlind::random(&mut OsRng),
         };
 
         let coin = Coin::new(bls12_381::Scalar::random(&mut OsRng).to_repr());
@@ -645,19 +650,19 @@ mod tests {
         let wallet = WalletDb::new(&walletdb_path, password.clone())?;
         init_db(&walletdb_path, password)?;
 
-        let secret: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
-        let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
+        let secret = SecretKey::random(&mut OsRng);
+        let public = derive_publickey(secret);
 
         wallet.put_keypair(&public, &secret)?;
 
         let mut tree = crate::crypto::merkle::CommitmentTree::empty();
 
         let note = Note {
-            serial: jubjub::Fr::random(&mut OsRng),
+            serial: NullifierSerial::random(&mut OsRng),
             value: 110,
-            token_id: jubjub::Fr::random(&mut OsRng),
-            coin_blind: jubjub::Fr::random(&mut OsRng),
-            valcom_blind: jubjub::Fr::random(&mut OsRng),
+            token_id: TokenId::random(&mut OsRng),
+            coin_blind: CoinBlind::random(&mut OsRng),
+            valcom_blind: ValueCommitBlind::random(&mut OsRng),
         };
 
         let coin = Coin::new(bls12_381::Scalar::random(&mut OsRng).to_repr());