Jelajahi Sumber

consensus: minor fixes, error codes added

aggstam 3 tahun lalu
induk
melakukan
3c28dbcd63
4 mengubah file dengan 33 tambahan dan 40 penghapusan
  1. 3 1
      src/consensus/coins.rs
  2. 14 37
      src/consensus/state.rs
  3. 1 2
      src/consensus/task/consensus_sync.rs
  4. 15 0
      src/error.rs

+ 3 - 1
src/consensus/coins.rs

@@ -39,7 +39,9 @@ fn get_frequency() -> Float10 {
 
 
 /// Calculate nodes total stake for specific epoch and slot.
 /// Calculate nodes total stake for specific epoch and slot.
 fn total_stake(epoch: u64, slot: u64) -> u64 {
 fn total_stake(epoch: u64, slot: u64) -> u64 {
-    (epoch * *EPOCH_LENGTH + slot + 1) * *REWARD
+    // TODO: fix this
+    //(epoch * *EPOCH_LENGTH + slot + 1) * *REWARD
+    *REWARD
 }
 }
 
 
 /// Generate epoch competing coins.
 /// Generate epoch competing coins.

+ 14 - 37
src/consensus/state.rs

@@ -38,7 +38,7 @@ use crate::{
     tx::Transaction,
     tx::Transaction,
     util::time::Timestamp,
     util::time::Timestamp,
     zk::circuit::LeadContract,
     zk::circuit::LeadContract,
-    Result,
+    Error, Result,
 };
 };
 
 
 /// This struct represents the information required by the consensus algorithm
 /// This struct represents the information required by the consensus algorithm
@@ -52,8 +52,6 @@ pub struct ConsensusState {
     pub proposals: Vec<ProposalChain>,
     pub proposals: Vec<ProposalChain>,
     /// Validators currently participating in the consensus
     /// Validators currently participating in the consensus
     pub participants: BTreeMap<Address, Participant>,
     pub participants: BTreeMap<Address, Participant>,
-    /// Validators to be added on the next slot as participants
-    pub pending_participants: Vec<Participant>,
     /// Last slot participants where refreshed
     /// Last slot participants where refreshed
     pub refreshed: u64,
     pub refreshed: u64,
     /// Current epoch
     /// Current epoch
@@ -72,7 +70,6 @@ impl ConsensusState {
             genesis_block,
             genesis_block,
             proposals: vec![],
             proposals: vec![],
             participants: BTreeMap::new(),
             participants: BTreeMap::new(),
-            pending_participants: vec![],
             refreshed: 0,
             refreshed: 0,
             epoch: 0,
             epoch: 0,
             coins: vec![],
             coins: vec![],
@@ -445,28 +442,28 @@ impl ValidatorState {
             }
             }
             None => return Ok(None),
             None => return Ok(None),
         }
         }
-
+        
         let leader = self.consensus.participants.get(&proposal.block.metadata.address);
         let leader = self.consensus.participants.get(&proposal.block.metadata.address);
         if leader.is_none() {
         if leader.is_none() {
             warn!(
             warn!(
                 "receive_proposal(): Received proposal from unknown node: ({})",
                 "receive_proposal(): Received proposal from unknown node: ({})",
                 proposal.block.metadata.address
                 proposal.block.metadata.address
             );
             );
-            return Ok(None)
+            return Err(Error::UnknownNodeError)
         }
         }
         let leader = leader.unwrap();
         let leader = leader.unwrap();
 
 
-        let public_inputs = &leader.coins[current as usize][proposal.block.metadata.winning_index];
+        let public_inputs = &leader.coins[self.relative_slot(current) as usize][proposal.block.metadata.winning_index];
         if public_inputs != &proposal.block.metadata.public_inputs {
         if public_inputs != &proposal.block.metadata.public_inputs {
             warn!("receive_proposal(): Received proposal public inputs are invalid.");
             warn!("receive_proposal(): Received proposal public inputs are invalid.");
-            return Ok(None)
+            return Err(Error::InvalidPublicInputsError)
         }
         }
 
 
         match proposal.block.metadata.proof.verify(&self.verifying_key, &public_inputs) {
         match proposal.block.metadata.proof.verify(&self.verifying_key, &public_inputs) {
             Ok(_) => info!("receive_proposal(): Proof veryfied succsessfully!"),
             Ok(_) => info!("receive_proposal(): Proof veryfied succsessfully!"),
             Err(e) => {
             Err(e) => {
                 error!("receive_proposal(): Error during leader proof verification: {}", e);
                 error!("receive_proposal(): Error during leader proof verification: {}", e);
-                return Ok(None)
+                return Err(Error::LeaderProofVerificationError);
             }
             }
         }
         }
 
 
