浏览代码

[consensus] clip f value, pruned nonce_cm for lead coin, commented derived coins

mohab metwally 3 年之前
父节点
当前提交
d80d02ff04
共有 5 个文件被更改,包括 67 次插入42 次删除
  1. 4 4
      proof/lead.zk
  2. 3 1
      src/consensus/constants.rs
  3. 33 20
      src/consensus/leadcoin.rs
  4. 27 16
      src/consensus/state.rs
  5. 0 1
      src/consensus/task/proposal.rs

+ 4 - 4
proof/lead.zk

@@ -34,9 +34,7 @@ circuit "Lead" {
 
         # coin (1) pk
         pk = poseidon_hash(PREFIX_PK, c1_sk_root, c1_tau, ZERO);
-        constrain_instance(pk);
-        # coin (2) rho/nonce 
-        c2_rho = poseidon_hash(PREFIX_EVL, c1_sk_root, c1_rho, ZERO);
+        constrain_instance(pk);        
         # coin (1) cm/commitment
         c1_cm_msg = poseidon_hash(PREFIX_CM, pk, value, c1_rho);
         c1_cm_v = ec_mul_base(c1_cm_msg, NULLIFIER_K);
@@ -47,6 +45,8 @@ circuit "Lead" {
         c1_cm_hash = poseidon_hash(c1_cm_x, c1_cm_y);
         constrain_instance(c1_cm_x);
         constrain_instance(c1_cm_y);
+        # coin (2) rho/nonce 
+        c2_rho = poseidon_hash(PREFIX_EVL, c1_sk_root, c1_rho, ZERO);
         # coin (2) cm/commitment
         # reward 
         c2_value = base_add(value, REWARD);
@@ -83,7 +83,7 @@ circuit "Lead" {
         term2 = base_mul(term2_1, value);
         target = base_add(term1, term2);
         #lottery
-        # constrain public value sigma1
+        #constrain public value sigma1
         constrain_instance(sigma1);
         # constrain public value sigma2
         constrain_instance(sigma2);

+ 3 - 1
src/consensus/constants.rs

@@ -46,11 +46,13 @@ lazy_static! {
     pub static ref  TI: Float10 = FLOAT10_ONE.clone();
     pub static ref  TD: Float10 = FLOAT10_ONE.clone();
     pub static ref  KP: Float10 = Float10::from_str_native("0.3").unwrap().with_precision(RADIX_BITS).value();
-    pub static ref  KI: Float10 = Float10::from_str_native("0.1").unwrap().with_precision(RADIX_BITS).value();
+    pub static ref  KI: Float10 = Float10::from_str_native("-0.1").unwrap().with_precision(RADIX_BITS).value();
     pub static ref  KD: Float10 = FLOAT10_ONE.clone();
     pub static ref PID_OUT_STEP: Float10  = Float10::from_str_native("0.1").unwrap().with_precision(RADIX_BITS).value();
     pub static ref MAX_DER: Float10 = Float10::from_str_native("0.3").unwrap().with_precision(RADIX_BITS).value();
     pub static ref MIN_DER: Float10 = Float10::from_str_native("-0.3").unwrap().with_precision(RADIX_BITS).value();
+    pub static ref MAX_F: Float10 = Float10::from_str_native("0.95").unwrap().with_precision(RADIX_BITS).value();
+    pub static ref MIN_F: Float10 = Float10::from_str_native("0.05").unwrap().with_precision(RADIX_BITS).value();
 
 }
 

+ 33 - 20
src/consensus/leadcoin.rs

@@ -59,14 +59,12 @@ pub struct LeadCoin {
     pub coin1_commitment: pallas::Point,
     /// Commitment for coin2 (rcpt coin)
     pub coin2_commitment: pallas::Point,
-    /// Coin index
+    /// Coin sk index
     pub idx: u32,
     /// Coin timestamp as slot index.
     pub tau: pallas::Base,
     /// Coin nonce
     pub nonce: pallas::Base,
-    /// Coin nonce's commitment
-    pub nonce_cm: pallas::Base,
     /// Merkle root of coin1 commitment
     pub coin1_commitment_root: MerkleNode,
     /// coin1 sk
@@ -89,6 +87,8 @@ pub struct LeadCoin {
     pub rho_mu: pallas::Base,
     /// Coin's secret key
     pub secret_key: SecretKey,
+    /// eta
+    pub eta: pallas::Base,
 }
 
 impl LeadCoin {
@@ -155,7 +155,6 @@ impl LeadCoin {
             // Assume tau is sl for simplicity
             tau,
             nonce: pallas::Base::from(seed),
-            nonce_cm: coin2_seed,
             coin1_commitment_root,
             coin1_sk,
             coin1_sk_root,
@@ -167,6 +166,7 @@ impl LeadCoin {
             y_mu,
             rho_mu,
             secret_key,
+            eta,
         }
     }
 
@@ -223,7 +223,7 @@ impl LeadCoin {
         // rho
         let rho_msg = [seed, self.rho_mu];
         let rho = poseidon_hash(rho_msg);
-        vec![
+        let public_inputs = vec![
             pk,
             *c1_cm.x(),
             *c1_cm.y(),
@@ -238,7 +238,8 @@ impl LeadCoin {
             rho,
             sigma1,
             sigma2,
-        ]
+        ];
+        public_inputs
     }
 
     fn util_pk(sk_root: MerkleNode, tau: pallas::Base) -> pallas::Base {
@@ -301,7 +302,7 @@ impl LeadCoin {
     pub fn derived_commitment(&self, blind: pallas::Scalar) -> pallas::Point {
         let pk = self.pk();
         let rho = self.derived_rho();
-        Self::commitment(pk, pallas::Base::from(self.value), rho, blind)
+        Self::commitment(pk, pallas::Base::from(self.value+constants::REWARD.clone()), rho, blind)
     }
 
     /// the new coin to be minted after the current coin is spent
@@ -323,16 +324,27 @@ impl LeadCoin {
         let commitment_root = coin_commitment_tree.root(0).unwrap();
         let commitment_merkle_path =
             coin_commitment_tree.authentication_path(leaf_pos, &commitment_root).unwrap();
-        derived.nonce = rho;
-        derived.coin1_commitment = derived.coin2_commitment;
-        derived.coin2_commitment = cm;
-        derived.coin1_blind = derived.coin2_blind;
-        derived.coin2_blind = blind;
-        derived.value = self.value + constants::REWARD;
-        derived.coin1_commitment_root = commitment_root;
-        derived.coin1_commitment_merkle_path = commitment_merkle_path.try_into().unwrap();
-        derived.idx = u32::try_from(usize::from(leaf_pos)).unwrap();
-        derived
+        LeadCoin {
+            value: self.value + constants::REWARD,
+            coin1_commitment: self.coin2_commitment,
+            coin2_commitment: cm,
+            idx: u32::try_from(usize::from(leaf_pos)).unwrap(),
+            tau: self.tau,
+            nonce: rho,
+            coin1_commitment_root: commitment_root,
+            coin1_sk: self.coin1_sk,
+            coin1_sk_root: self.coin1_sk_root,
+            coin1_sk_pos: self.coin1_sk_pos,
+            coin1_commitment_merkle_path: commitment_merkle_path.try_into().unwrap(),
+            coin1_sk_merkle_path: self.coin1_sk_merkle_path,
+            coin1_blind: self.coin2_blind,
+            coin2_blind: blind,
+            y_mu: self.y_mu,
+            rho_mu: self.rho_mu,
+            secret_key: self.secret_key,
+            eta: self.eta,
+        }
+
     }
 
     /// Try to create a ZK proof of consensus leadership
@@ -341,9 +353,9 @@ impl LeadCoin {
         sigma1: pallas::Base,
         sigma2: pallas::Base,
         pk: &ProvingKey,
-    ) -> Result<Proof> {
+    ) -> (Result<Proof>, Vec<pallas::Base>) {
         let bincode = include_bytes!("../../proof/lead.zk.bin");
-        let zkbin = ZkBinary::decode(bincode)?;
+        let zkbin = ZkBinary::decode(bincode).unwrap();
         let witnesses = vec![
             Witness::MerklePath(Value::known(self.coin1_commitment_merkle_path)),
             Witness::Uint32(Value::known(self.idx)),
@@ -362,7 +374,8 @@ impl LeadCoin {
             Witness::Base(Value::known(sigma2)),
         ];
         let circuit = ZkCircuit::new(witnesses, zkbin.clone());
-        Ok(Proof::create(pk, &[circuit], &self.public_inputs(sigma1, sigma2), &mut OsRng)?)
+        let public_inputs = self.public_inputs(sigma1, sigma2);
+        (Ok(Proof::create(pk, &[circuit], &public_inputs, &mut OsRng).unwrap()), public_inputs)
     }
 
     pub fn create_xfer_proof(

+ 27 - 16
src/consensus/state.rs

@@ -447,8 +447,8 @@ impl ValidatorState {
         if total_stake == 0 {
             total_stake = constants::GENESIS_TOTAL_STAKE;
         }
-        debug!("consensus::sigmas(): f: {}", f);
-        debug!("consensus::sigmas(): stake: {}", total_stake);
+        info!("consensus::sigmas(): f: {}", f);
+        info!("consensus::sigmas(): stake: {}", total_stake);
         let one = constants::FLOAT10_ONE.clone();
         let two = constants::FLOAT10_TWO.clone();
         let field_p = Float10::from_str_native(constants::P)
@@ -652,8 +652,16 @@ impl ValidatorState {
         info!("PID: P: {:?}", p);
         info!("PID: I: {:?}", i);
         info!("PID: D: {:?}", d);
-        let f = Self::pid(p, i, d);
-        info!("Consensus::win_prob_with_full_stake(): last f: {}", f);
+        let mut f = Self::pid(p, i, d);
+        info!("Consensus::win_prob_with_full_stake(): pid f: {}", f);
+        f = if f >= constants::FLOAT10_ONE.clone()  {
+            constants::MAX_F.clone()
+        } else if f <= constants::FLOAT10_ZERO.clone() {
+            constants::MIN_F.clone()
+        } else {
+            f
+        };
+        info!("Consensus::win_prob_with_full_stake(): clipped f: {}", f);
         f
     }
 
@@ -718,12 +726,12 @@ impl ValidatorState {
 
         let root = tree.root(0).unwrap();
 
-        let eta = self.consensus.epoch_eta;
+        //let eta = self.consensus.epoch_eta;
         // Generating leader proof
         let relative_slot = self.relative_slot(slot) as usize;
         let coin = self.consensus.coins[relative_slot][idx];
-        let proof =
-            coin.create_lead_proof(sigma1, sigma2, self.lead_proving_key.as_ref().unwrap())?;
+        let (proof, public_inputs) =
+            coin.create_lead_proof(sigma1, sigma2, self.lead_proving_key.as_ref().unwrap());
 
         // Signing using coin
         let secret_key = coin.secret_key;
@@ -735,14 +743,15 @@ impl ValidatorState {
         let lead_info = LeadInfo::new(
             signed_proposal,
             public_key,
-            coin.public_inputs(sigma1, sigma2),
-            eta.to_repr(),
-            LeadProof::from(proof),
+            //coin.public_inputs(sigma1, sigma2),
+            public_inputs,
+            coin.eta.to_repr(),
+            LeadProof::from(proof?),
             self.get_current_offset(slot),
             self.consensus.leaders_history.last().unwrap().clone(),
         );
         // Replacing old coin with the derived coin
-        self.consensus.coins[relative_slot][idx] = coin.derive_coin(&mut self.consensus.coins_tree);
+        //self.consensus.coins[relative_slot][idx] = coin.derive_coin(&mut self.consensus.coins_tree);
 
         Ok(Some(BlockProposal::new(header, unproposed_txs, lead_info)))
     }
@@ -926,19 +935,21 @@ impl ValidatorState {
     }
         */
         // sn
-        let prop_sn = lf.public_inputs[constants::PI_NULLIFIER_INDEX];
+        //let prop_sn = lf.public_inputs[constants::PI_NULLIFIER_INDEX];
+        /*
         for sn in &self.consensus.leaders_nullifiers {
             if *sn == prop_sn {
                 error!("receive_proposal(): Proposal nullifiers exist.");
                 return Err(Error::ProposalIsSpent)
             }
         }
-
+        */
         // cm
 
+        /*
         let prop_cm_x: pallas::Base = lf.public_inputs[constants::PI_COMMITMENT_X_INDEX];
         let prop_cm_y: pallas::Base = lf.public_inputs[constants::PI_COMMITMENT_Y_INDEX];
-        /*
+
         for cm in &self.consensus.leaders_spent_coins {
             if *cm == (prop_cm_x, prop_cm_y) {
                 error!("receive_proposal(): Proposal coin already spent.");
@@ -975,8 +986,8 @@ impl ValidatorState {
         };
 
         // Store proposal coin info
-        self.consensus.leaders_nullifiers.push(prop_sn);
-        self.consensus.leaders_spent_coins.push((prop_cm_x, prop_cm_y));
+        //self.consensus.leaders_nullifiers.push(prop_sn);
+        //self.consensus.leaders_spent_coins.push((prop_cm_x, prop_cm_y));
 
         Ok(())
     }

+ 0 - 1
src/consensus/task/proposal.rs

@@ -111,7 +111,6 @@ pub async fn proposal_task(consensus_p2p: P2pPtr, sync_p2p: P2pPtr, state: Valid
                 continue
             }
         };
-
         // Node checks if it's the slot leader to generate a new proposal
         // for that slot.
         let (won, idx) = state.write().await.is_slot_leader(sigma1, sigma2);