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

[consensus] fix derived coin cm path,leaf pos, root

mohab metwally 3 лет назад
Родитель
Сommit
27f15c5d44
2 измененных файлов с 24 добавлено и 7 удалено
  1. 12 1
      src/consensus/leadcoin.rs
  2. 12 6
      src/consensus/state.rs

+ 12 - 1
src/consensus/leadcoin.rs

@@ -306,18 +306,29 @@ impl LeadCoin {
 
     /// the new coin to be minted after the current coin is spent
     /// in lottery.
-    pub fn derive_coin(&self) -> LeadCoin {
+    pub fn derive_coin(&self, coin_commitment_tree:  &mut BridgeTree<MerkleNode, MERKLE_DEPTH>) -> LeadCoin {
         info!("LeadCoin::derive_coin()");
         let mut derived = self.clone();
         let rho = self.derived_rho();
         let blind = pallas::Scalar::random(&mut OsRng);
         let cm = self.derived_commitment(blind);
+        let cm_coord = cm.to_affine().coordinates().unwrap();
+        let cm_msg = [*cm_coord.x(), *cm_coord.y()];
+        let cm_base = poseidon_hash(cm_msg);
+        coin_commitment_tree.append(&MerkleNode::from(cm_base));
+        let leaf_pos = coin_commitment_tree.witness().unwrap();
+        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
     }
 

+ 12 - 6
src/consensus/state.rs

@@ -173,6 +173,8 @@ pub struct ValidatorState {
     pub verifying_keys: Arc<RwLock<HashMap<[u8; 32], Vec<(String, VerifyingKey)>>>>,
     /// Wallet interface
     pub wallet: WalletPtr,
+    /// consensuss coin commitment tree
+    pub coin_tree: BridgeTree::<MerkleNode, MERKLE_DEPTH>,
 }
 
 impl ValidatorState {
@@ -281,7 +283,7 @@ impl ValidatorState {
         let mut subscribers = HashMap::new();
         let block_subscriber = Subscriber::new();
         subscribers.insert("blocks", block_subscriber);
-
+        let tree_cm = BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(constants::EPOCH_LENGTH*100);
         let state = Arc::new(RwLock::new(ValidatorState {
             lead_proving_key,
             lead_verifying_key,
@@ -291,6 +293,7 @@ impl ValidatorState {
             subscribers,
             verifying_keys: Arc::new(RwLock::new(verifying_keys)),
             wallet,
+            coin_tree: tree_cm,
         }));
 
         Ok(state)
@@ -464,7 +467,7 @@ impl ValidatorState {
 
     /// Generate epoch-competing coins
     async fn create_epoch_coins(
-        &self,
+        &mut self,
         eta: pallas::Base,
         epoch: u64,
     ) -> Result<Vec<Vec<LeadCoin>>> {
@@ -474,7 +477,7 @@ impl ValidatorState {
 
     /// Generate coins for provided sigmas.
     /// NOTE: The strategy here is having a single competing coin per slot.
-    async fn create_coins(&self, eta: pallas::Base) -> Result<Vec<Vec<LeadCoin>>> {
+    async fn create_coins(&mut self, eta: pallas::Base) -> Result<Vec<Vec<LeadCoin>>> {
         let slot = self.current_slot();
         let mut rng = thread_rng();
 
@@ -485,7 +488,7 @@ impl ValidatorState {
 
         let epoch_secrets = LeadCoinSecrets::generate();
 
-        let mut tree_cm = BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(constants::EPOCH_LENGTH);
+        //let mut tree_cm = BridgeTree::<MerkleNode, MERKLE_DEPTH>::new(constants::EPOCH_LENGTH);
         // LeadCoin matrix where each row represents a slot and contains its competing coins.
         let mut coins: Vec<Vec<LeadCoin>> = Vec::with_capacity(constants::EPOCH_LENGTH);
 
@@ -505,7 +508,7 @@ impl ValidatorState {
                 epoch_secrets.merkle_paths[i],
                 seeds[i],
                 epoch_secrets.secret_keys[i],
-                &mut tree_cm,
+                &mut self.coin_tree,
             );
 
             coins.push(vec![coin]);
@@ -617,6 +620,9 @@ impl ValidatorState {
         let p = self.f_dif();
         let i = self.f_int();
         let d = self.f_der();
+        info!("PID: P: {:?}", p);
+        info!("PID: I: {:?}", i);
+        info!("PID: D: {:?}", d);
         let mut f = self.consensus.kp.clone() *
             (p.clone() +
                 one.clone() / constants::TI.clone() * i.clone() +
@@ -730,7 +736,7 @@ impl ValidatorState {
         // Replacing old coin with the derived coin
         // TODO: do we need that? on next epoch we replace everything
         // how is this going to get reused?
-        self.consensus.coins[relative_slot][idx] = coin.derive_coin();
+        self.consensus.coins[relative_slot][idx] = coin.derive_coin(&mut self.coin_tree);
 
         Ok(Some(BlockProposal::new(header, unproposed_txs, lead_info)))
     }