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

implemented note decryption. ran cargo fmt

rachel-rose 5 лет назад
Родитель
Сommit
0613393e95
5 измененных файлов с 78 добавлено и 53 удалено
  1. 4 1
      res/schema.sql
  2. 22 17
      src/bin/darkfid.rs
  3. 2 2
      src/crypto/merkle.rs
  4. 1 1
      src/rpc/adapter.rs
  5. 49 32
      src/wallet/walletdb.rs

+ 4 - 1
res/schema.sql

@@ -8,11 +8,14 @@ PRAGMA foreign_keys=on;
 CREATE TABLE IF NOT EXISTS coins(
 CREATE TABLE IF NOT EXISTS coins(
     coin_id INTEGER PRIMARY KEY NOT NULL,
     coin_id INTEGER PRIMARY KEY NOT NULL,
     coin BLOB NOT NULL,
     coin BLOB NOT NULL,
-    witness BLOB NOT NULL,
     serial BLOB NOT NULL,
     serial BLOB NOT NULL,
     value INT NOT NULL,
     value INT NOT NULL,
     coin_blind BLOB NOT NULL,
     coin_blind BLOB NOT NULL,
     valcom_blind BLOB NOT NULL,
     valcom_blind BLOB NOT NULL,
+    tree BLOB NOT NULL,
+    filled BLOB NOT NULL,
+    cursor_depth BLOB NOT NULL,
+    cursor_ BLOB NOT NULL,
     key_id INTEGER NOT NULL,
     key_id INTEGER NOT NULL,
     FOREIGN KEY (key_id)
     FOREIGN KEY (key_id)
         REFERENCES keys (key_id)
         REFERENCES keys (key_id)

+ 22 - 17
src/bin/darkfid.rs

@@ -81,7 +81,7 @@ impl ProgramState for State {
 }
 }
 
 
 impl State {
 impl State {
-    fn apply(&mut self, update: StateUpdate) -> Result<()> {
+    async fn apply(&mut self, update: StateUpdate) -> Result<()> {
         // Extend our list of nullifiers with the ones from the update
         // Extend our list of nullifiers with the ones from the update
         for nullifier in update.nullifiers {
         for nullifier in update.nullifiers {
             self.nullifiers.put(nullifier, vec![] as Vec<u8>)?;
             self.nullifiers.put(nullifier, vec![] as Vec<u8>)?;
@@ -101,35 +101,40 @@ impl State {
                 witness.append(node).expect("append to witness");
                 witness.append(node).expect("append to witness");
             }
             }
 
 
-            // if let Some((note, secret)) = self.try_decrypt_note(enc_note) {
-            //     // We need to keep track of the witness for this coin.
-            //     // This allows us to prove inclusion of the coin in the merkle tree with ZK.
-            //     // Just as we update the merkle tree with every new coin, so we do the same with
-            //     // the witness.
+            if let Some((note, secret)) = self.try_decrypt_note(enc_note).await {
+                // We need to keep track of the witness for this coin.
+                // This allows us to prove inclusion of the coin in the merkle tree with ZK.
+                // Just as we update the merkle tree with every new coin, so we do the same with
+                // the witness.
 
 
-            //     // Derive the current witness from the current tree.
-            //     // This is done right after we add our coin to the tree (but before any other
-            //     // coins are added)
+                // Derive the current witness from the current tree.
+                // This is done right after we add our coin to the tree (but before any other
+                // coins are added)
 
 
-            //     // Make a new witness for this coin
-            //     let witness = IncrementalWitness::from_tree(&self.tree);
-            //     self.own_coins.push((coin, note, secret, witness));
-            // }
+                // Make a new witness for this coin
+                let witness = IncrementalWitness::from_tree(&self.tree);
+
+                self.wallet.own_coins.push((coin, note, secret, witness));
+                self.wallet.put_own_coins();
+            }
         }
         }
         Ok(())
         Ok(())
     }
     }
 
 
-    // sql
     async fn try_decrypt_note(&self, ciphertext: EncryptedNote) -> Option<(Note, jubjub::Fr)> {
     async fn try_decrypt_note(&self, ciphertext: EncryptedNote) -> Option<(Note, jubjub::Fr)> {
         let vec = self.wallet.get_private().ok()?;
         let vec = self.wallet.get_private().ok()?;
-        let secret = self.wallet.get_value_deserialized::<jubjub::Fr>(vec).await.expect("Deserialize failed");
+        let secret = self
+            .wallet
+            .get_value_deserialized::<jubjub::Fr>(vec)
+            .await
+            .expect("Deserialize failed");
         match ciphertext.decrypt(&secret) {
         match ciphertext.decrypt(&secret) {
             Ok(note) => {
             Ok(note) => {
                 // ... and return the decrypted note for this coin.
                 // ... and return the decrypted note for this coin.
                 return Some((note, secret.clone()));
                 return Some((note, secret.clone()));
             }
             }
             Err(_) => {}
             Err(_) => {}
-            }
+        }
         // We weren't able to decrypt the note with our key.
         // We weren't able to decrypt the note with our key.
         None
         None
     }
     }
@@ -148,7 +153,7 @@ pub async fn subscribe(gateway_slabs_sub: GatewaySlabsSubscriber, mut state: Sta
         let tx = tx::Transaction::decode(&slab.get_payload()[..])?;
         let tx = tx::Transaction::decode(&slab.get_payload()[..])?;
 
 
         let update = state_transition(&state, tx)?;
         let update = state_transition(&state, tx)?;
-        state.apply(update)?;
+        state.apply(update).await?;
     }
     }
 }
 }
 
 

