Переглянути джерело

added data variables to struct and updated new() on walletdb and adapter

rachel-rose 5 роки тому
батько
коміт
32f86d1b0b
5 змінених файлів з 110 додано та 90 видалено
  1. 44 37
      src/bin/darkfid.rs
  2. 2 2
      src/bin/dfi.rs
  3. 33 26
      src/rpc/adapter.rs
  4. 3 1
      src/rpc/jsonserver.rs
  5. 28 24
      src/wallet/walletdb.rs

+ 44 - 37
src/bin/darkfid.rs

@@ -12,11 +12,11 @@ use drk::crypto::{
     nullifier::Nullifier,
     save_params, setup_mint_prover, setup_spend_prover,
 };
-use drk::serial::Decodable;
+use drk::serial::{deserialize, Decodable};
 use drk::service::{ClientProgramOptions, GatewayClient, GatewaySlabsSubscriber};
 use drk::state::{state_transition, ProgramState, StateUpdate};
 use drk::wallet::WalletDB;
-use drk::{tx, Result};
+use drk::{tx, Result, Error};
 use rusqlite::Connection;
 
 use async_executor::Executor;
@@ -49,14 +49,13 @@ pub struct State {
 
 impl ProgramState for State {
     fn is_valid_cashier_public_key(&self, _public: &jubjub::SubgroupPoint) -> bool {
-        // Still needs to be tested
-        let path = WalletDB::path("cashier.db").expect("Failed to get path");
-        let connect = Connection::open(&path).expect("Failed to connect to database.");
-        let mut stmt = connect
-            .prepare("SELECT key_public FROM cashier WHERE key_public IN (SELECT key_public)")
-            .expect("Cannot generate statement.");
-        // test this
-        stmt.exists([1i32]).unwrap()
+        //let path = WalletDB::path("cashier.db").expect("Failed to find path");
+        //let connect = Connection::open(&path).expect("Failed to connect to database.");
+        //let mut stmt = connect
+        //    .prepare("SELECT key_public FROM cashier WHERE key_public IN (SELECT key_public)")
+        //    .expect("Cannot generate statement.");
+        //stmt.exists([1i32]).unwrap()
+        0
     }
 
     fn is_valid_merkle(&self, merkle_root: &MerkleNode) -> bool {
@@ -97,52 +96,60 @@ impl State {
             // Keep track of all merkle roots that have existed
             self.merkle_roots.put(self.tree.root(), vec![] as Vec<u8>)?;
 
-            // own coins is sql
             // Also update all the coin witnesses
             for (_, _, _, witness) in self.own_coins.iter_mut() {
                 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) {
+           //     // 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.own_coins.push((coin, note, secret, witness));
+           // }
         }
         Ok(())
     }
 
     // sql
-    fn try_decrypt_note(&self, _ciphertext: EncryptedNote) -> Option<(Note, jubjub::Fr)> {
-        //let connect = Connection::open(&path).expect("Failed to connect to database.");
+    async fn try_decrypt_note(&self, ciphertext: EncryptedNote) -> Option<(Note, jubjub::Fr)> {
+        //let path = WalletDB::path("wallet.db")?;
+        //let vec = WalletDB::get_private(path)?;
+        //let secret = WalletDB::get_value_deserialized(vec).await?;
         //let mut stmt = connect.prepare("SELECT key_private FROM keys").ok()?;
         //let key_iter = stmt.query_map::<String, _, _>([], |row| row.get(0)).ok()?;
         //for key in key_iter {
-        //    println!("Found key {:?}", key.unwrap());
+        //    println!("Foun//d key {:?}", key.unwrap());
         //}
         //
-        //// Loop through all our secret keys...
-
-        //for secret in &self.secrets {
-        //    // ... attempt to decrypt the note ...
-        //    match ciphertext.decrypt(secret) {
-        //        Ok(note) => {
-        //            // ... and return the decrypted note for this coin.
-        //            return Some((note, secret.clone()));
-        //        }
-        //        Err(_) => {}
+        //match stmt {
+        //let mut stmt = connect
+        //    .prepare("SELECT key_public FROM cashier WHERE key_public IN (SELECT key_public)")
+            //.expect("Cannot generate statement.");
+        // test this
+        //stmt.exists([1i32]).unwrap()
+        //    Some(v) => {
+        //        Ok(Some(v))
+        //    }
+        //    None => Ok(None),
+        //}
+        //match ciphertext.decrypt(&secret) {
+        //    Ok(note) => {
+        //        // ... and return the decrypted note for this coin.
+        //        return Some((note, secret.clone()));
+        //    }
+        //    Err(_) => {
+        //        println!("Cannot decrypt note! {}", err)
         //    }
         //}
-        // We weren't able to decrypt the note with any of our keys.
         None
     }
 }

+ 2 - 2
src/bin/dfi.rs

@@ -25,7 +25,7 @@ async fn start2(executor: Arc<Executor<'_>>, options: ProgramOptions) -> Result<
             protocol.start(executor2).await?;
             Ok::<(), drk::Error>(())
         }));
-    }
+//    }
 
     let mut seed_protocols = Vec::with_capacity(options.seed_addrs.len());
 
