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

consensus: renamed block Metadata to LeadInfo

aggstam 3 лет назад
Родитель
Сommit
8fc779782f

+ 10 - 8
doc/src/architecture/blockchain.md

@@ -266,7 +266,7 @@ be used by the protocol.
 |   Field     |        Type        |            Description                     |
 |-------------|--------------------|--------------------------------------------|
 | `version`   | `u8`               | Version                                    |
-| `state`     | `blake3Hash`       | Previous block hash                        |
+| `previous`  | `blake3Hash`       | Previous block hash                        |
 | `epoch`     | `u64`              | Epoch                                      |
 | `slot`      | `u64`              | Slot UID                                   |
 | `timestamp` | `Timestamp`        | Block creation timestamp                   |
@@ -275,14 +275,14 @@ be used by the protocol.
 
 ## Block
 
-|   Field    |        Type       |            Description             |
-|------------|-------------------|------------------------------------|
-| `magic`    | `u8`              | Magic bytes                        |
-| `header`   | `blake3Hash`      | Header hash                        |
-| `txs`      | `Vec<blake3Hash>` | Transaction hashes                 |
-| `metadata` | `Metadata`        | Additional block information       |
+|   Field     |        Type       |            Description             |
+|-------------|-------------------|------------------------------------|
+| `magic`     | `u8`              | Magic bytes                        |
+| `header`    | `blake3Hash`      | Header hash                        |
+| `txs`       | `Vec<blake3Hash>` | Transaction hashes                 |
+| `lead_info` | `LeadInfo`        | Block leader information           |
 
-## Metadata
+## LeadInfo
 
 | Field           | Type                | Description                                         |
 |-----------------|---------------------|-----------------------------------------------------|
@@ -291,3 +291,5 @@ be used by the protocol.
 | `serial_number` | `pallas::Base`      | competing coin's nullifier                          |
 | `eta`           | `[u8; 32]`          | randomness from the previous epoch                  |
 | `proof`         | `Vec<u8>`           | Nizk $\pi$ Proof the stakeholder is the block owner |
+| `offset`        | `u64`               | Slot offset block producer used                     |
+| `leaders`       | `u64`               | Block producer leaders count                        |

+ 3 - 3
src/blockchain/mod.rs

@@ -145,7 +145,7 @@ impl Blockchain {
             let txs = self.transactions.get(&block.txs, true)?;
             let txs = txs.iter().map(|x| x.clone().unwrap()).collect();
 
-            let info = BlockInfo::new(header, txs, block.metadata.clone());
+            let info = BlockInfo::new(header, txs, block.lead_info.clone());
             ret.push(info);
         }
 
@@ -188,7 +188,7 @@ impl Blockchain {
         let blocks = self.blocks.get(&[hash], true)?;
         // Since we used strict get, its safe to unwrap here
         let block = blocks[0].clone().unwrap();
-        let hash = blake3::hash(&serialize(&block.metadata.proof));
+        let hash = blake3::hash(&serialize(&block.lead_info.proof));
         Ok(hash)
     }
 
@@ -198,6 +198,6 @@ impl Blockchain {
         let blocks = self.blocks.get(&[hash], true)?;
         // Since we used strict get, its safe to unwrap here
         let block = blocks[0].clone().unwrap();
-        Ok(block.metadata.offset)
+        Ok(block.lead_info.offset)
     }
 }

+ 17 - 17
src/consensus/block.rs

@@ -26,7 +26,7 @@ use pasta_curves::pallas;
 
 use super::{
     constants::{BLOCK_MAGIC_BYTES, BLOCK_VERSION},
-    Metadata,
+    LeadInfo,
 };
 use crate::{net, tx::Transaction, util::time::Timestamp};
 
@@ -85,7 +85,7 @@ impl Default for Header {
     }
 }
 
-/// This struct represents a tuple of the form (`magic`, `header`, `counter`, `txs`, `metadata`).
+/// This struct represents a tuple of the form (`magic`, `header`, `counter`, `txs`, `lead_info`).
 /// The header and transactions are stored as hashes, serving as pointers to
 /// the actual data in the sled database.
 #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