+ 2 - 2
src/crypto/merkle.rs

@@ -469,11 +469,11 @@ impl<Node: Hashable> MerklePath<Node> {
         // path
         // path
         let mut tmp = position;
         let mut tmp = position;
         for entry in auth_path.iter_mut() {
         for entry in auth_path.iter_mut() {
-            entry.1 = (tmp & 1) == 1;
+            entry.1 =(tmp & 1) == 1;
             tmp >>= 1;
             tmp >>= 1;
         }
         }
 
 
-        // The witness should be empty now; if it wasn't, the caller would
+        // The witnesmas should be empty now; if it wasn't, the caller would
         // have provided more information than they should have, indicating
         // have provided more information than they should have, indicating
         // a bug downstream
         // a bug downstream
         if witness.is_empty() {
         if witness.is_empty() {

+ 1 - 1
src/rpc/adapter.rs

@@ -21,7 +21,7 @@ impl RpcAdapter {
     pub async fn key_gen(&self) -> Result<()> {
     pub async fn key_gen(&self) -> Result<()> {
         debug!(target: "adapter", "key_gen() [START]");
         debug!(target: "adapter", "key_gen() [START]");
         let (public, private) = self.wallet.key_gen().await;
         let (public, private) = self.wallet.key_gen().await;
-        self.wallet.put_key(public, private).await?;
+        self.wallet.put_keypair(public, private).await?;
         Ok(())
         Ok(())
     }
     }
 
 

+ 49 - 32
src/wallet/walletdb.rs

@@ -1,6 +1,6 @@
 use crate::crypto::{coin::Coin, merkle::IncrementalWitness, merkle_node::MerkleNode, note::Note};
 use crate::crypto::{coin::Coin, merkle::IncrementalWitness, merkle_node::MerkleNode, note::Note};
 use crate::serial;
 use crate::serial;
-use crate::serial::{deserialize, Decodable};
+use crate::serial::{deserialize, serialize, Decodable, Encodable};
 use crate::Error;
 use crate::Error;
 use crate::Result;
 use crate::Result;
 use async_std::sync::Arc;
 use async_std::sync::Arc;
@@ -40,6 +40,31 @@ impl WalletDB {
         })
         })
     }
     }
 
 
