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

made path retreival more general

rachel-rose 5 лет назад
Родитель
Сommit
dd21e0a9f3
7 измененных файлов с 89 добавлено и 44 удалено
  1. 22 0
      scripts/drk
  2. 7 0
      src/bin/darkfid.rs
  3. 13 3
      src/bin/tx-test.rs
  4. 22 39
      src/rpc/adapter.rs
  5. 5 0
      src/rpc/jsonserver.rs
  6. 2 0
      src/wallet/mod.rs
  7. 18 2
      src/wallet/walletdb.rs

+ 22 - 0
scripts/drk

@@ -5,6 +5,7 @@ import requests
 import json
 import json
 
 
 def arg_parser(client):
 def arg_parser(client):
+    #choices = ['wallet', 'cashierwallet', 'keypair', 'pub']
     parser = argparse.ArgumentParser(prog='drk',
     parser = argparse.ArgumentParser(prog='drk',
                                           usage='%(prog)s [commands]',
                                           usage='%(prog)s [commands]',
                                           description="""DarkFi wallet
                                           description="""DarkFi wallet
@@ -15,8 +16,16 @@ def arg_parser(client):
     parser.add_argument("-n", "--new", action='store_true', help="Generate a new wallet")
     parser.add_argument("-n", "--new", action='store_true', help="Generate a new wallet")
     parser.add_argument("-o", "--hello", action='store_true', help="Say hello")
     parser.add_argument("-o", "--hello", action='store_true', help="Say hello")
     parser.add_argument("-c", "--cash", action='store_true', help="Create a new cashier wallet")
     parser.add_argument("-c", "--cash", action='store_true', help="Create a new cashier wallet")
+    parser.add_argument("-t", "--test", action='store_true', help="Test path")
     args = parser.parse_args()
     args = parser.parse_args()
 
 
+    if args.test:
+        try:
+            print("Testing path...")
+            client.test_path(client.payload)
+        except Exception:
+            raise
+
     if args.key:
     if args.key:
         try:
         try:
             print("Attemping to generate a new key pair...")
             print("Attemping to generate a new key pair...")
@@ -61,6 +70,12 @@ def arg_parser(client):
         except Exception:
         except Exception:
             raise
             raise
 
 
+    #if args.wallet:
+    #    try:
+    #        print("This worked")
+    #    except Exception:
+    #        raise
+
 
 
 # TODO: refactor into async
 # TODO: refactor into async
 class DarkClient:
 class DarkClient:
@@ -75,6 +90,13 @@ class DarkClient:
             "id": [],
             "id": [],
         }
         }
 
 
+    def test_path(self, payload):
+        payload['method'] = "test_path"
+        payload['jsonrpc'] = "2.0"
+        payload['id'] = "0"
+        test = self.__request(payload)
+        print(test)
+        
     def key_gen(self, payload):
     def key_gen(self, payload):
         payload['method'] = "key_gen"
         payload['method'] = "key_gen"
         payload['jsonrpc'] = "2.0"
         payload['jsonrpc'] = "2.0"

+ 7 - 0
src/bin/darkfid.rs

@@ -14,6 +14,7 @@ use drk::crypto::{
 };
 };
 use drk::serial::Decodable;
 use drk::serial::Decodable;
 use drk::service::{ClientProgramOptions, GatewayClient, Subscriber};
 use drk::service::{ClientProgramOptions, GatewayClient, Subscriber};
+use drk::wallet::WalletDB;
 use drk::state::{state_transition, ProgramState, StateUpdate};
 use drk::state::{state_transition, ProgramState, StateUpdate};
 use drk::{tx, Result};
 use drk::{tx, Result};
 
 
