Jelajahi Sumber

remove restrictions to generate more than one keypair & load the all the keys from walletdb

ghassmo 4 tahun lalu
induk
melakukan
3c91d0d2fa
3 mengubah file dengan 42 tambahan dan 30 penghapusan
  1. 17 5
      src/bin/darkfid.rs
  2. 5 0
      src/client.rs
  3. 20 25
      src/wallet/walletdb.rs

+ 17 - 5
src/bin/darkfid.rs

@@ -164,6 +164,18 @@ impl Darkfid {
         JsonResult::Resp(jsonresp(json!(b58), id))
     }
 
+    // --> {"method": "get_keys", "params": []}
+    // <-- {"result": "[vdNS7oBj7KvsMWWmo9r96SV4SqATLrGsH2a3PGpCfJC, ... ]"}
+    async fn get_keys(&self, id: Value, _params: Value) -> JsonResult {
+        match self.client.lock().await.get_keypairs().await {
+            Ok(_) => {
+                // TODO
+                JsonResult::Resp(jsonresp(json!(vec!["ADDRESS", "ADDRESS"]), id))
+            }
+            Err(err) => JsonResult::Err(jsonerr(ServerError(-32002), Some(err.to_string()), id)),
+        }
+    }
+
     // --> {"method": "get_balances", "params": []}
     // <-- {"result": "get_balances": "[ {"btc": (value, network)}, .. ]"}
     async fn get_balances(&self, id: Value, _params: Value) -> JsonResult {
@@ -270,11 +282,11 @@ impl Darkfid {
     async fn features(&self, id: Value, _params: Value) -> JsonResult {
         let req = jsonreq(json!("features"), json!([]));
         let rep: JsonResult =
-        // NOTE: this just selects the first cashier in the list
-        match send_raw_request(&self.cashiers[0].rpc_url, json!(req)).await {
-            Ok(v) => v,
-            Err(e) => return JsonResult::Err(jsonerr(ServerError(-32004), Some(e.to_string()), id)),
-        };
+            // NOTE: this just selects the first cashier in the list
+            match send_raw_request(&self.cashiers[0].rpc_url, json!(req)).await {
+                Ok(v) => v,
+                Err(e) => return JsonResult::Err(jsonerr(ServerError(-32004), Some(e.to_string()), id)),
+            };
 
         match rep {
             JsonResult::Resp(r) => JsonResult::Resp(r),

+ 5 - 0
src/client.rs

@@ -1,4 +1,5 @@
 use async_std::sync::{Arc, Mutex};
+
 use incrementalmerkletree::{bridgetree::BridgeTree, Tree};
 use log::{debug, info, trace, warn};
 use smol::Executor;
@@ -374,6 +375,10 @@ impl Client {
         self.wallet.confirm_spend_coin(coin).await
     }
 
+    pub async fn get_keypairs(&self) -> Result<Vec<Keypair>> {
+        self.wallet.get_keypairs().await
+    }
+
     pub async fn key_gen(&self) -> Result<()> {
         self.wallet.key_gen().await
     }

+ 20 - 25
src/wallet/walletdb.rs

@@ -92,26 +92,15 @@ impl WalletDb {
 
     pub async fn key_gen(&self) -> Result<()> {
         debug!("Attempting to generate keypairs");
-        let mut conn = self.conn.acquire().await?;
-
-        // TODO: Think about multiple keys
-        match sqlx::query("SELECT * FROM keys WHERE key_id > ?").fetch_one(&mut conn).await {
-            Ok(_) => {
-                error!("Keys already exist");
-                Err(Error::from(ClientFailed::KeyExists))
-            }
-            Err(_) => {
-                let keypair = Keypair::random(&mut OsRng);
-                self.put_keypair(&keypair.public, &keypair.secret).await?;
-                Ok(())
-            }
-        }
+        let keypair = Keypair::random(&mut OsRng);
+        self.put_keypair(&keypair).await?;
+        Ok(())
     }
 
-    pub async fn put_keypair(&self, public: &PublicKey, secret: &SecretKey) -> Result<()> {
+    pub async fn put_keypair(&self, keypair: &Keypair) -> Result<()> {
         debug!("Writing keypair into the wallet database");
-        let pubkey = serialize(&public.0);
-        let secret = serialize(&secret.0);
+        let pubkey = serialize(&keypair.public);
+        let secret = serialize(&keypair.secret);
 
         let mut conn = self.conn.acquire().await?;
         sqlx::query("INSERT INTO keys(public, secret) VALUES (?1, ?2)")
@@ -127,12 +116,15 @@ impl WalletDb {
         debug!("Returning keypairs");
         let mut conn = self.conn.acquire().await?;
 
-        // TODO: Think about multiple keys
-        let row = sqlx::query("SELECT * FROM keys").fetch_one(&mut conn).await?;
-        let public: PublicKey = self.get_value_deserialized(row.get("public"))?;
-        let secret: SecretKey = self.get_value_deserialized(row.get("secret"))?;
+        let mut keypairs = vec![];
+
+        for row in sqlx::query("SELECT * FROM keys").fetch_all(&mut conn).await? {
+            let public: PublicKey = self.get_value_deserialized(row.get("public"))?;
+            let secret: SecretKey = self.get_value_deserialized(row.get("secret"))?;
+            keypairs.push(Keypair { public, secret });
+        }
 
-        Ok(vec![Keypair { public, secret }])
+        Ok(keypairs)
     }
 
     pub async fn tree_gen(&self) -> Result<BridgeTree<MerkleNode, 32>> {
@@ -383,7 +375,7 @@ mod tests {
         let mut tree1 = wallet.tree_gen().await?;
 
         // put_keypair()
-        wallet.put_keypair(&keypair.public, &keypair.secret).await?;
+        wallet.put_keypair(&keypair).await?;
 
         let token_id = DrkTokenId::random(&mut OsRng);
 
@@ -432,8 +424,11 @@ mod tests {
         assert_eq!(balances.list[3].token_id, token_id);
 
         // get_keypairs()
-        let keypair_r = wallet.get_keypairs().await?[0];
-        assert_eq!(keypair, keypair_r);
+        let keypair2 = Keypair::random(&mut OsRng);
+        wallet.put_keypair(&keypair2).await?;
+        let keypairs = wallet.get_keypairs().await?;
+        assert_eq!(keypair, keypairs[0]);
+        assert_eq!(keypair2, keypairs[1]);
 
         // get_own_coins()
         let own_coins = wallet.get_own_coins().await?;