Răsfoiți Sursa

daod: bugfix x2 -- fix multiple imports of State + CallData causing state_transition to crash

lunar-mining 4 ani în urmă
părinte
comite
72a2d46e96

+ 1 - 19
bin/daod/src/dao_contract/mint/builder.rs

@@ -11,7 +11,7 @@ use halo2_proofs::circuit::Value;
 use pasta_curves::{arithmetic::CurveAffine, group::Curve, pallas};
 use pasta_curves::{arithmetic::CurveAffine, group::Curve, pallas};
 use rand::rngs::OsRng;
 use rand::rngs::OsRng;
 
 
-use crate::{demo::FuncCall, CallDataBase, ZkBinaryTable};
+use crate::{dao_contract::mint::validate::CallData, demo::FuncCall, CallDataBase, ZkBinaryTable};
 
 
 pub struct Builder {
 pub struct Builder {
     dao_proposer_limit: u64,
     dao_proposer_limit: u64,
@@ -101,21 +101,3 @@ impl Builder {
         }
         }
     }
     }
 }
 }
-
-pub struct CallData {
-    dao_bulla: DaoBulla,
-}
-
-impl CallDataBase for CallData {
-    fn zk_public_values(&self) -> Vec<Vec<DrkCircuitField>> {
-        vec![vec![self.dao_bulla.0]]
-    }
-
-    fn zk_proof_addrs(&self) -> Vec<String> {
-        vec!["dao-mint".to_string()]
-    }
-
-    fn as_any(&self) -> &dyn Any {
-        self
-    }
-}

+ 3 - 29
bin/daod/src/dao_contract/mint/mod.rs

@@ -1,14 +1,3 @@
-use std::any::Any;
-
-use darkfi::crypto::types::DrkCircuitField;
-
-use super::state::DaoBulla;
-use crate::demo::CallDataBase;
-
-pub mod builder;
-pub mod validate;
-pub use builder::Builder;
-
 /// This is an anonymous contract function that mutates the internal DAO state.
 /// This is an anonymous contract function that mutates the internal DAO state.
 ///
 ///
 /// Corresponds to `mint(proposer_limit, quorum, approval_ratio, dao_pubkey, dao_blind)`
 /// Corresponds to `mint(proposer_limit, quorum, approval_ratio, dao_pubkey, dao_blind)`
@@ -43,21 +32,6 @@ pub use builder::Builder;
 /// );
 /// );
 /// let tx = builder.build();
 /// let tx = builder.build();
 /// ```
 /// ```
-
-pub struct CallData {
-    pub dao_bulla: DaoBulla,
-}
-
-impl CallDataBase for CallData {
-    fn zk_public_values(&self) -> Vec<Vec<DrkCircuitField>> {
-        vec![vec![self.dao_bulla.0]]
-    }
-
-    fn zk_proof_addrs(&self) -> Vec<String> {
-        vec!["dao-mint".to_string()]
-    }
-
-    fn as_any(&self) -> &dyn Any {
-        self
-    }
-}
+pub mod builder;
+pub mod validate;
+pub use builder::Builder;

+ 22 - 2
bin/daod/src/dao_contract/mint/validate.rs

@@ -1,9 +1,11 @@
 use pasta_curves::pallas;
 use pasta_curves::pallas;
 use std::any::{Any, TypeId};
 use std::any::{Any, TypeId};
 
 
