Sfoglia il codice sorgente

consensus: simplyfied total stake calculation and removed slot offset logic

aggstam 3 anni fa
parent
commit
3f6fc0d7af

+ 0 - 9
src/blockchain/mod.rs

@@ -214,15 +214,6 @@ impl Blockchain {
         Ok(hash)
         Ok(hash)
     }
     }
 
 
-    /// Retrieve last finalized block slot offset
-    pub fn get_last_offset(&self) -> Result<(u64, u64)> {
-        let (slot, hash) = self.last().unwrap();
-        let blocks = self.blocks.get(&[hash], true)?;
-        // Since we used strict get, its safe to unwrap here
-        let block = blocks[0].clone().unwrap();
-        Ok((slot, block.lead_info.offset))
-    }
-
     /// Retrieve the last slot checkpoint.
     /// Retrieve the last slot checkpoint.
     pub fn last_slot_checkpoint(&self) -> Result<SlotCheckpoint> {
     pub fn last_slot_checkpoint(&self) -> Result<SlotCheckpoint> {
         self.slot_checkpoints.get_last()
         self.slot_checkpoints.get_last()

+ 1 - 6
src/consensus/lead_info.rs

@@ -45,8 +45,6 @@ pub struct LeadInfo {
     pub coin_eta: pallas::Base,
     pub coin_eta: pallas::Base,
     /// Leader NIZK proof
     /// Leader NIZK proof
     pub proof: LeadProof,
     pub proof: LeadProof,
-    /// Slot offset block producer used
-    pub offset: u64,
     /// Block producer leaders count
     /// Block producer leaders count
     pub leaders: u64,
     pub leaders: u64,
 }
 }
@@ -60,7 +58,6 @@ impl Default for LeadInfo {
         let coin_slot = 0;
         let coin_slot = 0;
         let coin_eta = pallas::Base::zero();
         let coin_eta = pallas::Base::zero();
         let proof = LeadProof::default();
         let proof = LeadProof::default();
-        let offset = 0;
         let leaders = 0;
         let leaders = 0;
         Self {
         Self {
             signature,
             signature,
@@ -69,7 +66,6 @@ impl Default for LeadInfo {
             coin_slot,
             coin_slot,
             coin_eta,
             coin_eta,
             proof,
             proof,
-            offset,
             leaders,
             leaders,
         }
         }
     }
     }
@@ -84,10 +80,9 @@ impl LeadInfo {
         coin_slot: u64,
         coin_slot: u64,
         coin_eta: pallas::Base,
         coin_eta: pallas::Base,
         proof: LeadProof,
         proof: LeadProof,
-        offset: u64,
         leaders: u64,
         leaders: u64,
     ) -> Self {
     ) -> Self {
-        Self { signature, public_key, public_inputs, coin_slot, coin_eta, proof, offset, leaders }
+        Self { signature, public_key, public_inputs, coin_slot, coin_eta, proof, leaders }
     }
     }
 }
 }
 
 

+ 0 - 2
src/consensus/proto/protocol_sync_consensus.rs

