Forráskód Böngészése

removed own_coins vector. fn apply() now writes directly to sqlite

rachel-rose 5 éve
szülő
commit
23faf56fdd

+ 4 - 6
src/bin/darkfid.rs

@@ -1,6 +1,6 @@
 use async_std::sync::Arc;
 use async_std::sync::Arc;
 //use drk::rpc::
 //use drk::rpc::
-use drk::rpc::adapter::{RpcAdapter, AdapterPtr};
+use drk::rpc::adapter::{AdapterPtr, RpcAdapter};
 use drk::rpc::jsonserver;
 use drk::rpc::jsonserver;
 //use drk::rpc::options::ProgramOptions;
 //use drk::rpc::options::ProgramOptions;
 use rand::rngs::OsRng;
 use rand::rngs::OsRng;
@@ -98,7 +98,7 @@ impl State {
             self.merkle_roots.put(self.tree.root(), vec![] as Vec<u8>)?;
             self.merkle_roots.put(self.tree.root(), vec![] as Vec<u8>)?;
 
 
             // Also update all the coin witnesses
             // Also update all the coin witnesses
-            for (_, _, _, witness) in self.wallet.own_coins.iter_mut() {
+            for witness in self.wallet.witnesses.lock().await.iter_mut() {
                 witness.append(node).expect("append to witness");
                 witness.append(node).expect("append to witness");
             }
             }
 
 
@@ -115,9 +115,7 @@ impl State {
                 // Make a new witness for this coin
                 // Make a new witness for this coin
                 let witness = IncrementalWitness::from_tree(&self.tree);
                 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?;
+                self.wallet.put_own_coins(coin, note, witness).await?;
             }
             }
         }
         }
         Ok(())
         Ok(())