@@ -47,6 +48,12 @@ pub struct State {
 impl ProgramState for State {
 impl ProgramState for State {
     fn is_valid_cashier_public_key(&self, _public: &jubjub::SubgroupPoint) -> bool {
     fn is_valid_cashier_public_key(&self, _public: &jubjub::SubgroupPoint) -> bool {
         // TODO
         // TODO
+        // Still needs to be tested
+        //let path = WalletDB::wallet_path();
+        //let connect = Connection::open(&path).expect("Failed to connect to database.");
+        //connect.execute(
+        //    " SELECT key_public FROM cashier WHERE key_public IN (SELECT key_public)",
+        //Ok(())
         true
         true
     }
     }
 
 

+ 13 - 3
src/bin/tx-test.rs

@@ -5,10 +5,11 @@ use drk::{Error, Result};
 use ff::{Field, PrimeField};
 use ff::{Field, PrimeField};
 use log::*;
 use log::*;
 use rand::rngs::OsRng;
 use rand::rngs::OsRng;
-use rocksdb::DB;
+//use rocksdb::DB;
 use rusqlite::{named_params, Connection};
 use rusqlite::{named_params, Connection};
-use std::fs::File;
+//use std::fs::File;
 use std::path::Path;
 use std::path::Path;
+use rocksdb::{IteratorMode, Options, DB};
 
 
 use drk::crypto::{
 use drk::crypto::{
     coin::Coin,
     coin::Coin,
@@ -61,7 +62,16 @@ impl ProgramState for MemoryState {
         //// does not actually check whether the cashier key is valid
         //// does not actually check whether the cashier key is valid
         //for key in key_iter {
         //for key in key_iter {
         //    key.unwrap() == self.cashier_public;
         //    key.unwrap() == self.cashier_public;
-        //}
+        //connect.execute(
+        //    "SELECT key_public FROM cashier WHERE key_public IN (SELECT key_public){
+        //
+        //    INSERT INTO keys(key_id, key_private, key_public)
+        //    VALUES (:id, :privkey, :pubkey)",
+        //    named_params! {":id": id,
+        //     ":privkey": privkey,
+        //     ":pubkey": pubkey
+        //    },
+        ////}
         true
         true
     }
     }
     // rocksdb
     // rocksdb

+ 22 - 39
src/rpc/adapter.rs

@@ -1,8 +1,8 @@
-use crate::Result;
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
 use log::*;
 use log::*;
 use std::sync::Arc;
 use std::sync::Arc;
-use crate::wallet::walletdb::WalletDB;
+use crate::wallet::WalletDB;
+use crate::{Error, Result};
 
 
 // Dummy adapter for now
 // Dummy adapter for now
 pub struct RpcAdapter {}
 pub struct RpcAdapter {}
@@ -12,68 +12,51 @@ impl RpcAdapter {
         Arc::new(Self {})
         Arc::new(Self {})
     }
     }
 
 
-    pub async fn key_gen() -> Result<()> {
+    pub async fn get_path(wallet: &str) -> Result<PathBuf> {
+        debug!(target: "adapter", "TEST PATH [START]");
+        let mut path = WalletDB::path().await.expect("Failed to get path");
+        debug!(target: "adapter", "TEST PATH {:?}", path);
+        path.push(wallet);
+        Ok(path)
+    }
+
+    pub async fn key_gen() -> Result<PathBuf> {
         debug!(target: "adapter", "key_gen() [START]");
         debug!(target: "adapter", "key_gen() [START]");
-        let path = dirs::home_dir()
-            .expect("cannot find home directory.")
-            .as_path()
-            .join(".config/darkfi/wallet.db");
-        WalletDB::key_gen(path).await?;
-        Ok(())
+        let path = Self::get_path("wallet.db").await.expect("Failed to get path");
+        //WalletDB::key_gen(path).await?;
+        Ok(path)
     }
     }
 
 
-    // user input should define wallet path
     pub async fn new_wallet() -> Result<()> {
     pub async fn new_wallet() -> Result<()> {
         debug!(target: "adapter", "new_wallet() [START]");
         debug!(target: "adapter", "new_wallet() [START]");
-        let path = dirs::home_dir()
-            .expect("cannot find home directory.")
-            .as_path()
-            .join(".config/darkfi/wallet.db");
+        let path = Self::get_path("wallet.db").await.expect("Failed to get path");
         WalletDB::new(path).await?;
         WalletDB::new(path).await?;
         Ok(())
         Ok(())
     }
     }
 
 
     pub async fn new_cashier_wallet() -> Result<()> {
     pub async fn new_cashier_wallet() -> Result<()> {
-        let path = dirs::home_dir()
-            .expect("cannot find home directory.")
-            .as_path()
-            .join(".config/darkfi/cashier.db");
-        debug!(target: "adapter", "new_wallet() [START]");
+        debug!(target: "adapter", "new_cashier_wallet() [START]");
+        let path = Self::get_path("cashier.db").await.expect("Failed to get path");
         WalletDB::new(path).await?;
         WalletDB::new(path).await?;
         Ok(())
         Ok(())
     }
     }
 
 
     pub async fn save_cash_key(pubkey: Vec<u8>) -> Result<()> {
     pub async fn save_cash_key(pubkey: Vec<u8>) -> Result<()> {
-        let path = dirs::home_dir()
-            .expect("cannot find home directory.")
-            .as_path()
-            .join(".config/darkfi/cashier.db");
-        debug!(target: "adapter", "new_wallet() [START]");
+        debug!(target: "adapter", "save_cash_key() [START]");
+        let path = Self::get_path("cashier.db").await.expect("Failed to get path");
         WalletDB::save(path, pubkey).await?;
         WalletDB::save(path, pubkey).await?;
         Ok(())
         Ok(())
 
 
     }
     }
 
 
     pub async fn save_key(pubkey: Vec<u8>) -> Result<()> {
     pub async fn save_key(pubkey: Vec<u8>) -> Result<()> {
-        let path = dirs::home_dir()
-            .expect("cannot find home directory.")
-            .as_path()
-            .join(".config/darkfi/wallet.db");
-        debug!(target: "adapter", "new_wallet() [START]");
+        debug!(target: "adapter", "save_key() [START]");
+        let path = Self::get_path("wallet.db").await.expect("Failed to get path");
         WalletDB::save(path, pubkey).await?;
         WalletDB::save(path, pubkey).await?;
         Ok(())
         Ok(())
 
 
     }
     }
 
 
-    pub fn wallet_path() -> PathBuf {
-        debug!(target: "wallet_path", "Finding wallet path...");
-        let path = dirs::home_dir()
-            .expect("cannot find home directory.")
-            .as_path()
-            .join(".config/darkfi/wallet.db");
-        path
-    }
-
     pub async fn get_info() {}
     pub async fn get_info() {}
 
 
     pub async fn say_hello() {}
     pub async fn say_hello() {}

+ 5 - 0
src/rpc/jsonserver.rs

@@ -145,6 +145,11 @@ impl RpcInterface {
             Ok(jsonrpc_core::Value::String("Hello World!".into()))
             Ok(jsonrpc_core::Value::String("Hello World!".into()))
         });
         });
 
 