+use darkfi::crypto::types::DrkCircuitField;
+
 use crate::{
 use crate::{
-    dao_contract::{mint::CallData, DaoBulla, State},
-    demo::{StateRegistry, Transaction},
+    dao_contract::{DaoBulla, State},
+    demo::{CallDataBase, StateRegistry, Transaction},
 };
 };
 
 
 pub fn state_transition(
 pub fn state_transition(
@@ -42,3 +44,21 @@ pub enum Error {
     MalformedPacket,
     MalformedPacket,
 }
 }
 type Result<T> = std::result::Result<T, Error>;
 type Result<T> = std::result::Result<T, Error>;
+
+pub struct CallData {
+    pub dao_bulla: DaoBulla,
+}
+
+impl CallDataBase for CallData {
+    fn zk_public_values(&self) -> Vec<Vec<DrkCircuitField>> {
+        vec![vec![self.dao_bulla.0]]
+    }
+
+    fn zk_proof_addrs(&self) -> Vec<String> {
+        vec!["dao-mint".to_string()]
+    }
+
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+}

+ 1 - 1
bin/daod/src/dao_contract/state.rs

@@ -2,7 +2,7 @@ use pasta_curves::pallas;
 use std::any::{Any, TypeId};
 use std::any::{Any, TypeId};
 
 
 use crate::{
 use crate::{
-    dao_contract::mint::CallData,
+    dao_contract::mint::validate::CallData,
     demo::{StateRegistry, Transaction},
     demo::{StateRegistry, Transaction},
     Result,
     Result,
 };
 };

+ 11 - 90
bin/daod/src/demo.rs

@@ -42,69 +42,6 @@ use darkfi::{
     zkas::decoder::ZkBinary,
     zkas::decoder::ZkBinary,
 };
 };
 
 