@@ -94,7 +94,6 @@ impl ProtocolSyncConsensus {
             // Extra validations can be added here.
             // Extra validations can be added here.
             let lock = self.state.read().await;
             let lock = self.state.read().await;
             let bootstrap_slot = lock.consensus.bootstrap_slot;
             let bootstrap_slot = lock.consensus.bootstrap_slot;
-            let offset = lock.consensus.offset;
             let mut forks = vec![];
             let mut forks = vec![];
             for fork in &lock.consensus.forks {
             for fork in &lock.consensus.forks {
                 forks.push(fork.clone().into());
                 forks.push(fork.clone().into());
@@ -105,7 +104,6 @@ impl ProtocolSyncConsensus {
             let nullifiers = lock.consensus.nullifiers.clone();
             let nullifiers = lock.consensus.nullifiers.clone();
             let response = ConsensusResponse {
             let response = ConsensusResponse {
                 bootstrap_slot,
                 bootstrap_slot,
-                offset,
                 forks,
                 forks,
                 unconfirmed_txs,
                 unconfirmed_txs,
                 slot_checkpoints,
                 slot_checkpoints,

+ 9 - 41
src/consensus/state.rs

@@ -61,8 +61,6 @@ pub struct ConsensusState {
     pub proposing: bool,
     pub proposing: bool,
     /// Last slot node check for finalization
     /// Last slot node check for finalization
     pub checked_finalization: u64,
     pub checked_finalization: u64,
-    /// Slots offset since genesis,
-    pub offset: Option<u64>,
     /// Fork chains containing block proposals
     /// Fork chains containing block proposals
     pub forks: Vec<Fork>,
     pub forks: Vec<Fork>,
     /// Current epoch
     /// Current epoch
@@ -105,7 +103,6 @@ impl ConsensusState {
             participating: None,
             participating: None,
             proposing: false,
             proposing: false,
             checked_finalization: 0,
             checked_finalization: 0,
-            offset: None,
             forks: vec![],
             forks: vec![],
             epoch: 0,
             epoch: 0,
             epoch_eta: pallas::Base::zero(),
             epoch_eta: pallas::Base::zero(),
@@ -328,50 +325,24 @@ impl ConsensusState {
         constants::REWARD
         constants::REWARD
     }
     }
 
 
-    /// Auxillary function to receive current slot offset.
-    /// If offset is None, its setted up as last block slot offset.
-    pub fn get_current_offset(&mut self, current_slot: u64) -> u64 {
-        // This is the case were we restarted our node, didn't receive offset from other nodes,
-        // so we need to find offset from last block, exluding network dead period.
-        if self.offset.is_none() {
-            let (last_slot, last_offset) = self.blockchain.get_last_offset().unwrap();
-            let offset = last_offset + (current_slot - last_slot);
-            info!(target: "consensus::state", "get_current_offset(): Setting slot offset: {}", offset);
-            self.offset = Some(offset);
-        }
-
-        self.offset.unwrap()
-    }
-
-    /// Auxillary function to calculate overall empty slots.
-    /// We keep an offset from genesis indicating when the first slot actually started.
-    /// This offset is shared between nodes.
-    fn overall_empty_slots(&mut self, current_slot: u64) -> u64 {
+    /// Auxillary function to calculate total slot rewards.
+    fn slot_rewards(&self) -> u64 {
         // Retrieve existing blocks excluding genesis
         // Retrieve existing blocks excluding genesis
         let blocks = (self.blockchain.len() as u64) - 1;
         let blocks = (self.blockchain.len() as u64) - 1;
-        // Setup offset if only have genesis and havent received offset from other nodes
-        if blocks == 0 && self.offset.is_none() {
-            info!(
-                target: "consensus::state",
-                "overall_empty_slots(): Blockchain contains only genesis, setting slot offset: {}",
-                current_slot
-            );
-            self.offset = Some(current_slot);
-        }
-        // Retrieve longest fork length, to also those proposals in the calculation
+        // Retrieve longest fork length, to include those proposals in the calculation
         let max_fork_length = self.longest_chain_length() as u64;
         let max_fork_length = self.longest_chain_length() as u64;
-        current_slot - blocks - self.get_current_offset(current_slot) - max_fork_length
+        // Calculate rewarded slots
+        let rewarded_slots = blocks + max_fork_length;
+
+        rewarded_slots * self.reward()
     }
     }
 
 
     /// Network total stake, assuming constant reward.
     /// Network total stake, assuming constant reward.
     /// Only used for fine-tuning. At genesis epoch first slot, of absolute index 0,
     /// Only used for fine-tuning. At genesis epoch first slot, of absolute index 0,
     /// if no stake was distributed, the total stake would be 0.
     /// if no stake was distributed, the total stake would be 0.
     /// To avoid division by zero, we asume total stake at first division is GENESIS_TOTAL_STAKE(1).
     /// To avoid division by zero, we asume total stake at first division is GENESIS_TOTAL_STAKE(1).
-    fn total_stake(&mut self) -> u64 {
-        let current_slot = self.current_slot();
-        let rewarded_slots = current_slot - self.overall_empty_slots(current_slot) - 1;
-        let rewards = rewarded_slots * self.reward();
-        let total_stake = rewards + self.initial_distribution;
+    fn total_stake(&self) -> u64 {
+        let total_stake = self.slot_rewards() + self.initial_distribution;
         if total_stake == 0 {
         if total_stake == 0 {
             return constants::GENESIS_TOTAL_STAKE
             return constants::GENESIS_TOTAL_STAKE
         }
         }
@@ -672,7 +643,6 @@ impl ConsensusState {
     pub fn reset(&mut self) {
     pub fn reset(&mut self) {
         self.participating = None;
         self.participating = None;
         self.proposing = false;
         self.proposing = false;
-        self.offset = None;
         self.forks = vec![];
         self.forks = vec![];
         self.slot_checkpoints = vec![];
         self.slot_checkpoints = vec![];
         self.leaders_history = vec![0];
         self.leaders_history = vec![0];
@@ -695,8 +665,6 @@ impl net::Message for ConsensusRequest {
 pub struct ConsensusResponse {
 pub struct ConsensusResponse {
     /// Slot the network was bootstrapped
     /// Slot the network was bootstrapped
     pub bootstrap_slot: u64,
     pub bootstrap_slot: u64,
-    /// Slots offset since genesis,
-    pub offset: Option<u64>,
     /// Hot/live data used by the consensus algorithm
     /// Hot/live data used by the consensus algorithm
     pub forks: Vec<ForkInfo>,
     pub forks: Vec<ForkInfo>,
     /// Pending transactions
     /// Pending transactions

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

@@ -136,7 +136,6 @@ pub async fn consensus_sync_task(p2p: P2pPtr, state: ValidatorStatePtr) -> Resul
 
 
     // Node stores response data.
     // Node stores response data.
     let mut lock = state.write().await;
     let mut lock = state.write().await;
-    lock.consensus.offset = response.offset;
     let mut forks = vec![];
     let mut forks = vec![];
     for fork in &response.forks {
     for fork in &response.forks {
         forks.push(fork.clone().into());
         forks.push(fork.clone().into());

+ 0 - 12
src/consensus/validator.rs

@@ -321,7 +321,6 @@ impl ValidatorState {
             coin.slot,
             coin.slot,
             eta,
             eta,
             LeadProof::from(proof?),
             LeadProof::from(proof?),
-            self.consensus.get_current_offset(slot),
             *self.consensus.leaders_history.last().unwrap(),
             *self.consensus.leaders_history.last().unwrap(),
         );
         );
 
 
@@ -457,17 +456,6 @@ impl ValidatorState {
             return Err(Error::ProposalHeadersMissmatchError)
             return Err(Error::ProposalHeadersMissmatchError)
         }
         }
 
 
-        // Verify proposal offset
-        let offset = self.consensus.get_current_offset(current);
-        if offset != lf.offset {
-            warn!(
-                target: "consensus::validator",
-                "receive_proposal(): Received proposal contains different offset: {} - {}",
-                offset, lf.offset
-            );
-            return Err(Error::ProposalDifferentOffsetError)
-        }
-
         // Verify proposal leader proof
         // Verify proposal leader proof
         if let Err(e) = lf.proof.verify(&self.lead_verifying_key, &lf.public_inputs) {
         if let Err(e) = lf.proof.verify(&self.lead_verifying_key, &lf.public_inputs) {
             error!(target: "consensus::validator", "receive_proposal(): Error during leader proof verification: {}", e);
             error!(target: "consensus::validator", "receive_proposal(): Error during leader proof verification: {}", e);

+ 0 - 3
src/error.rs

@@ -254,9 +254,6 @@ pub enum Error {
     #[error("Proposal contains missmatched headers")]
     #[error("Proposal contains missmatched headers")]
     ProposalHeadersMissmatchError,
     ProposalHeadersMissmatchError,
 
 
-    #[error("Proposal contains different offset")]
-    ProposalDifferentOffsetError,
-
     #[error("Proposal contains different coin creation eta")]
     #[error("Proposal contains different coin creation eta")]
     ProposalDifferentCoinEtaError,
     ProposalDifferentCoinEtaError,