+        io.add_method("test_path", move |_| async move {
+            //RpcAdapter::get_path().await;
+            Ok(jsonrpc_core::Value::String("TEST PATH!".into()))
+        });
+
         io.add_method("get_info", move |_| async move {
         io.add_method("get_info", move |_| async move {
             RpcAdapter::get_info().await;
             RpcAdapter::get_info().await;
             Ok(jsonrpc_core::Value::Null)
             Ok(jsonrpc_core::Value::Null)

+ 2 - 0
src/wallet/mod.rs

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

+ 18 - 2
src/wallet/walletdb.rs

@@ -18,8 +18,24 @@ impl WalletDB {
         Ok(connect.execute_batch(&contents)?)
         Ok(connect.execute_batch(&contents)?)
     }
     }
 
 
-    pub async fn key_gen(path: PathBuf) -> Result<()> {
-        debug!(target: "own_key_gen", "Generating keys...");
+//    pub async fn create_keypair() -> Result<String, String> {
+//        let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
+//        let pubkey = serial::serialize(&public);
+//        let secret: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
+//        let privkey = serial::serialize(&secret);
+//        Ok(pubkey, privkey)
+//    }
+    pub async fn path() -> Result<PathBuf> {
+        let path = dirs::home_dir()
+            .expect("cannot find home directory.")
+            .as_path()
+            .join(".config/darkfi/");
+        debug!(target: "walletdb", "CREATE PATH {:?}", path);
+        Ok(path)
+    }
+
+    pub async fn key_gen(path: PathBuf, id: i32, 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).expect("Failed to connect to database.");
         // TODO: ID should not be fixed
         // TODO: ID should not be fixed
         let id = 0;
         let id = 0;