Răsfoiți Sursa

fixed improper dependency graph which caused wallet to be constructed twice

rachel-rose 5 ani în urmă
părinte
comite
0daef9f312
6 a modificat fișierele cu 52 adăugiri și 29 ștergeri
  1. 14 11
      src/bin/darkfid.rs
  2. 9 4
      src/rpc/adapter.rs
  3. 2 2
      src/rpc/jsonserver.rs
  4. 2 0
      src/rpc/mod.rs
  5. 1 1
      src/wallet/mod.rs
  6. 24 11
      src/wallet/walletdb.rs

+ 14 - 11
src/bin/darkfid.rs

@@ -1,5 +1,6 @@
 use async_std::sync::Arc;
-use drk::rpc::adapter::RpcAdapter;
+//use drk::rpc::
+use drk::rpc::adapter::{RpcAdapter, AdapterPtr};
 use drk::rpc::jsonserver;
 //use drk::rpc::options::ProgramOptions;
 use rand::rngs::OsRng;
@@ -17,7 +18,7 @@ use drk::crypto::{
 use drk::serial::Decodable;
 use drk::service::{ClientProgramOptions, GatewayClient, GatewaySlabsSubscriber};
 use drk::state::{state_transition, ProgramState, StateUpdate};
-use drk::wallet::WalletDB;
+use drk::wallet::{WalletDB, WalletPtr};
 use drk::{tx, Result};
 use rusqlite::Connection;
 
@@ -45,7 +46,7 @@ pub struct State {
     spend_pvk: groth16::PreparedVerifyingKey<Bls12>,
     // Public key of the cashier
     // List of all our secret keys
-    wallet: WalletDB,
+    wallet: WalletPtr,
 }
 
 impl ProgramState for State {
@@ -114,6 +115,7 @@ impl State {
                 // Make a new witness for this coin
                 let witness = IncrementalWitness::from_tree(&self.tree);
 
+                // own_coins should not be vector
                 self.wallet.own_coins.push((coin, note, secret, witness));
                 self.wallet.put_own_coins().await?;
             }
@@ -166,6 +168,7 @@ async fn start(executor: Arc<Executor<'_>>, options: Arc<ClientProgramOptions>)
 
     let slabstore = RocksColumn::<columns::Slabs>::new(rocks.clone());
 
+    //let adapter = RpcAdapter::new("wallet.db")?;
     //
     // Auto create trusted ceremony parameters if they don't exist
     if !Path::new("mint.params").exists() {
@@ -191,7 +194,12 @@ async fn start(executor: Arc<Executor<'_>>, options: Arc<ClientProgramOptions>)
 
     let merkle_roots = RocksColumn::<columns::MerkleRoots>::new(rocks.clone());
     let nullifiers = RocksColumn::<columns::Nullifiers>::new(rocks);
-    let wallet = RpcAdapter::new("wallet.db")?.wallet;
+
+    //let wallet = adapter.wallet;
+    let wallet = Arc::new(WalletDB::new("wallet.db")?);
+
+    //let wallet2 = wallet.clone();
+    let ex = executor.clone();
 
     let state = State {
         tree: CommitmentTree::empty(),
@@ -199,14 +207,10 @@ async fn start(executor: Arc<Executor<'_>>, options: Arc<ClientProgramOptions>)
         nullifiers,
         mint_pvk,
         spend_pvk,
-        wallet,
+        wallet: wallet.clone(),
     };
 
-    let ex = executor.clone();
-
-    // create a wallet adapter
-    let adapter = RpcAdapter::new("wallet.db")?;
-
+    let adapter = RpcAdapter::new(wallet.clone())?;
     // start the rpc server
     jsonserver::start(ex.clone(), options.clone(), adapter).await?;
 
@@ -251,7 +255,6 @@ fn main() -> Result<()> {
     ])
     .unwrap();
 
-    debug!(target: "DARKFID", "main() [ADAPTER CREATED]");
     let ex2 = ex.clone();
 
     let (_, result) = Parallel::new()

+ 9 - 4
src/rpc/adapter.rs

@@ -1,17 +1,18 @@
-use crate::wallet::WalletDB;
+use crate::wallet::{WalletDB, WalletPtr};
 use crate::Result;
 use log::*;
+use async_std::sync::Arc;
 //use std::sync::Arc;
 
+pub type AdapterPtr = Arc<RpcAdapter>;
 // Dummy adapter for now
 pub struct RpcAdapter {
-    pub wallet: WalletDB,
+    pub wallet: Arc<WalletDB>,
 }
 
 impl RpcAdapter {
-    pub fn new(dbname: &str) -> Result<Self> {
+    pub fn new(wallet: Arc<WalletDB>) -> Result<Self> {
         debug!(target: "ADAPTER", "new() [CREATING NEW WALLET]");
-        let wallet = WalletDB::new(dbname)?;
         Ok(Self { wallet })
     }
 
@@ -43,6 +44,10 @@ impl RpcAdapter {
         Ok(())
     }
 
+    //pub async fn walletdb(&self) -> WalletPtr {
+    //    self.wallet.clone();
+    //}
+
     //pub async fn create_
     //pub async fn save_key(&self, pubkey: Vec<u8>) -> Result<()> {
     //    debug!(target: "adapter", "save_key() [START]");

+ 2 - 2
src/rpc/jsonserver.rs

@@ -182,7 +182,7 @@ impl RpcInterface {
             let self2 = self1.clone();
             async move {
             println!("New wallet method called...");
-            RpcAdapter::new("wallet.db").expect("Failed to create wallet");
+            //RpcAdapter::new("wallet.db").expect("Failed to create wallet");
             println!("Wallet created at path {:?}", self2.adapter.wallet.path);
             Ok(jsonrpc_core::Value::String(
                 "Created wallet".into(),))
@@ -215,7 +215,7 @@ impl RpcInterface {
             let self2 = self1.clone();
             async move {
             println!("New wallet method called...");
-            RpcAdapter::new("cashier.db").expect("Failed to create wallet");
+            //RpcAdapter::new("cashier.db").expect("Failed to create wallet");
             println!("Wallet created at path {:?}", self2.adapter.wallet.path);
             Ok(jsonrpc_core::Value::String(
                 "Created cashier wallet".into(),

+ 2 - 0
src/rpc/mod.rs

@@ -1,3 +1,5 @@
 pub mod adapter;
 pub mod jsonserver;
 pub mod test;
+
+pub use adapter::{RpcAdapter, AdapterPtr};

+ 1 - 1
src/wallet/mod.rs

@@ -1,3 +1,3 @@
 pub mod walletdb;
 
-pub use walletdb::WalletDB;
+pub use walletdb::{WalletDB, WalletPtr};

+ 24 - 11
src/wallet/walletdb.rs

@@ -10,41 +10,54 @@ use rand::rngs::OsRng;
 use rusqlite::{named_params, Connection, OpenFlags};
 use std::path::{Path, PathBuf};
 
+pub type WalletPtr = Arc<WalletDB>;
+
+// function: given keyID, get corresponding secret
 pub struct WalletDB {
     pub path: PathBuf,
     pub secrets: Vec<jubjub::Fr>,
     pub cashier_secrets: Vec<jubjub::Fr>,
+    //pub coin: Coin,
+    //pub note: Note,
+    //pub witness: IncrementalWitness<MerkleNode>,
+    // wrap in mutex or read/write lock
     pub own_coins: Vec<(Coin, Note, jubjub::Fr, IncrementalWitness<MerkleNode>)>,
     pub cashier_public: jubjub::SubgroupPoint,
+    pub public: jubjub::SubgroupPoint,
     //conn: Arc<Connection>,
 }
 
 impl WalletDB {
     pub fn new(wallet: &str) -> Result<Self> {
         debug!(target: "walletdb", "new() Constructor called");
-        let path = Self::create_path(wallet)?;
-        let conn = Connection::open(&path)?;
-        debug!(target: "walletdb", "OPENED CONNECTION AT PATH {:?}", path);
-        let contents = include_str!("../../res/schema.sql");
+        //let path = Self::create_path(wallet)?;
+        //let conn = Connection::open(&path)?;
+        //debug!(target: "walletdb", "OPENED CONNECTION AT PATH {:?}", path);
+        //let contents = include_str!("../../res/schema.sql");
         let cashier_secret = jubjub::Fr::random(&mut OsRng);
         let secret = jubjub::Fr::random(&mut OsRng);
-        let _public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
+        let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
         let cashier_public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * cashier_secret;
-        match conn.execute_batch(&contents) {
-            Ok(v) => println!("Database initalized successfully {:?}", v),
-            Err(err) => println!("Error: {}", err),
-        };
-        debug!(target: "walletdb", "new(): inititalized wallet");
+        //match conn.execute_batch(&contents) {
+        //    Ok(v) => println!("Database initalized successfully {:?}", v),
+        //    Err(err) => println!("Error: {}", err),
+        //};
+        debug!(target: "walletdb", "new(): wallet constructor called");
         Ok(Self {
-            path,
+            path: Self::create_path(wallet)?,
             own_coins: vec![],
             cashier_secrets: vec![cashier_secret.clone()],
             secrets: vec![secret.clone()],
             cashier_public,
+            public,
+            //coin,
+            //note,
+            //witness,
             //conn,
         })
     }
 
+    //coin, serial, value, asset_id, coin_blind, valcom_blind, witness, key_id
     pub async fn put_own_coins(&self) -> Result<()> {
         let coin = self.get_value_serialized(&self.own_coins[0].0.repr).await?;
         let note = &self.own_coins[0].1;