@@ -478,7 +476,7 @@ mod test {
 
 
         let mut thread_pools: Vec<std::thread::JoinHandle<()>> = vec![];
         let mut thread_pools: Vec<std::thread::JoinHandle<()>> = vec![];
 
 
-        // Client A: User 
+        // Client A: User
         let thread = std::thread::spawn(|| {
         let thread = std::thread::spawn(|| {
             smol::future::block_on(async move {
             smol::future::block_on(async move {
                 let connect_addr: SocketAddr = "127.0.0.1:3333".parse().unwrap();
                 let connect_addr: SocketAddr = "127.0.0.1:3333".parse().unwrap();

+ 6 - 3
src/bin/spend-classic.rs

@@ -5,8 +5,8 @@ use ff::{Field, PrimeField};
 use group::{Curve, GroupEncoding};
 use group::{Curve, GroupEncoding};
 
 
 use drk::crypto::{
 use drk::crypto::{
-    create_spend_proof, load_params, save_params, setup_spend_prover, verify_spend_proof,
-    merkle_node::SAPLING_COMMITMENT_TREE_DEPTH,
+    create_spend_proof, load_params, merkle_node::SAPLING_COMMITMENT_TREE_DEPTH, save_params,
+    setup_spend_prover, verify_spend_proof,
 };
 };
 
 
 // This thing is nasty lol
 // This thing is nasty lol
@@ -184,7 +184,10 @@ fn main() {
 
 
     let mut merkle_path = vec![true, false];
     let mut merkle_path = vec![true, false];
     merkle_path.resize(SAPLING_COMMITMENT_TREE_DEPTH, true);
     merkle_path.resize(SAPLING_COMMITMENT_TREE_DEPTH, true);
-    let merkle_path = merkle_path.into_iter().map(|x| (bls12_381::Scalar::random(&mut OsRng), x)).collect();
+    let merkle_path = merkle_path
+        .into_iter()
+        .map(|x| (bls12_381::Scalar::random(&mut OsRng), x))
+        .collect();
 
 
     {
     {
         let params = setup_spend_prover();
         let params = setup_spend_prover();

+ 5 - 1
src/bin/tx.rs

@@ -162,7 +162,11 @@ fn main() {
             signature_secret: cashier_secret,
             signature_secret: cashier_secret,
         }],
         }],
         inputs: vec![],
         inputs: vec![],
-        outputs: vec![tx::TransactionBuilderOutputInfo { value: 110, asset_id: 1, public }],
+        outputs: vec![tx::TransactionBuilderOutputInfo {
+            value: 110,
+            asset_id: 1,
+            public,
+        }],
     };
     };
 
 
     // We will 'compile' the tx, and then serialize it to this Vec<u8>
     // We will 'compile' the tx, and then serialize it to this Vec<u8>

+ 0 - 1
src/circuit/mint_contract.rs

@@ -112,7 +112,6 @@ impl Circuit<bls12_381::Scalar> for MintContract {
         // Line 50: emit_ec ca
         // Line 50: emit_ec ca
         ca.inputize(cs.namespace(|| "Line 50: emit_ec ca"))?;
         ca.inputize(cs.namespace(|| "Line 50: emit_ec ca"))?;
 
 
-
         // Line 39: alloc_binary preimage
         // Line 39: alloc_binary preimage
         let mut preimage = vec![];
         let mut preimage = vec![];
 
 

+ 0 - 1
src/circuit/spend_contract.rs

@@ -96,7 +96,6 @@ impl Circuit<bls12_381::Scalar> for SpendContract {
         // Line 50: emit_ec ca
         // Line 50: emit_ec ca
         ca.inputize(cs.namespace(|| "Line 50: emit_ec ca"))?;
         ca.inputize(cs.namespace(|| "Line 50: emit_ec ca"))?;
 
 
-
         // Line 54: fr_as_binary_le serial param:serial
         // Line 54: fr_as_binary_le serial param:serial
         let serial = boolean::field_into_boolean_vec_le(
         let serial = boolean::field_into_boolean_vec_le(
             cs.namespace(|| "Line 54: fr_as_binary_le serial param:serial"),
             cs.namespace(|| "Line 54: fr_as_binary_le serial param:serial"),

+ 14 - 3
src/crypto/mint_proof.rs

@@ -52,7 +52,11 @@ impl MintRevealedValues {
                 .as_bytes(),
                 .as_bytes(),
         );
         );
 
 
-        MintRevealedValues { value_commit, asset_commit, coin }
+        MintRevealedValues {
+            value_commit,
+            asset_commit,
+            coin,
+        }
     }
     }
 
 
     fn make_outputs(&self) -> [bls12_381::Scalar; 6] {
     fn make_outputs(&self) -> [bls12_381::Scalar; 6] {
@@ -142,8 +146,15 @@ pub fn create_mint_proof(
     randomness_coin: jubjub::Fr,
     randomness_coin: jubjub::Fr,
     public: jubjub::SubgroupPoint,
     public: jubjub::SubgroupPoint,
 ) -> (groth16::Proof<Bls12>, MintRevealedValues) {
 ) -> (groth16::Proof<Bls12>, MintRevealedValues) {
-    let revealed =
-        MintRevealedValues::compute(value, asset_id, &randomness_value, &randomness_asset, &serial, &randomness_coin, &public);
+    let revealed = MintRevealedValues::compute(
+        value,
+        asset_id,
+        &randomness_value,
+        &randomness_asset,
+        &serial,
+        &randomness_coin,
+        &public,
+    );
 
 
     let c = MintContract {
     let c = MintContract {
         value: Some(value),
         value: Some(value),

+ 1 - 1
src/rpc/adapter.rs

@@ -1,7 +1,7 @@
 use crate::wallet::{WalletDB, WalletPtr};
 use crate::wallet::{WalletDB, WalletPtr};
 use crate::Result;
 use crate::Result;
-use log::*;
 use async_std::sync::Arc;
 use async_std::sync::Arc;
+use log::*;
 //use std::sync::Arc;
 //use std::sync::Arc;
 
 
 pub type AdapterPtr = Arc<RpcAdapter>;
 pub type AdapterPtr = Arc<RpcAdapter>;

+ 25 - 16
src/rpc/jsonserver.rs

@@ -155,14 +155,18 @@ impl RpcInterface {
         io.add_method("get_cash_key", move |_| {
         io.add_method("get_cash_key", move |_| {
             let self2 = self1.clone();
             let self2 = self1.clone();
             async move {
             async move {
-                self2.adapter.get_cash_key().await.expect("Failed to get key");
+                self2
+                    .adapter
+                    .get_cash_key()
+                    .await
+                    .expect("Failed to get key");
                 Ok(jsonrpc_core::Value::String("Getting cashier key...".into()))
                 Ok(jsonrpc_core::Value::String("Getting cashier key...".into()))
             }
             }
         });
         });
 
 
         let self1 = self.clone();
         let self1 = self.clone();
         io.add_method("get_info", move |_| {
         io.add_method("get_info", move |_| {
-        let self2 = self1.clone();
+            let self2 = self1.clone();
             async move {
             async move {
                 self2.adapter.get_info().await;
                 self2.adapter.get_info().await;
                 Ok(jsonrpc_core::Value::Null)
                 Ok(jsonrpc_core::Value::Null)
@@ -171,7 +175,7 @@ impl RpcInterface {
 
 
         let self1 = self.clone();
         let self1 = self.clone();
         io.add_method("stop", move |_| {
         io.add_method("stop", move |_| {
-        let self2 = self1.clone();
+            let self2 = self1.clone();
             async move {
             async move {
                 self2.adapter.stop().await;
                 self2.adapter.stop().await;
                 Ok(jsonrpc_core::Value::Null)
                 Ok(jsonrpc_core::Value::Null)
@@ -181,11 +185,10 @@ 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);
-            Ok(jsonrpc_core::Value::String(
-                "Created wallet".into(),))
+                println!("New wallet method called...");
+                //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()))
             }
             }
         });
         });
         let self1 = self.clone();
         let self1 = self.clone();
@@ -193,7 +196,11 @@ impl RpcInterface {
             let self2 = self1.clone();
             let self2 = self1.clone();
             async move {
             async move {
                 println!("Key generation method called...");
                 println!("Key generation method called...");
-                self2.adapter.key_gen().await.expect("Failed to generate key");
+                self2
+                    .adapter
+                    .key_gen()
+                    .await
+                    .expect("Failed to generate key");
                 Ok(jsonrpc_core::Value::String(
                 Ok(jsonrpc_core::Value::String(
                     "Attempted key generation".into(),
                     "Attempted key generation".into(),
                 ))
                 ))
@@ -204,7 +211,11 @@ impl RpcInterface {
             let self2 = self1.clone();
             let self2 = self1.clone();
             async move {
             async move {
                 println!("Key generation method called...");
                 println!("Key generation method called...");
-                self2.adapter.cash_key_gen().await.expect("Failed to generate key");
+                self2
+                    .adapter
+                    .cash_key_gen()
+                    .await
+                    .expect("Failed to generate key");
                 Ok(jsonrpc_core::Value::String(
                 Ok(jsonrpc_core::Value::String(
                     "Attempted key generation".into(),
                     "Attempted key generation".into(),
                 ))
                 ))
@@ -214,12 +225,10 @@ impl RpcInterface {
         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...");
-            //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(),
-            ))
+                println!("New wallet method called...");
+                //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()))
             }
             }
         });
         });
         debug!(target: "rpc", "JsonRpcInterface::handle_input() [END]");
         debug!(target: "rpc", "JsonRpcInterface::handle_input() [END]");

+ 1 - 1
src/rpc/mod.rs

@@ -2,4 +2,4 @@ pub mod adapter;
 pub mod jsonserver;
 pub mod jsonserver;
 pub mod test;
 pub mod test;
 
 
-pub use adapter::{RpcAdapter, AdapterPtr};
+pub use adapter::{AdapterPtr, RpcAdapter};

+ 14 - 3
src/tx/mod.rs

@@ -68,9 +68,20 @@ impl Transaction {
         assert_ne!(self.outputs.len(), 0);
         assert_ne!(self.outputs.len(), 0);
         let asset_commit_value = self.outputs[0].revealed.asset_commit;
         let asset_commit_value = self.outputs[0].revealed.asset_commit;
 
 
-        let mut failed = self.inputs.iter().any(|input| input.revealed.asset_commit != asset_commit_value);
-        failed = failed || self.outputs.iter().any(|output| output.revealed.asset_commit != asset_commit_value);
-        failed = failed || self.clear_inputs.iter().any(|input| Self::compute_pedersen_commit(input.asset_id, &input.asset_commit_blind) != asset_commit_value);
+        let mut failed = self
+            .inputs
+            .iter()
+            .any(|input| input.revealed.asset_commit != asset_commit_value);
+        failed = failed
+            || self
+                .outputs
+                .iter()
+                .any(|output| output.revealed.asset_commit != asset_commit_value);
+        failed = failed
+            || self.clear_inputs.iter().any(|input| {
+                Self::compute_pedersen_commit(input.asset_id, &input.asset_commit_blind)
+                    != asset_commit_value
+            });
         !failed
         !failed
     }
     }
 
 

+ 25 - 15
src/wallet/walletdb.rs

@@ -3,7 +3,7 @@ use crate::serial;
 use crate::serial::{deserialize, serialize, Decodable, Encodable};
 use crate::serial::{deserialize, serialize, Decodable, Encodable};
 use crate::Error;
 use crate::Error;
 use crate::Result;
 use crate::Result;
-use async_std::sync::Arc;
+use async_std::sync::{Arc, Mutex};
 use ff::Field;
 use ff::Field;
 use log::*;
 use log::*;
 use rand::rngs::OsRng;
 use rand::rngs::OsRng;
@@ -17,11 +17,11 @@ pub struct WalletDB {
     pub path: PathBuf,
     pub path: PathBuf,
     pub secrets: Vec<jubjub::Fr>,
     pub secrets: Vec<jubjub::Fr>,
     pub cashier_secrets: Vec<jubjub::Fr>,
     pub cashier_secrets: Vec<jubjub::Fr>,
-    //pub coin: Coin,
-    //pub note: Note,
-    //pub witness: IncrementalWitness<MerkleNode>,
+    pub coins: Mutex<Vec<Coin>>,
+    pub notes: Mutex<Vec<Note>>,
+    pub witnesses: Mutex<Vec<IncrementalWitness<MerkleNode>>>,
     // wrap in mutex or read/write lock
     // wrap in mutex or read/write lock
-    pub own_coins: Vec<(Coin, Note, jubjub::Fr, IncrementalWitness<MerkleNode>)>,
+    //pub own_coins: Vec<(Coin, Note, jubjub::Fr, IncrementalWitness<MerkleNode>)>,
     pub cashier_public: jubjub::SubgroupPoint,
     pub cashier_public: jubjub::SubgroupPoint,
     pub public: jubjub::SubgroupPoint,
     pub public: jubjub::SubgroupPoint,
     //conn: Arc<Connection>,
     //conn: Arc<Connection>,
@@ -30,7 +30,7 @@ pub struct WalletDB {
 impl WalletDB {
 impl WalletDB {
     pub fn new(wallet: &str) -> Result<Self> {
     pub fn new(wallet: &str) -> Result<Self> {
         debug!(target: "walletdb", "new() Constructor called");
         debug!(target: "walletdb", "new() Constructor called");
-        //let path = Self::create_path(wallet)?;
+        let path = Self::create_path(wallet)?;
         //let conn = Connection::open(&path)?;
         //let conn = Connection::open(&path)?;
         //debug!(target: "walletdb", "OPENED CONNECTION AT PATH {:?}", path);
         //debug!(target: "walletdb", "OPENED CONNECTION AT PATH {:?}", path);
         //let contents = include_str!("../../res/schema.sql");
         //let contents = include_str!("../../res/schema.sql");
@@ -38,36 +38,46 @@ impl WalletDB {
         let 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;
         let cashier_public = zcash_primitives::constants::SPENDING_KEY_GENERATOR * cashier_secret;
+        let coins = Mutex::new(Vec::new());
+        let notes = Mutex::new(Vec::new());
+        let witnesses = Mutex::new(Vec::new());
         //match conn.execute_batch(&contents) {
         //match conn.execute_batch(&contents) {
         //    Ok(v) => println!("Database initalized successfully {:?}", v),
         //    Ok(v) => println!("Database initalized successfully {:?}", v),
         //    Err(err) => println!("Error: {}", err),
         //    Err(err) => println!("Error: {}", err),
         //};
         //};
         debug!(target: "walletdb", "new(): wallet constructor called");
         debug!(target: "walletdb", "new(): wallet constructor called");
         Ok(Self {
         Ok(Self {
-            path: Self::create_path(wallet)?,
-            own_coins: vec![],
+            path,
+            //own_coins: vec![],
             cashier_secrets: vec![cashier_secret.clone()],
             cashier_secrets: vec![cashier_secret.clone()],
             secrets: vec![secret.clone()],
             secrets: vec![secret.clone()],
             cashier_public,
             cashier_public,
             public,
             public,
-            //coin,
-            //note,
-            //witness,
+            coins,
+            notes,
+            witnesses,
             //conn,
             //conn,
         })
         })
     }
     }
 
 
     //coin, serial, value, asset_id, coin_blind, valcom_blind, witness, key_id
     //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;
+    pub async fn put_own_coins(
+        &self,
+        coin: Coin,
+        note: Note,
+        witness: IncrementalWitness<MerkleNode>,
+    ) -> Result<()> {
+        let coin = self.get_value_serialized(&coin.repr).await?;
+        //let coin = self.get_value_serialized(&self.own_coins[0].0.repr).await?;
+        //let note = &self.own_coins[0].1;
         let serial = self.get_value_serialized(&note.serial).await?;
         let serial = self.get_value_serialized(&note.serial).await?;
         let coin_blind = self.get_value_serialized(&note.coin_blind).await?;
         let coin_blind = self.get_value_serialized(&note.coin_blind).await?;
         let valcom_blind = self.get_value_serialized(&note.valcom_blind).await?;
         let valcom_blind = self.get_value_serialized(&note.valcom_blind).await?;
         let value = self.get_value_serialized(&note.value).await?;
         let value = self.get_value_serialized(&note.value).await?;
         let asset_id = self.get_value_serialized(&note.asset_id).await?;
         let asset_id = self.get_value_serialized(&note.asset_id).await?;
         let conn = Connection::open(&self.path)?;
         let conn = Connection::open(&self.path)?;
-        let witness = self.get_value_serialized(&self.own_coins[0].3).await?;
+        let witness = self.get_value_serialized(&witness).await?;
+        //let witness = self.get_value_serialized(&self.own_coins[0].3).await?;
         conn.execute(
         conn.execute(
             "INSERT INTO coins(coin, serial, value, asset_id, coin_blind, valcom_blind, witness, key_id)
             "INSERT INTO coins(coin, serial, value, asset_id, coin_blind, valcom_blind, witness, key_id)
             VALUES (NULL, :coin, :serial, :value, :asset_id, :coin_blind, :valcom_blind, :witness, :key_id)",
             VALUES (NULL, :coin, :serial, :value, :asset_id, :coin_blind, :valcom_blind, :witness, :key_id)",