-/// The state machine, held in memory.
-struct MemoryState {
-    /// The entire Merkle tree state
-    tree: BridgeTree<MerkleNode, MERKLE_DEPTH>,
-    /// List of all previous and the current Merkle roots.
-    /// This is the hashed value of all the children.
-    merkle_roots: Vec<MerkleNode>,
-    /// Nullifiers prevent double spending
-    nullifiers: Vec<Nullifier>,
-    /// Verifying key for the mint zk circuit.
-    mint_vk: VerifyingKey,
-    /// Verifying key for the burn zk circuit.
-    burn_vk: VerifyingKey,
-
-    /// Public key of the cashier
-    cashier_signature_public: PublicKey,
-
-    /// Public key of the faucet
-    faucet_signature_public: PublicKey,
-}
-
-impl ProgramState for MemoryState {
-    fn is_valid_cashier_public_key(&self, public: &PublicKey) -> bool {
-        public == &self.cashier_signature_public
-    }
-
-    fn is_valid_faucet_public_key(&self, public: &PublicKey) -> bool {
-        public == &self.faucet_signature_public
-    }
-
-    fn is_valid_merkle(&self, merkle_root: &MerkleNode) -> bool {
-        self.merkle_roots.iter().any(|m| m == merkle_root)
-    }
-
-    fn nullifier_exists(&self, nullifier: &Nullifier) -> bool {
-        self.nullifiers.iter().any(|n| n == nullifier)
-    }
-
-    fn mint_vk(&self) -> &VerifyingKey {
-        &self.mint_vk
-    }
-
-    fn burn_vk(&self) -> &VerifyingKey {
-        &self.burn_vk
-    }
-}
-
-impl MemoryState {
-    fn apply(&mut self, mut update: StateUpdate) {
-        // Extend our list of nullifiers with the ones from the update
-        self.nullifiers.append(&mut update.nullifiers);
-
-        // Update merkle tree and witnesses
-        for (coin, enc_note) in update.coins.into_iter().zip(update.enc_notes.into_iter()) {
-            // Add the new coins to the Merkle tree
-            let node = MerkleNode(coin.0);
-            self.tree.append(&node);
-
-            // Keep track of all Merkle roots that have existed
-            self.merkle_roots.push(self.tree.root(0).unwrap());
-        }
-    }
-}
 type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
 type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
 
 
 pub struct ZkContractInfo {
 pub struct ZkContractInfo {
@@ -207,6 +144,7 @@ impl StateRegistry {
     }
     }
 
 
     fn register(&mut self, contract_id: ContractId, state: GenericContractState) {
     fn register(&mut self, contract_id: ContractId, state: GenericContractState) {
+        debug!(target: "StateRegistry::register()", "contract_id: {:?}", contract_id);
         self.states.insert(contract_id, state);
         self.states.insert(contract_id, state);
     }
     }
 
 
@@ -242,31 +180,14 @@ pub async fn demo() -> Result<()> {
     let zk_dao_mint_bin = ZkBinary::decode(zk_dao_mint_bincode)?;
     let zk_dao_mint_bin = ZkBinary::decode(zk_dao_mint_bincode)?;
     zk_bins.add_contract("dao-mint".to_string(), zk_dao_mint_bin, 13);
     zk_bins.add_contract("dao-mint".to_string(), zk_dao_mint_bin, 13);
 
 
-    /*
-    /////////////////////////////////////////////////
-
-    TODO: The following money_contract behaviors are still unimplemented:
-
-    [ ] money_contract/transfer/builder.rs.
-        The mint proof is currently part of its outputs and CallData::proofs is an empty vector.
-    [ ] CallDataBase
-        Not fully implemented for money_contract/mint/mod::CallData.
-
-        all inputs and outputs have proofs. if there are 7 inputs/outputs, there are 7 proofs
-        proofs need to be moved outside of inputs/ouputs and into Vec<Proof>
-
-    [ ] money_contract/state.rs
-        State transition function is totally unimplemented.
-
-    /////////////////////////////////////////////////
-    */
-
     // State for money contracts
     // State for money contracts
     let cashier_signature_secret = SecretKey::random(&mut OsRng);
     let cashier_signature_secret = SecretKey::random(&mut OsRng);
     let cashier_signature_public = PublicKey::from_secret(cashier_signature_secret);
     let cashier_signature_public = PublicKey::from_secret(cashier_signature_secret);
     let faucet_signature_secret = SecretKey::random(&mut OsRng);
     let faucet_signature_secret = SecretKey::random(&mut OsRng);
     let faucet_signature_public = PublicKey::from_secret(faucet_signature_secret);
     let faucet_signature_public = PublicKey::from_secret(faucet_signature_secret);
 
 
+    ///////////////////////////////////////////////////
+
     let start = Instant::now();
     let start = Instant::now();
     let mint_vk = VerifyingKey::build(11, &MintContract::default());
     let mint_vk = VerifyingKey::build(11, &MintContract::default());
     debug!("Mint VK: [{:?}]", start.elapsed());
     debug!("Mint VK: [{:?}]", start.elapsed());
@@ -274,7 +195,7 @@ pub async fn demo() -> Result<()> {
     let burn_vk = VerifyingKey::build(11, &BurnContract::default());
     let burn_vk = VerifyingKey::build(11, &BurnContract::default());
     debug!("Burn VK: [{:?}]", start.elapsed());
     debug!("Burn VK: [{:?}]", start.elapsed());
 
 
-    let money_state = Box::new(MemoryState {
+    let money_state = Box::new(crate::money_contract::state::State {
         tree: BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(100),
         tree: BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(100),
         merkle_roots: vec![],
         merkle_roots: vec![],
         nullifiers: vec![],
         nullifiers: vec![],
@@ -285,7 +206,7 @@ pub async fn demo() -> Result<()> {
     });
     });
     states.register("money_contract".to_string(), money_state);
     states.register("money_contract".to_string(), money_state);
 
 
-    ///////////////////////////////////////////////////
+    /////////////////////////////////////////////////////
 
 
     let dao_state = crate::dao_contract::State::new();
     let dao_state = crate::dao_contract::State::new();
     states.register("dao_contract".to_string(), dao_state);
     states.register("dao_contract".to_string(), dao_state);
@@ -295,9 +216,9 @@ pub async fn demo() -> Result<()> {
         let bulla = pallas::Base::random(&mut OsRng);
         let bulla = pallas::Base::random(&mut OsRng);
     }
     }
 
 
-    ///////////////////////////////////////////////////
-    //// Create the DAO bulla
-    ///////////////////////////////////////////////////
+    /////////////////////////////////////////////////////
+    ////// Create the DAO bulla
+    /////////////////////////////////////////////////////
 
 
     //// Setup the DAO
     //// Setup the DAO
     let dao_keypair = Keypair::random(&mut OsRng);
     let dao_keypair = Keypair::random(&mut OsRng);
@@ -322,8 +243,8 @@ pub async fn demo() -> Result<()> {
         if func_call.func_id == "DAO::mint()" {
         if func_call.func_id == "DAO::mint()" {
             debug!("dao_contract::mint::state_transition()");
             debug!("dao_contract::mint::state_transition()");
 
 
-            let update =
-                crate::dao_contract::mint::validate::state_transition(&states, idx, &tx).unwrap();
+            let update = crate::dao_contract::mint::validate::state_transition(&states, idx, &tx)
+                .expect("dao_contract::mint::validate::state_transition() failed!");
             crate::dao_contract::mint::validate::apply(&mut states, update);
             crate::dao_contract::mint::validate::apply(&mut states, update);
         }
         }
     }
     }
@@ -374,7 +295,7 @@ pub async fn demo() -> Result<()> {
 
 
             let update =
             let update =
                 crate::money_contract::transfer::validate::state_transition(&states, idx, &tx)
                 crate::money_contract::transfer::validate::state_transition(&states, idx, &tx)
-                    .unwrap();
+                    .expect("money_contract::state_transition() failed!");
             crate::money_contract::transfer::validate::apply(&mut states, update);
             crate::money_contract::transfer::validate::apply(&mut states, update);
         }
         }
     }
     }

