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

added wallet tests. updated adapter functions to init_db()

rachel-rose 5 лет назад
Родитель
Сommit
e0053026aa
7 измененных файлов с 96 добавлено и 87 удалено
  1. 6 24
      scripts/dark_client/drk.py
  2. 5 37
      scripts/dark_client/util.py
  3. 0 8
      src/bin/darkfid.rs
  4. 8 0
      src/error.rs
  5. 23 3
      src/rpc/adapter.rs
  6. 34 14
      src/rpc/jsonserver.rs
  7. 20 1
      src/wallet/walletdb.rs

+ 6 - 24
scripts/dark_client/drk.py

@@ -18,27 +18,6 @@ class DarkClient:
                 "id": [],
                 "id": [],
                 }
                 }
 
 
-    #def ckeygen(self, payload):
-    #    payload['method'] = "cash_key_gen"
-    #    payload['jsonrpc'] = "2.0"
-    #    payload['id'] = "0"
-    #    ckeygen = self.__request(payload)
-    #    print(ckeygen)
-
-    #def cashkey(self, payload):
-    #    payload['method'] = "get_cash_key"
-    #    payload['jsonrpc'] = "2.0"
-    #    payload['id'] = "0"
-    #    cashk = self.__request(payload)
-    #    print(cashk)
-    #
-    #def test_path(self, payload):
-    #    payload['method'] = "test_path"
-    #    payload['jsonrpc'] = "2.0"
-    #    payload['id'] = "0"
-    #    test = self.__request(payload)
-    #    print(test)
-
     async def key_gen(self, payload):
     async def key_gen(self, payload):
         payload['method'] = "key_gen"
         payload['method'] = "key_gen"
         payload['jsonrpc'] = "2.0"
         payload['jsonrpc'] = "2.0"
@@ -81,15 +60,18 @@ class DarkClient:
         wallet = await self.__request(payload)
         wallet = await self.__request(payload)
         print(wallet)
         print(wallet)
 
 
+    async def test_wallet(self, payload):
+        payload['method'] = "test_wallet"
+        payload['jsonrpc'] = "2.0"
+        payload['id'] = "0"
+        test = await self.__request(payload)
+        print(test)
 
 
     async def __request(self, payload):
     async def __request(self, payload):
         async with self.client_session.post(self.url, json=payload) as response:
         async with self.client_session.post(self.url, json=payload) as response:
             resp = await response.text()
             resp = await response.text()
             print(resp)
             print(resp)
 
 
-
-
-
 async def main():
 async def main():
     try:
     try:
         async with aiohttp.ClientSession() as session:
         async with aiohttp.ClientSession() as session:

+ 5 - 37
scripts/dark_client/util.py

@@ -14,6 +14,7 @@ async def arg_parser(client):
     parser.add_argument('-i', '--info', action='store_true', help='Request info from daemon')
     parser.add_argument('-i', '--info', action='store_true', help='Request info from daemon')
     parser.add_argument('-hi', '--hello', action='store_true', help='Test hello')
     parser.add_argument('-hi', '--hello', action='store_true', help='Test hello')
     parser.add_argument("-s", "--stop", action='store_true', help="Send a stop signal to the daemon")
     parser.add_argument("-s", "--stop", action='store_true', help="Send a stop signal to the daemon")
+    parser.add_argument("-t", "--test", action='store_true', help="Test writing to the wallet")
 
 
     try:
     try:
         args = parser.parse_args()
         args = parser.parse_args()
@@ -44,42 +45,9 @@ async def arg_parser(client):
             print("Attempting to generate a cashier wallet...")
             print("Attempting to generate a cashier wallet...")
             await client.create_cashier_wallet(client.payload)
             await client.create_cashier_wallet(client.payload)
 
 
+        if args.test:
+            print("Testing wallet write")
+            await client.test_wallet(client.payload)
+
     except Exception:
     except Exception:
         raise
         raise