@@ -478,7 +475,7 @@ impl ValidatorState {
                 "receive_proposal(): Proposer ({}) signature could not be verified",
                 "receive_proposal(): Proposer ({}) signature could not be verified",
                 proposal.block.metadata.address
                 proposal.block.metadata.address
             );
             );
-            return Ok(None)
+            return Err(Error::InvalidSignatureError)
         }
         }
 
 
         debug!("receive_proposal(): Starting state transition validation");
         debug!("receive_proposal(): Starting state transition validation");
@@ -491,7 +488,7 @@ impl ValidatorState {
             }
             }
             Err(e) => {
             Err(e) => {
                 warn!("receive_proposal(): State transition fail: {}", e);
                 warn!("receive_proposal(): State transition fail: {}", e);
-                return Ok(None)
+                return Err(Error::StateTransitionError)
             }
             }
         }
         }
 
 
@@ -661,38 +658,18 @@ impl ValidatorState {
         Ok(finalized)
         Ok(finalized)
     }
     }
 
 
-    /// Append a new participant to the pending participants list.
+    /// Append a new participant to the participants list.
     pub fn append_participant(&mut self, participant: Participant) -> bool {
     pub fn append_participant(&mut self, participant: Participant) -> bool {
-        if self.consensus.pending_participants.contains(&participant) {
-            return false
+        if let Some(p) = self.consensus.participants.get(&participant.address) {
+            if p == &participant {
+                return false
+            }
         }
         }
-
         // TODO: [PLACEHOLDER] don't blintly trust the public inputs/validate them
         // TODO: [PLACEHOLDER] don't blintly trust the public inputs/validate them
-
-        self.consensus.pending_participants.push(participant);
+        self.consensus.participants.insert(participant.address, participant);
         true
         true
     }
     }
 
 
-    /// Utility function to reset the current consensus state.
-    pub fn reset_consensus_state(&mut self) -> Result<()> {
-        let genesis_ts = self.consensus.genesis_ts;
-        let genesis_block = self.consensus.genesis_block;
-
-        let consensus = ConsensusState {
-            genesis_ts,
-            genesis_block,
-            proposals: vec![],
-            participants: BTreeMap::new(),
-            pending_participants: vec![],
-            refreshed: 0,
-            epoch: 0,
-            coins: vec![],
-        };
-
-        self.consensus = consensus;
-        Ok(())
-    }
-
     // ==========================
     // ==========================
     // State transition functions
     // State transition functions
     // ==========================
     // ==========================

+ 1 - 2
src/consensus/task/consensus_sync.rs

@@ -43,8 +43,7 @@ pub async fn consensus_sync_task(p2p: P2pPtr, state: ValidatorStatePtr) -> Resul
             break
             break
         }
         }
     } else {
     } else {
-        warn!("Node is not connected to other nodes, resetting consensus state.");
-        state.write().await.reset_consensus_state()?;
+        warn!("Node is not connected to other nodes");
     }
     }
 
 
     info!("Consensus state synced!");
     info!("Consensus state synced!");

+ 15 - 0
src/error.rs

@@ -192,6 +192,21 @@ pub enum Error {
 
 
     #[error("JSON-RPC error: {0}")]
     #[error("JSON-RPC error: {0}")]
     JsonRpcError(String),
     JsonRpcError(String),
+    
+    #[error("Received proposal from unknown node")]
+    UnknownNodeError,
+    
+    #[error("Public inputs are invalid")]
+    InvalidPublicInputsError,
+    
+    #[error("Error during leader proof verification")]
+    LeaderProofVerificationError,
+    
+    #[error("Signature could not be verified")]
+    InvalidSignatureError,
+    
+    #[error("State transition failed")]
+    StateTransitionError,
 
 
     // ===============
     // ===============
     // Database errors
     // Database errors