+ 4 - 4
bin/daod/src/money_contract/state.rs

@@ -18,15 +18,15 @@ pub struct State {
     /// Nullifiers prevent double spending
     /// Nullifiers prevent double spending
     pub nullifiers: Vec<Nullifier>,
     pub nullifiers: Vec<Nullifier>,
     /// Verifying key for the mint zk circuit.
     /// Verifying key for the mint zk circuit.
-    mint_vk: VerifyingKey,
+    pub mint_vk: VerifyingKey,
     /// Verifying key for the burn zk circuit.
     /// Verifying key for the burn zk circuit.
-    burn_vk: VerifyingKey,
+    pub burn_vk: VerifyingKey,
 
 
     /// Public key of the cashier
     /// Public key of the cashier
-    cashier_signature_public: PublicKey,
+    pub cashier_signature_public: PublicKey,
 
 
     /// Public key of the faucet
     /// Public key of the faucet
-    faucet_signature_public: PublicKey,
+    pub faucet_signature_public: PublicKey,
 }
 }
 
 
 impl ProgramState for State {
 impl ProgramState for State {

+ 4 - 2
bin/daod/src/money_contract/transfer/validate.rs

@@ -26,7 +26,7 @@ pub struct Update {
 }
 }
 
 
 pub fn apply(states: &mut StateRegistry, mut update: Update) {
 pub fn apply(states: &mut StateRegistry, mut update: Update) {
-    let state = states.lookup_mut::<State>(&"mint_contract".to_string()).unwrap();
+    let state = states.lookup_mut::<State>(&"money_contract".to_string()).unwrap();
 
 
     // Extend our list of nullifiers with the ones from the update
     // Extend our list of nullifiers with the ones from the update
     state.nullifiers.append(&mut update.nullifiers);
     state.nullifiers.append(&mut update.nullifiers);
@@ -59,7 +59,9 @@ pub fn state_transition(
     // This will be inside wasm so unwrap is fine.
     // This will be inside wasm so unwrap is fine.
     let call_data = call_data.unwrap();
     let call_data = call_data.unwrap();
 
 
-    let state = states.lookup::<State>(&"mint_contract".to_string()).unwrap();
+    let state = states
+        .lookup::<State>(&"money_contract".to_string())
+        .expect("Return type is not of type State");
 
 
     // Code goes here
     // Code goes here
     for (i, input) in call_data.clear_inputs.iter().enumerate() {
     for (i, input) in call_data.clear_inputs.iter().enumerate() {