Jelajahi Sumber

refactored rpc/adapter to use walletdb interface

rachel-rose 5 tahun lalu
induk
melakukan
0323a9af87
2 mengubah file dengan 48 tambahan dan 130 penghapusan
  1. 11 103
      src/rpc/adapter.rs
  2. 37 27
      src/wallet/walletdb.rs

+ 11 - 103
src/rpc/adapter.rs

@@ -1,12 +1,7 @@
-use crate::serial;
 use crate::Result;
-use ff::Field;
 use log::*;
-use rand::rngs::OsRng;
-use rusqlite::{named_params, Connection};
-use std::fs::File;
-use std::io::prelude::*;
 use std::sync::Arc;
+use crate::wallet::walletdb::DBInterface;
 
 // Dummy adapter for now
 pub struct RpcAdapter {}
@@ -16,81 +11,29 @@ impl RpcAdapter {
         Arc::new(Self {})
     }
 
-    pub async fn db_connect() -> Connection {
-        let path = dirs::home_dir()
-            .expect("Cannot find home directory.")
-            .as_path()
-            .join(".config/darkfi/wallet.db");
-        let connector = Connection::open(&path);
-        connector.expect("Failed to connect to database.")
-    }
-
     pub async fn key_gen() -> Result<()> {
         debug!(target: "adapter", "key_gen() [START]");
-        let path = dirs::home_dir()
-            .expect("Cannot find home directory.")
-            .as_path()
-            .join(".config/darkfi/wallet.db");
-        debug!(target: "adapter", "key_gen() [FOUND PATH]");
-        println!("Found path: {:?}", &path);
-        debug!(target: "adapter", "key_gen() [TRY DB CONNECT]");
-        let connect = Connection::open(&path).expect("Failed to connect to database.");
-        // TODO: assign new ID on each run
-        debug!(target: "adapter", "key_gen() [Assigning ID...]");
-        let id = 0;
-        debug!(target: "adapter", "key_gen() [Generating private key...]");
-        let secret: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
-        debug!(target: "adapter", "key_gen() [Generating public key...]");
-        let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
-        let pubkey = serial::serialize(&public);
-        let privkey = serial::serialize(&secret);
-        connect.execute(
-            "INSERT INTO keys(key_id, key_private, key_public)
-            VALUES (:id, :privkey, :pubkey)",
-            named_params! {":id": id,
-             ":privkey": privkey,
-             ":pubkey": pubkey
-            },
-        )?;
+        DBInterface::own_key_gen().await?;
         Ok(())
     }
 
     pub async fn new_wallet() -> Result<()> {
         debug!(target: "adapter", "new_wallet() [START]");
-        let path = dirs::home_dir()
-            .expect("Cannot find home directory.")
-            .as_path()
-            .join(".config/darkfi/wallet.db");
-        debug!(target: "adapter", "new_wallet() [FOUND PATH]");
-        println!("Found path: {:?}", &path);
-        debug!(target: "adapter", "new_wallet() [TRY DB CONNECT]");
-        let connect = Connection::open(&path).expect("Failed to connect to database.");
-        let contents = include_str!("../../res/schema.sql");
-        Ok(connect.execute_batch(&contents)?)
+        DBInterface::new_wallet().await?;
+        Ok(())
     }
 
     pub async fn new_cashier_wallet() -> Result<()> {
         debug!(target: "adapter", "new_wallet() [START]");
-        let path = dirs::home_dir()
-            .expect("Cannot find home directory.")
-            .as_path()
-            .join(".config/darkfi/cashier.db");
-        debug!(target: "adapter", "new_wallet() [FOUND PATH]");
-        println!("Found path: {:?}", &path);
-        debug!(target: "adapter", "new_wallet() [TRY DB CONNECT]");
-        let connect = Connection::open(&path).expect("Failed to connect to database.");
-        let contents = include_str!("../../res/schema.sql");
-        Ok(connect.execute_batch(&contents)?)
+        DBInterface::new_cashier_wallet().await?;
+        Ok(())
     }
 