@@ -96,8 +96,8 @@ pub struct Block {
     pub header: blake3::Hash,
     /// Trasaction hashes
     pub txs: Vec<blake3::Hash>,
-    /// Metadata
-    pub metadata: Metadata,
+    /// Lead Info
+    pub lead_info: LeadInfo,
 }
 
 impl net::Message for Block {
@@ -113,13 +113,13 @@ impl Block {
         slot: u64,
         txs: Vec<blake3::Hash>,
         root: MerkleNode,
-        metadata: Metadata,
+        lead_info: LeadInfo,
     ) -> Self {
         let magic = BLOCK_MAGIC_BYTES;
         let timestamp = Timestamp::current_time();
         let header = Header::new(previous, epoch, slot, timestamp, root);
         let header = header.headerhash();
-        Self { magic, header, txs, metadata }
+        Self { magic, header, txs, lead_info }
     }
 
     /// Generate the genesis block.
@@ -127,8 +127,8 @@ impl Block {
         let magic = BLOCK_MAGIC_BYTES;
         let header = Header::genesis_header(genesis_ts, genesis_data);
         let header = header.headerhash();
-        let metadata = Metadata::default();
-        Self { magic, header, txs: vec![], metadata }
+        let lead_info = LeadInfo::default();
+        Self { magic, header, txs: vec![], lead_info }
     }
 
     /// Calculate the block hash
@@ -161,14 +161,14 @@ pub struct BlockInfo {
     pub header: Header,
     /// Transactions payload
     pub txs: Vec<Transaction>,
-    /// Metadata,
-    pub metadata: Metadata,
+    /// Lead Info,
+    pub lead_info: LeadInfo,
 }
 
 impl Default for BlockInfo {
     fn default() -> Self {
         let magic = BLOCK_MAGIC_BYTES;
-        Self { magic, header: Header::default(), txs: vec![], metadata: Metadata::default() }
+        Self { magic, header: Header::default(), txs: vec![], lead_info: LeadInfo::default() }
     }
 }
 
@@ -179,9 +179,9 @@ impl net::Message for BlockInfo {
 }
 
 impl BlockInfo {
-    pub fn new(header: Header, txs: Vec<Transaction>, metadata: Metadata) -> Self {
+    pub fn new(header: Header, txs: Vec<Transaction>, lead_info: LeadInfo) -> Self {
         let magic = BLOCK_MAGIC_BYTES;
-        Self { magic, header, txs, metadata }
+        Self { magic, header, txs, lead_info }
     }
 
     /// Calculate the block hash
@@ -198,7 +198,7 @@ impl From<BlockInfo> for Block {
             magic: block_info.magic,
             header: block_info.header.headerhash(),
             txs,
-            metadata: block_info.metadata,
+            lead_info: block_info.lead_info,
         }
     }
 }
@@ -229,8 +229,8 @@ pub struct BlockProposal {
 
 impl BlockProposal {
     #[allow(clippy::too_many_arguments)]
-    pub fn new(header: Header, txs: Vec<Transaction>, metadata: Metadata) -> Self {
-        let block = BlockInfo::new(header, txs, metadata);
+    pub fn new(header: Header, txs: Vec<Transaction>, lead_info: LeadInfo) -> Self {
+        let block = BlockInfo::new(header, txs, lead_info);
         let hash = block.blockhash();
         let header = block.header.headerhash();
         Self { hash, header, block }
@@ -250,7 +250,7 @@ impl fmt::Display for BlockProposal {
     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
         formatter.write_fmt(format_args!(
             "BlockProposal {{ leader public key: {}, hash: {}, header: {}, epoch: {}, slot: {}, txs: {} }}",
-            self.block.metadata.public_key,
+            self.block.lead_info.public_key,
             self.hash,
             self.header,
             self.block.header.epoch,

+ 12 - 10
src/consensus/metadata.rs → src/consensus/lead_info.rs

@@ -28,27 +28,29 @@ use crate::{
     Result,
 };
 
-/// This struct represents [`Block`](super::Block) information used by the consensus protocol.
+// TODO: Replace 'Lead' terms with 'Producer' to make it more clear that
+// we refer to block producer.
+/// This struct represents [`Block`](super::Block) leader information used by the consensus protocol.
 #[derive(Debug, Clone, PartialEq, Eq, SerialEncodable, SerialDecodable)]
-pub struct Metadata {
-    /// Block owner signature
+pub struct LeadInfo {
+    /// Block producer signature
     pub signature: Signature,
-    /// Block owner public_key
+    /// Block producer public_key
     pub public_key: PublicKey, // TODO: remove this(to be derived by proof)
-    /// Block owner slot competing coins public inputs
+    /// Block producer slot competing coins public inputs
     pub public_inputs: Vec<pallas::Base>,
     /// Response of global random oracle, or it's emulation.
     pub eta: [u8; 32],
     /// Leader NIZK proof
     pub proof: LeadProof,
-    /// Slot offset block owner used
+    /// Slot offset block producer used
     pub offset: u64,
-    /// Block owner leaders count
+    /// Block producer leaders count
     pub leaders: u64,
 }
 
-impl Default for Metadata {
-    /// Default Metadata used in genesis block generation
+impl Default for LeadInfo {
+    /// Default LeadInfo used in genesis block generation
     fn default() -> Self {
         let keypair = Keypair::default();
         let signature = Signature::dummy();
@@ -61,7 +63,7 @@ impl Default for Metadata {
     }
 }
 
-impl Metadata {
+impl LeadInfo {
     pub fn new(
         signature: Signature,
         public_key: PublicKey,

+ 3 - 3
src/consensus/mod.rs

@@ -23,9 +23,9 @@ pub use block::{Block, BlockInfo, BlockProposal, Header, ProposalChain};
 /// Constants
 pub mod constants;
 
-/// Consensus metadata
-pub mod metadata;
-pub use metadata::{LeadProof, Metadata};
+/// Consensus block leader information
+pub mod lead_info;
+pub use lead_info::{LeadInfo, LeadProof};
 
 /// Consensus state
 pub mod state;

+ 16 - 16
src/consensus/state.rs

@@ -43,7 +43,7 @@ use super::{
     },
     leadcoin::{LeadCoin, LeadCoinSecrets},
     utils::fbig2base,
-    Block, BlockInfo, BlockProposal, Float10, Header, LeadProof, Metadata, ProposalChain,
+    Block, BlockInfo, BlockProposal, Float10, Header, LeadInfo, LeadProof, ProposalChain,
 };
 
 use crate::{
@@ -698,7 +698,7 @@ impl ValidatorState {
         let signed_proposal = secret_key.sign(&mut OsRng, &header.headerhash().as_bytes()[..]);
         let public_key = PublicKey::from_secret(secret_key);
 
-        let metadata = Metadata::new(
+        let lead_info = LeadInfo::new(
             signed_proposal,
             public_key,
             coin.public_inputs(),
@@ -712,7 +712,7 @@ impl ValidatorState {
         // how is this going to get reused?
         self.consensus.coins[relative_slot][idx] = coin.derive_coin(eta, relative_slot as u64);
 
-        Ok(Some(BlockProposal::new(header, unproposed_txs, metadata)))
+        Ok(Some(BlockProposal::new(header, unproposed_txs, lead_info)))
     }
 
     /// Retrieve all unconfirmed transactions not proposed in previous blocks
@@ -788,13 +788,13 @@ impl ValidatorState {
             return Err(Error::ProposalAfterFinalizationError)
         }
 
-        let md = &proposal.block.metadata;
+        let lf = &proposal.block.lead_info;
         let hdr = &proposal.block.header;
 
         // Verify proposal signature is valid based on producer public key
         // TODO: derive public key from proof
-        if !md.public_key.verify(proposal.header.as_bytes(), &md.signature) {
-            warn!("receive_proposal(): Proposer {} signature could not be verified", md.public_key);
+        if !lf.public_key.verify(proposal.header.as_bytes(), &lf.signature) {
+            warn!("receive_proposal(): Proposer {} signature could not be verified", lf.public_key);
             return Err(Error::InvalidSignature)
         }
 
@@ -820,16 +820,16 @@ impl ValidatorState {
 
         // Verify proposal offset
         let offset = self.get_current_offset();
-        if offset != md.offset {
+        if offset != lf.offset {
             warn!(
                 "receive_proposal(): Received proposal contains different offset: {} - {}",
-                offset, md.offset
+                offset, lf.offset
             );
             return Err(Error::ProposalDifferentOffsetError)
         }
 
         // Verify proposal leader proof
-        if let Err(e) = md.proof.verify(&self.lead_verifying_key, &md.public_inputs) {
+        if let Err(e) = lf.proof.verify(&self.lead_verifying_key, &lf.public_inputs) {
             error!("receive_proposal(): Error during leader proof verification: {}", e);
             return Err(Error::LeaderProofVerification)
         };
@@ -838,28 +838,28 @@ impl ValidatorState {
         // verify proposal public values
         // mu values
         // y
-        let prop_mu_y = md.public_inputs[PI_MU_Y_INDEX];
+        let prop_mu_y = lf.public_inputs[PI_MU_Y_INDEX];
         if mu_y != prop_mu_y {
             error!("failed to verify mu_y: {:?}, proposed: {:?}", mu_y, prop_mu_y);
             return Err(Error::ProposalPublicValuesMismatched)
         }
         // rho
-        let prop_mu_rho = md.public_inputs[PI_MU_RHO_INDEX];
+        let prop_mu_rho = lf.public_inputs[PI_MU_RHO_INDEX];
         if mu_rho != prop_mu_rho {
             error!("failed to verify mu_rho: {:?}, proposed: {:?}", mu_rho, prop_mu_rho);
             return Err(Error::ProposalPublicValuesMismatched)
         }
 
         // Verify proposal public inputs
-        let prop_sn = md.public_inputs[PI_NULLIFIER_INDEX];
+        let prop_sn = lf.public_inputs[PI_NULLIFIER_INDEX];
         for sn in &self.leaders_nullifiers {
             if *sn == prop_sn {
                 error!("receive_proposal(): Proposal nullifiers exist.");
                 return Err(Error::ProposalIsSpent)
             }
         }
-        let prop_cm_x: pallas::Base = md.public_inputs[PI_COMMITMENT_X_INDEX];
-        let prop_cm_y: pallas::Base = md.public_inputs[PI_COMMITMENT_Y_INDEX];
+        let prop_cm_x: pallas::Base = lf.public_inputs[PI_COMMITMENT_X_INDEX];
+        let prop_cm_y: pallas::Base = lf.public_inputs[PI_COMMITMENT_Y_INDEX];
 
         for cm in &self.leaders_spent_coins {
             if *cm == (prop_cm_x, prop_cm_y) {
@@ -989,7 +989,7 @@ impl ValidatorState {
                 if last_proposal.block.header.slot == self.current_slot() {
                     // Replacing our last history element with the leaders one
                     self.leaders_history.pop();
-                    self.leaders_history.push(last_proposal.block.metadata.leaders);
+                    self.leaders_history.push(last_proposal.block.lead_info.leaders);
                     debug!("set_leader_history(): New leaders history: {:?}", self.leaders_history);
                     return
                 }
@@ -1093,7 +1093,7 @@ impl ValidatorState {
         }
 
         // Setting leaders history to last proposal leaders count
-        self.leaders_history = vec![chain.proposals.last().unwrap().block.metadata.leaders];
+        self.leaders_history = vec![chain.proposals.last().unwrap().block.lead_info.leaders];
 
         // Removing rest forks
         self.consensus.proposals = vec![];

+ 0 - 3
src/error.rs

@@ -281,9 +281,6 @@ pub enum Error {
     #[error("Block in slot {0} not found in database")]
     SlotNotFound(u64),
 
-    #[error("Block {0} metadata not found in database")]
-    BlockMetadataNotFound(String),
-
     #[error("Contract {0} not found in database")]
     ContractNotFound(String),