-
-    #subparser = parser.add_subparsers(help='All available commands', title="Commands", dest='cmd')
-    #subparser.metavar = 'subcommands';
-    #login = subparser.add_parser('login', help='wallet login')
-    ##test = subparser.add_parser('test', help='test wallet functions')
-    #new = subparser.add_parser('new', help='create something new')
-
-    #new.add_argument('-w', '--wallet', action='store_true', help='Create a new wallet')
-    #new.add_argument('-k', '--key', action='store_true', help='Create a new key')
-    #new.add_argument('-c', '--cashier', action='store_true', help='Create a cashier wallet')
-
-    #login.add_argument('-u', '--username', type=str, required=True)
-    #login.add_argument('-p', '--password', type=str, required=True)
-
-    ##test.add_argument('-k', '--key', dest='key', action='store_true', help='Test key')
-    ##test.add_argument('-p', '--path', dest='path', action='store_true', help='Test path')
-    ##test.add_argument('-pk', '--pkey', dest='pkey', action='store_true', help='Print test key')
-    ##test.add_argument('-ck', '--ckey', dest='ckey', action='store_true', help='Cashier test key')
-    ##test.add_argument('-w', '--wallet', dest='wallet', action='store_true', help='Create a new wallet')
-    ##test.add_argument('-c', '--cashier', dest='cashier',action='store_true', help='Create a cashier wallet')
-
-    #if args.path:
-    #    try:
-    #        print("Testing path...")
-    #        client.test_path(client.payload)
-    #    except Exception:
-    #        raise
-
-    #if args.pkey:
-    #    try:
-    #        print("Attempting to print cashier key...")
-    #        client.cashkey(client.payload)
-    #    except Exception:
-    #        raise
-
-
-

+ 0 - 8
src/bin/darkfid.rs