-    //pub async fn decrypt(conn: &Connection, password: )
-    // TODO: getting an error when i call this function- does not implement send
-    pub async fn save_key(conn: &Connection, pubkey: Vec<u8>, privkey: Vec<u8>) -> Result<()> {
-        // loads the walle
-        let mut db_file = File::open("wallet.sql")?;
-        let mut contents = String::new();
-        db_file.read_to_string(&mut contents)?;
-        Ok(conn.execute_batch(&mut contents)?)
+    pub async fn save_key(pubkey: Vec<u8>) -> Result<()> {
+        debug!(target: "adapter", "save_key() [START]");
+        DBInterface::save_key(pubkey).await?;
+        Ok(())
+
     }
 
     pub async fn get_info() {}
@@ -100,38 +43,3 @@ impl RpcAdapter {
     pub async fn stop() {}
 }
 
-//let stop_send = self.stop_send.clone();
-//io.add_method("stop", move |_| {
-//    let stop_send = stop_send.clone();
-//    async move {
-//        RpcAdapter::stop().await;
-//        let _ = stop_send.send(()).await;
-//        Ok(jsonrpc_core::Value::Null)
-//    }
-//});
-
-//let stop_send = self.stop_send.clone();
-//pub async fn wait_for_quit(self: Arc<Self>) -> Result<()> {
-//    Ok(self.stop_recv.recv().await?)
-//}
-//let self2 = self2.clone();
-//async move {
-//    Ok(json!({
-//        "started": *self2.started.lock().await,
-//        "connections": self2.p2p.connections_count().await
-//    }))
-
-//pub async fn serve(self: Arc<Self>, mut req: Request) ->
-// http_types::Result<Response> {    info!("RPC serving {}", req.url());
-
-//    let request = req.body_string().await?;
-
-//    let mut res = Response::new(StatusCode::Ok);
-//    res.insert_header("Content-Type", "text/plain");
-//    res.set_body(response);
-//    Ok(res)
-//}
-
-//pub async fn wait_for_quit(self: Arc<Self>) -> Result<()> {
-//    Ok(self.stop_recv.recv().await?)
-//}

+ 37 - 27
src/wallet/walletdb.rs

@@ -11,19 +11,6 @@ use rusqlite::{named_params, Connection};
 use std::fs::File;
 use std::path::{Path, PathBuf};
 
-//use drk::crypto::{
-//    coin::Coin,
-//    load_params,
-//    merkle::{CommitmentTree, IncrementalWitness},
-//    merkle_node::{hash_coin, MerkleNode},
-//    note::{EncryptedNote, Note},
-//    nullifier::Nullifier,
-//    save_params, setup_mint_prover, setup_spend_prover,
-//};
-//use drk::serial::{Decodable, Encodable};
-//use drk::state::{state_transition, ProgramState, StateUpdate};
-//use drk::tx;
-
 pub struct DBInterface {}
 
 impl DBInterface {
@@ -35,7 +22,7 @@ impl DBInterface {
         path
     }
 
-    pub fn cashier_path(&self) -> PathBuf {
+    pub fn cashier_path() -> PathBuf {
         let path = dirs::home_dir()
             .expect("Cannot find home directory.")
             .as_path()
@@ -43,7 +30,21 @@ impl DBInterface {
         path
     }
 
-    pub async fn own_key_gen(&self) -> Result<()> {
+    pub async fn new_wallet() -> Result<()> {
+        let path = Self::wallet_path();
+        let connect = Connection::open(&path).expect("Failed to connect to database.");
+        let contents = include_str!("../../res/schema.sql");
+        Ok(connect.execute_batch(&contents)?)
+    }
+
+    pub async fn new_cashier_wallet() -> Result<()> {
+        let path = Self::cashier_path();
+        let connect = Connection::open(&path).expect("Failed to connect to database.");
+        let contents = include_str!("../../res/schema.sql");
+        Ok(connect.execute_batch(&contents)?)
+    }
+
+    pub async fn own_key_gen() -> Result<()> {
         let path = Self::wallet_path();
         let connect = Connection::open(&path).expect("Failed to connect to database.");
         let id = 0;
@@ -65,8 +66,8 @@ impl DBInterface {
         Ok(())
     }
 
-    pub async fn cash_key_gen(&self) -> Result<()> {
-        let path = self.cashier_path();
+    pub async fn cash_key_gen() -> Result<()> {
+        let path = Self::cashier_path();
         let connect = Connection::open(&path).expect("Failed to connect to database.");
         let id = 0;
         // Create keys
@@ -86,11 +87,8 @@ impl DBInterface {
         Ok(())
     }
 
-    pub async fn get_cash_public(&self) -> Result<()> {
-        let path = dirs::home_dir()
-            .expect("Cannot find home directory.")
-            .as_path()
-            .join(".config/darkfi/cashier.db");
+    pub async fn get_cash_public() -> Result<()> {
+        let path = Self::cashier_path();
         let connect = Connection::open(&path).expect("Failed to connect to database.");
         let id = 0;
         let mut stmt = connect.prepare("SELECT key_public FROM keys").unwrap();
@@ -108,11 +106,8 @@ impl DBInterface {
         Ok(key)
     }
 
-    pub async fn save_cash_pubkey(&self, pubkey: Vec<u8>) -> Result<()> {
-        let path = dirs::home_dir()
-            .expect("Cannot find home directory.")
-            .as_path()
-            .join(".config/darkfi/wallet.db");
+    pub async fn save_cash_key(pubkey: Vec<u8>) -> Result<()> {
+        let path = Self::wallet_path();
         let connect = Connection::open(&path).expect("Failed to connect to database.");
         let id = 0;
         // Write keys to database
@@ -125,6 +120,21 @@ impl DBInterface {
         )?;
         Ok(())
     }
+
+    pub async fn save_key(pubkey: Vec<u8>) -> Result<()> {
+        let path = Self::wallet_path();
+        let connect = Connection::open(&path).expect("Failed to connect to database.");
+        let id = 0;
+        // Write keys to database
+        connect.execute(
+            "INSERT INTO keys(key_id, key_public)
+            VALUES (:id, :pubkey)",
+            named_params! {":id": id,
+             ":pubkey": pubkey
+            },
+        )?;
+        Ok(())
+    }
 }
 
 fn main() {}