@@ -192,7 +192,7 @@ fn main() -> Result<()> {
     ])
     .unwrap();
 
-    let adapter = RpcAdapter::new();
+    let adapter = RpcAdapter::new("wallet.db")?;
     let ex = Arc::new(Executor::new());
     let (signal, shutdown) = async_channel::unbounded::<()>();
     let ex2 = ex.clone();

+ 33 - 26
src/rpc/adapter.rs

@@ -3,73 +3,80 @@ use crate::Result;
 use log::*;
 use std::sync::Arc;
 
+// there should 
 // Dummy adapter for now
-pub struct RpcAdapter {}
+pub struct RpcAdapter {
+    wallet: Arc<WalletDB>
+}
 
 impl RpcAdapter {
-    pub fn new() -> Arc<Self> {
-        Arc::new(Self {})
+    pub fn new(dbname: &str) -> Result<Arc<Self>> {
+        let wallet = WalletDB::new(dbname)?;
+        Ok(Arc::new(Self {
+            wallet
+        }))
     }
 
     pub async fn new_wallet() -> Result<()> {
         debug!(target: "adapter", "new_wallet() [START]");
-        let path = WalletDB::path("wallet.db").expect("Failed to get path");
-        WalletDB::new(path).await?;
+        //let path = WalletDB::path("wallet.db")?;
+        //WalletDB::new(path).await?;
         Ok(())
     }
 
     pub async fn new_cash_wallet() -> Result<()> {
         debug!(target: "adapter", "new_cashier_wallet() [START]");
-        let path = WalletDB::path("cashier.db").expect("Failed to get path");
-        WalletDB::new(path).await?;
+        //let path = WalletDB::path("cashier.db")?;
+        //WalletDB::new(path).await?;
         Ok(())
     }
 
     pub async fn key_gen() -> Result<()> {
         debug!(target: "adapter", "key_gen() [START]");
-        let (public, private) = WalletDB::create_key().await;
-        let path = WalletDB::path("wallet.db").expect("Failed to get path");
-        WalletDB::save_key(path, public, private)
-            .await
-            .expect("Failed to save key");
+        //let (public, private) = WalletDB::create_key().await;
+        //let path = WalletDB::path("wallet.db")?;
+        ////self.wallet.save_key()
+        //WalletDB::save_key(path, public, private)
+        //    .await
+        //    .expect("Failed to save key");
         Ok(())
     }
 
     pub async fn cash_key_gen() -> Result<()> {
         debug!(target: "adapter", "key_gen() [START]");
-        let (public, private) = WalletDB::create_key().await;
-        let path = WalletDB::path("cashier.db").expect("Failed to get path");
-        WalletDB::save_key(path, public, private)
-            .await
-            .expect("Failed to save key");
+        //let (public, private) = WalletDB::create_key().await;
+        //let path = WalletDB::path("cashier.db")?;
+        //WalletDB::save_key(path, public, private)
+        //    .await
+        //    .expect("Failed to save key");
         Ok(())
     }
 
     pub async fn get_key() -> Result<()> {
         debug!(target: "adapter", "get_key() [START]");
-        let path = WalletDB::path("wallet.db").expect("Failed to get path");
-        WalletDB::get(path).await?;
+        //let path = WalletDB::path("wallet.db")?;
+        //WalletDB::get_public(path).await?;
         Ok(())
     }
 
     pub async fn get_cash_key() -> Result<()> {
         debug!(target: "adapter", "get_cash_key() [START]");
-        let path = WalletDB::path("cashier.db").expect("Failed to get path");
-        let key = WalletDB::get(path).await?;
-        println!("{:?}", key);
+        //let path = WalletDB::path("cashier.db")?;
+        //let key = WalletDB::get_public(path).await?;
+        //println!("{:?}", key);
         Ok(())
     }
     pub async fn save_key(pubkey: Vec<u8>) -> Result<()> {
         debug!(target: "adapter", "save_key() [START]");
-        let path = WalletDB::path("wallet.db").expect("Failed to get path");
-        WalletDB::save(path, pubkey).await?;
+        //let path = WalletDB::path("wallet.db")?;
+        //WalletDB::save(path, pubkey).await?;
         Ok(())
     }
 
     pub async fn save_cash_key(pubkey: Vec<u8>) -> Result<()> {
         debug!(target: "adapter", "save_cash_key() [START]");
-        let path = WalletDB::path("cashier.db").expect("Failed to get path");
-        WalletDB::save(path, pubkey).await?;
+        //let path = WalletDB::path("cashier.db")?;
+        //WalletDB::save(path, pubkey).await?;
         Ok(())
     }
 

+ 3 - 1
src/rpc/jsonserver.rs

@@ -181,7 +181,9 @@ impl RpcInterface {
         });
         io.add_method("cash_key_gen", move |_| async move {
             println!("Key generation method called...");
-            RpcAdapter::cash_key_gen().await.expect("Failed to generate key");
+            RpcAdapter::cash_key_gen()
+                .await
+                .expect("Failed to generate key");
             Ok(jsonrpc_core::Value::String(
                 "Attempted key generation".into(),
             ))

+ 28 - 24
src/wallet/walletdb.rs

@@ -1,4 +1,5 @@
 use crate::serial;
+use async_std::sync::Arc;
 use crate::serial::{deserialize, serialize, Decodable, Encodable};
 use crate::Error;
 use crate::Result;
@@ -8,16 +9,22 @@ use rand::rngs::OsRng;
 use rusqlite::{named_params, Connection};
 use std::path::PathBuf;
 
-pub struct WalletDB {}
+pub struct WalletDB {
+    path: PathBuf,
+}
 
 impl WalletDB {
-    pub async fn new(path: PathBuf) -> Result<()> {
-        let connect = Connection::open(&path).expect("Failed to connect to database.");
+    pub fn new(wallet: &str) -> Result<Arc<Self>> {
+        let path = Self::create_path(wallet)?;
+        let connect = Connection::open(&path)?;
         let contents = include_str!("../../res/schema.sql");
-        Ok(connect.execute_batch(&contents)?)
+        connect.execute_batch(&contents)?;
+        Ok(Arc::new(Self {
+            path
+        }))
     }
 
-    pub fn path(wallet: &str) -> Result<PathBuf> {
+    pub fn create_path(wallet: &str) -> Result<PathBuf> {
         let mut path = dirs::home_dir()
             .ok_or(Error::PathNotFound)?
             .as_path()
@@ -27,9 +34,9 @@ impl WalletDB {
         Ok(path)
     }
 
-    pub async fn save_key(path: PathBuf, pubkey: Vec<u8>, privkey: Vec<u8>) -> Result<()> {
+    pub async fn save_key(&self, path: PathBuf, pubkey: Vec<u8>, privkey: Vec<u8>) -> Result<()> {
         debug!(target: "key_gen", "Generating keys...");
-        let connect = Connection::open(&path).expect("Failed to connect to database.");
+        let connect = Connection::open(&path)?;
         debug!(target: "adapter", "key_gen() [Saving public key...]");
         connect.execute(
             "INSERT INTO keys(key_id, key_private, key_public)
@@ -42,7 +49,7 @@ impl WalletDB {
         Ok(())
     }
 
-    pub async fn create_key() -> (Vec<u8>, Vec<u8>) {
+    pub async fn create_key(&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;
@@ -52,42 +59,39 @@ impl WalletDB {
         (pubkey, privkey)
     }
 
-    // match statement here
-    pub async fn get_public(path: PathBuf) -> Result<Vec<u8>> {
+    pub async fn get_public(&self, path: PathBuf) -> Result<Vec<u8>> {
         debug!(target: "get", "Returning keys...");
-        let connect = Connection::open(&path).expect("Failed to connect to database.");
-        // does use unwrap here
-        let mut stmt = connect.prepare("SELECT key_public FROM keys").unwrap();
-        let key_iter = stmt.query_map::<u8, _, _>([], |row| row.get(0)).unwrap();
+        let connect = Connection::open(&path)?;
+        let mut stmt = connect.prepare("SELECT key_public FROM keys")?;
+        let key_iter = stmt.query_map::<u8, _, _>([], |row| row.get(0))?;
         let mut pub_keys = Vec::new();
         for key in key_iter {
-            pub_keys.push(key.unwrap());
+            pub_keys.push(key?);
         }
         Ok(pub_keys)
     }
 
-    // match statement here
-    pub fn get_private(path: PathBuf) -> Result<Vec<u8>> {
+    pub fn get_private(&self, path: PathBuf) -> Result<Vec<u8>> {
         debug!(target: "get", "Returning keys...");
-        let connect = Connection::open(&path).expect("Failed to connect to database.");
-        let mut stmt = connect.prepare("SELECT key_private FROM keys").unwrap();
-        let key_iter = stmt.query_map::<u8, _, _>([], |row| row.get(0)).unwrap();
+        let connect = Connection::open(&path)?;
+        let mut stmt = connect.prepare("SELECT key_private FROM keys")?;
+        let key_iter = stmt.query_map::<u8, _, _>([], |row| row.get(0))?;
         let mut keys = Vec::new();
         for key in key_iter {
-            keys.push(key.unwrap());
+            keys.push(key?);
         }
         Ok(keys)
     }
 
-    pub async fn get_value_deserialized<D: Decodable>(key: Vec<u8>) -> Result<D> {
+    pub async fn get_value_deserialized<D: Decodable>(&self, key: Vec<u8>) -> Result<D> {
         let v: D = deserialize(&key)?;
         Ok(v)
     }
 
-    pub async fn save(path: PathBuf, pubkey: Vec<u8>) -> Result<()> {
+    pub async fn save(&self, path: PathBuf, pubkey: Vec<u8>) -> Result<()> {
         debug!(target: "save_cash_key", "Save cashier keys...");
         //let path = Self::wallet_path();
-        let connect = Connection::open(&path).expect("Failed to connect to database.");
+        let connect = Connection::open(&path)?;
         // Write keys to database
         connect.execute(
             "INSERT INTO cashier(key_id, key_public)