@@ -169,8 +169,6 @@ async fn start(executor: Arc<Executor<'_>>, options: Arc<WalletCli>) -> Result<(
 
 
     let slabstore = RocksColumn::<columns::Slabs>::new(rocks.clone());
     let slabstore = RocksColumn::<columns::Slabs>::new(rocks.clone());
 
 
-    //let adapter = RpcAdapter::new("wallet.db")?;
-    //
     // Auto create trusted ceremony parameters if they don't exist
     // Auto create trusted ceremony parameters if they don't exist
     if !Path::new("mint.params").exists() {
     if !Path::new("mint.params").exists() {
         let params = setup_mint_prover();
         let params = setup_mint_prover();
@@ -196,12 +194,6 @@ async fn start(executor: Arc<Executor<'_>>, options: Arc<WalletCli>) -> Result<(
     let merkle_roots = RocksColumn::<columns::MerkleRoots>::new(rocks.clone());
     let merkle_roots = RocksColumn::<columns::MerkleRoots>::new(rocks.clone());
     let nullifiers = RocksColumn::<columns::Nullifiers>::new(rocks);
     let nullifiers = RocksColumn::<columns::Nullifiers>::new(rocks);
 
 
-    //let wallet = adapter.wallet;
-    let wallet = Arc::new(WalletDB::new("wallet.db")?);
-
-    //let wallet2 = wallet.clone();
-    let ex = executor.clone();
-
     let state = State {
     let state = State {
         tree: CommitmentTree::empty(),
         tree: CommitmentTree::empty(),
         merkle_roots,
         merkle_roots,

+ 8 - 0
src/error.rs

@@ -1,4 +1,5 @@
 // TODO: Add support for rusqlite error
 // TODO: Add support for rusqlite error
+use jsonrpc_core::*;
 use rusqlite;
 use rusqlite;
 use std::fmt;
 use std::fmt;
 
 
@@ -108,6 +109,13 @@ impl From<jsonrpc_core::Error> for Error {
     }
     }
 }
 }
 
 
+
+//impl From<Error> for jsonrpc_core::types::error::Error {
+//    fn from(err: Error) -> jsonrpc_core::types::error::Error {
+//        jsonrpc_core::types::error::Error::ErrorCode
+//    }
+//}
+
 impl From<std::io::Error> for Error {
 impl From<std::io::Error> for Error {
     fn from(err: std::io::Error) -> Error {
     fn from(err: std::io::Error) -> Error {
         Error::Io(err.kind())
         Error::Io(err.kind())

+ 23 - 3
src/rpc/adapter.rs

@@ -16,17 +16,31 @@ impl RpcAdapter {
         Ok(Self { wallet })
         Ok(Self { wallet })
     }
     }
 
 
+    pub async fn init_db(&self) -> Result<()> {
+        debug!(target: "adapter", "init_db() [START]");
+        self.wallet.init_db().await?;
+        Ok(())
+    }
+
+    pub async fn init_cashier_db(&self) -> Result<()> {
+        debug!(target: "adapter", "init_cashier_db() [START]");
+        self.wallet.init_cashier_db().await?;
+        Ok(())
+    }
+
     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;
+        debug!(target: "adapter", "Created keypair...");
+        debug!(target: "adapter", "Attempting to write to database...");
         self.wallet.put_keypair(public, private).await?;
         self.wallet.put_keypair(public, private).await?;
         Ok(())
         Ok(())
     }
     }
 
 
     pub async fn cash_key_gen(&self) -> Result<()> {
     pub async fn cash_key_gen(&self) -> Result<()> {
         debug!(target: "adapter", "key_gen() [START]");
         debug!(target: "adapter", "key_gen() [START]");
-        let (_public, _private) = self.wallet.key_gen().await;
-        //self.wallet.put_keypair(public, private).await?;
+        let (public, private) = self.wallet.key_gen().await;
+        self.wallet.put_keypair(public, private).await?;
         Ok(())
         Ok(())
     }
     }
 
 
@@ -39,11 +53,17 @@ impl RpcAdapter {
 
 
     pub async fn get_cash_key(&self) -> Result<()> {
     pub async fn get_cash_key(&self) -> Result<()> {
         debug!(target: "adapter", "get_cash_key() [START]");
         debug!(target: "adapter", "get_cash_key() [START]");
-        let cashier_public = self.wallet.get_public().await?;
+        let cashier_public = self.wallet.get_cashier_public().await?;
         println!("{:?}", cashier_public);
         println!("{:?}", cashier_public);
         Ok(())
         Ok(())
     }
     }
 
 
+    pub async fn test_wallet(&self) -> Result<()> {
+        self.wallet.test_wallet()?;
+        debug!(target: "adapter", "test wallet: START");
+        Ok(())
+    }
+
     //pub async fn walletdb(&self) -> WalletPtr {
     //pub async fn walletdb(&self) -> WalletPtr {
     //    self.wallet.clone();
     //    self.wallet.clone();
     //}
     //}

+ 34 - 14
src/rpc/jsonserver.rs

@@ -1,3 +1,4 @@
+use jsonrpc_core::types::error::ErrorCode as JsonError;
 use crate::rpc::adapter::RpcAdapter;
 use crate::rpc::adapter::RpcAdapter;
 use crate::cli::WalletCli;
 use crate::cli::WalletCli;
 use crate::{Error, Result};
 use crate::{Error, Result};
@@ -76,9 +77,7 @@ pub async fn start(
     options: Arc<WalletCli>,
     options: Arc<WalletCli>,
     adapter: RpcAdapter,
     adapter: RpcAdapter,
 ) -> Result<()> {
 ) -> Result<()> {
-    debug!(target: "JSONSERVER", "START FUNCTION CALLED");
     let rpc = RpcInterface::new(adapter)?;
     let rpc = RpcInterface::new(adapter)?;
-    debug!(target: "JSONSERVER", "Listening...");
     let http = listen(
     let http = listen(
         executor.clone(),
         executor.clone(),
         rpc.clone(),
         rpc.clone(),
@@ -86,16 +85,12 @@ pub async fn start(
         None,
         None,
     );
     );
 
 
-    debug!(target: "JSONSERVER", "Spawning http task...");
     let http_task = executor.spawn(http);
     let http_task = executor.spawn(http);
 
 
-    debug!(target: "JSONSERVER", "Locking...");
     *rpc.started.lock().await = true;
     *rpc.started.lock().await = true;
 
 
-    debug!(target: "JSONSERVER", "Waiting for quit...");
     rpc.wait_for_quit().await?;
     rpc.wait_for_quit().await?;
 
 
-    debug!(target: "JSONSERVER", "Cancel http task...");
     http_task.cancel().await;
     http_task.cancel().await;
 
 
     Ok(())
     Ok(())
@@ -146,11 +141,14 @@ 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()))
+        let self1 = self.clone();
+        io.add_method("get_key", move |_| {
+            let self2 = self1.clone();
+            async move {
+                self2.adapter.get_key().await.expect("Failed to get key");
+                Ok(jsonrpc_core::Value::String("Getting cashier key...".into()))
+            }
         });
         });
-
         let self1 = self.clone();
         let self1 = self.clone();
         io.add_method("get_cash_key", move |_| {
         io.add_method("get_cash_key", move |_| {
             let self2 = self1.clone();
             let self2 = self1.clone();
@@ -185,9 +183,15 @@ impl RpcInterface {
         io.add_method("create_wallet", move |_| {
         io.add_method("create_wallet", move |_| {
             let self2 = self1.clone();
             let self2 = self1.clone();
             async move {
             async move {
-                println!("New wallet method called...");
-                //RpcAdapter::new("wallet.db").expect("Failed to create wallet");
-                println!("Wallet created at path {:?}", self2.adapter.wallet.path);
+                println!(
+                    "Attempting wallet generation at path {:?}",
+                    self2.adapter.wallet.path
+                );
+                self2
+                    .adapter
+                    .init_db()
+                    .await
+                    .expect("Wallet generation failed");
                 Ok(jsonrpc_core::Value::String("Created wallet".into()))
                 Ok(jsonrpc_core::Value::String("Created wallet".into()))
             }
             }
         });
         });
@@ -222,11 +226,27 @@ impl RpcInterface {
             }
             }
         });
         });
         let self1 = self.clone();
         let self1 = self.clone();
+        io.add_method("test_wallet", move |_| {
+            let self2 = self1.clone();
+            async move {
+                println!("Test wallet method called...");
+                // use map err to convert from own error to jsonrpc
+                // convert our error to string 
+                // use json to process error string
+
+                self2.adapter.test_wallet().await.expect("Wallet test failed");
+                Ok(jsonrpc_core::Value::String("Test wallet".into()))
+            }
+        });
+        let self1 = self.clone();
         io.add_method("create_cashier_wallet", move |_| {
         io.add_method("create_cashier_wallet", move |_| {
             let self2 = self1.clone();
             let self2 = self1.clone();
             async move {
             async move {
                 println!("New wallet method called...");
                 println!("New wallet method called...");
-                //RpcAdapter::new("cashier.db").expect("Failed to create wallet");
+                self2
+                    .adapter
+                    .init_cashier_db()
+                    .await.expect("Create wallet failed");
                 println!("Wallet created at path {:?}", self2.adapter.wallet.path);
                 println!("Wallet created at path {:?}", self2.adapter.wallet.path);
                 Ok(jsonrpc_core::Value::String("Created cashier wallet".into()))
                 Ok(jsonrpc_core::Value::String("Created cashier wallet".into()))
             }
             }

+ 20 - 1
src/wallet/walletdb.rs

@@ -59,6 +59,18 @@ impl WalletDB {
         Ok(())
         Ok(())
     }
     }
 
 
+    pub async fn init_cashier_db(&self) -> Result<()> {
+        let path = Self::create_path("cashier.db")?;
+        let conn = Connection::open(&self.path)?;
+        debug!(target: "walletdb", "OPENED CONNECTION AT PATH {:?}", self.path);
+        let contents = include_str!("../../res/schema.sql");
+        match conn.execute_batch(&contents) {
+            Ok(v) => println!("Database initalized successfully {:?}", v),
+            Err(err) => println!("Error: {}", err),
+        };
+        Ok(())
+    }
+
     pub async fn put_own_coins(
     pub async fn put_own_coins(
         &self,
         &self,
         coin: Coin,
         coin: Coin,
@@ -92,7 +104,7 @@ impl WalletDB {
 
 
 
 
     pub async fn key_gen(&self) -> (Vec<u8>, Vec<u8>) {
     pub async fn key_gen(&self) -> (Vec<u8>, Vec<u8>) {
-        debug!(target: "key_gen", "Generating keys...");
+        debug!(target: "key_gen", "Attempting to generate keys...");
         let secret: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
         let secret: jubjub::Fr = jubjub::Fr::random(&mut OsRng);
         let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
         let public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * secret;
         let pubkey = serial::serialize(&public);
         let pubkey = serial::serialize(&public);
@@ -170,6 +182,13 @@ impl WalletDB {
         Ok(keys)
         Ok(keys)
     }
     }
 
 
+    pub fn test_wallet(&self) -> Result<()> {
+        let conn = Connection::open(&self.path)?;
+        let mut stmt = conn.prepare("SELECT * FROM keys")?;
+        stmt.execute(["NULL"])?;
+        Ok(())
+    }
+
     pub async fn get_value_serialized<T: Encodable>(&self, data: &T) -> Result<Vec<u8>> {
     pub async fn get_value_serialized<T: Encodable>(&self, data: &T) -> Result<Vec<u8>> {
         let v = serialize(data);
         let v = serialize(data);
         Ok(v)
         Ok(v)