+    pub async fn put_own_coins(&self) -> Result<()> {
+        let note = &self.own_coins[0].1;
+        let coin = self.get_value_serialized(&self.own_coins[0].0.repr).await?;
+        let serial = self.get_value_serialized(&note.serial).await?;
+        let coin_blind = self.get_value_serialized(&note.coin_blind).await?;
+        let valcom_blind = self.get_value_serialized(&note.valcom_blind).await?;
+        let value = self.get_value_serialized(&note.value).await?;
+        let conn = Connection::open(&self.path)?;
+        // witness deserialization not implemented
+        conn.execute(
+            "INSERT INTO coins(coin, serial, value, coin_blind, valcom_blind, witness, key_id)
+            VALUES (NULL, :coin, :serial, :value, :coin_blind, :valcom_blind, :witness, :key_id)",
+            named_params! {
+            ":coin": coin,
+            ":serial": serial,
+            ":value": value,
+            ":coin_blind": coin_blind,
+            ":valcom_blind": valcom_blind,
+            //":privkey": privkey,
+             //":pubkey": pubkey
+            },
+        )?;
+        Ok(())
+    }
+
     fn create_path(wallet: &str) -> Result<PathBuf> {
     fn create_path(wallet: &str) -> Result<PathBuf> {
         let mut path = dirs::home_dir()
         let mut path = dirs::home_dir()
             .ok_or(Error::PathNotFound)?
             .ok_or(Error::PathNotFound)?
@@ -50,11 +75,16 @@ impl WalletDB {
         Ok(path)
         Ok(path)
     }
     }
 
 
-    //fn get_path() -> Result<PathBuf> {
-    //    Ok(self.path)
-    //}
+    pub async fn key_gen(&self) -> (Vec<u8>, Vec<u8>) {
+        debug!(target: "key_gen", "Generating keys...");
+        let secret: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
+        let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
+        let pubkey = serial::serialize(&public);
+        let privkey = serial::serialize(&secret);
+        (pubkey, privkey)
+    }
 
 
-    pub async fn put_key(&self, pubkey: Vec<u8>, privkey: Vec<u8>) -> Result<()> {
+    pub async fn put_keypair(&self, pubkey: Vec<u8>, privkey: Vec<u8>) -> Result<()> {
         //debug!(target: "key_gen", "Generating keys...");
         //debug!(target: "key_gen", "Generating keys...");
         let conn = Connection::open(&self.path)?;
         let conn = Connection::open(&self.path)?;
         //debug!(target: "adapter", "key_gen() [Saving public key...]");
         //debug!(target: "adapter", "key_gen() [Saving public key...]");
@@ -69,13 +99,16 @@ impl WalletDB {
         Ok(())
         Ok(())
     }
     }
 
 
-    pub async fn key_gen(&self) -> (Vec<u8>, Vec<u8>) {
-        debug!(target: "key_gen", "Generating keys...");
-        let secret: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
-        let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
-        let pubkey = serial::serialize(&public);
-        let privkey = serial::serialize(&secret);
-        (pubkey, privkey)
+    pub async fn put_cashier_pub(&self, pubkey: Vec<u8>) -> Result<()> {
+        debug!(target: "save_cash_key", "Save cashier keys...");
+        let conn = Connection::open(&self.path)?;
+        // Write keys to database
+        conn.execute(
+            "INSERT INTO cashier(key_id, key_public)
+            VALUES (NULL, :pubkey)",
+            named_params! {":pubkey": pubkey},
+        )?;
+        Ok(())
     }
     }
 
 
     pub async fn get_public(&self) -> Result<Vec<u8>> {
     pub async fn get_public(&self) -> Result<Vec<u8>> {
@@ -102,28 +135,12 @@ impl WalletDB {
         Ok(keys)
         Ok(keys)
     }
     }
 
 
+    pub async fn get_value_serialized<T: Encodable>(&self, data: &T) -> Result<Vec<u8>> {
+        let v = serialize(data);
+        Ok(v)
+    }
     pub async fn get_value_deserialized<D: Decodable>(&self, key: Vec<u8>) -> Result<D> {
     pub async fn get_value_deserialized<D: Decodable>(&self, key: Vec<u8>) -> Result<D> {
         let v: D = deserialize(&key)?;
         let v: D = deserialize(&key)?;
         Ok(v)
         Ok(v)
     }
     }
-
-    pub async fn put_cashier_pub(&self, pubkey: Vec<u8>) -> Result<()> {
-        debug!(target: "save_cash_key", "Save cashier keys...");
-        let conn = Connection::open(&self.path)?;
-        // Write keys to database
-        conn.execute(
-            "INSERT INTO cashier(key_id, key_public)
-            VALUES (NULL, :pubkey)",
-            named_params! {":pubkey": pubkey},
-        )?;
-        Ok(())
-    }
-
-    pub async fn is_valid_cashier_pub(&self, public: &jubjub::SubgroupPoint) -> Result<bool> {
-        let conn = Connection::open(&self.path)?;
-        let mut stmt = conn
-            .prepare("SELECT key_public FROM cashier WHERE key_public IN (SELECT key_public)")
-            .expect("Cannot generate statement.");
-        Ok(stmt.exists([1i32])?)
-    }
 }
 }