consensus_types/
vote_data.rs

1// Copyright (c) The Diem Core Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4// Copyright 2021 Conflux Foundation. All rights reserved.
5// Conflux is free software and distributed under GNU General Public License.
6// See http://www.gnu.org/licenses/
7
8use diem_crypto_derive::{BCSCryptoHash, CryptoHasher};
9use diem_types::block_info::BlockInfo;
10use serde::{Deserialize, Serialize};
11use std::fmt::{Display, Formatter};
12
13/// VoteData keeps the information about the block, and its parent.
14#[derive(
15    Deserialize,
16    Serialize,
17    Clone,
18    Debug,
19    PartialEq,
20    Eq,
21    CryptoHasher,
22    BCSCryptoHash,
23)]
24pub struct VoteData {
25    /// Contains all the block information needed for voting for the proposed
26    /// round.
27    proposed: BlockInfo,
28    /// Contains all the block information for the block the proposal is
29    /// extending.
30    parent: BlockInfo,
31}
32
33impl Display for VoteData {
34    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
35        write!(
36            f,
37            "VoteData: [block id: {}, epoch: {}, round: {:02}, parent_block_id: {}, parent_block_round: {:02}]",
38            self.proposed().id(), self.proposed().epoch(), self.proposed().round(), self.parent().id(), self.parent().round(),
39        )
40    }
41}
42
43impl VoteData {
44    /// Constructs a new VoteData from the block information of a proposed block
45    /// and the block it extends.
46    pub fn new(proposed: BlockInfo, parent: BlockInfo) -> Self {
47        Self { proposed, parent }
48    }
49
50    /// Returns block information associated to the block being extended by the
51    /// proposal.
52    pub fn parent(&self) -> &BlockInfo { &self.parent }
53
54    /// Returns block information associated to the block being voted on.
55    pub fn proposed(&self) -> &BlockInfo { &self.proposed }
56
57    /// Well-formedness checks that are independent of the current state.
58    pub fn verify(&self) -> anyhow::Result<()> {
59        anyhow::ensure!(
60            self.parent.epoch() == self.proposed.epoch(),
61            "Parent and proposed epochs do not match",
62        );
63        anyhow::ensure!(
64            self.parent.round() < self.proposed.round(),
65            "Proposed round is less than parent round",
66        );
67        anyhow::ensure!(
68            self.parent.timestamp_usecs() <= self.proposed.timestamp_usecs(),
69            "Proposed happened before parent",
70        );
71        anyhow::ensure!(
72            self.parent.version() <= self.proposed.version(),
73            "Proposed version is less than parent version",
74        );
75        Ok(())
76    }
77}