safety_rules/
consensus_state.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 consensus_types::{common::Round, safety_data::SafetyData};
9use serde::{Deserialize, Serialize};
10use std::fmt::{Display, Formatter};
11
12/// Public representation of the internal state of SafetyRules for monitoring /
13/// debugging purposes. This does not include sensitive data like private keys.
14#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
15pub struct ConsensusState {
16    safety_data: SafetyData,
17    in_validator_set: bool,
18}
19
20impl Display for ConsensusState {
21    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
22        write!(
23            f,
24            "ConsensusState: [\n\
25             \tepoch = {},
26             \tlast_voted_round = {},\n\
27             \tpreferred_round = {}\n\
28             \tin_validator_set = {}\n\
29             ]",
30            self.epoch(),
31            self.last_voted_round(),
32            self.preferred_round(),
33            self.in_validator_set,
34        )
35    }
36}
37
38impl ConsensusState {
39    pub fn new(safety_data: SafetyData, in_validator_set: bool) -> Self {
40        Self {
41            safety_data,
42            in_validator_set,
43        }
44    }
45
46    /// Returns the current epoch
47    pub fn epoch(&self) -> u64 { self.safety_data.epoch }
48
49    /// Returns the last round that was voted on
50    pub fn last_voted_round(&self) -> Round {
51        self.safety_data.last_voted_round
52    }
53
54    /// A "preferred block" is the two-chain head with the highest block round.
55    /// The expectation is that a new proposal's parent is higher or equal
56    /// to the preferred_round.
57    pub fn preferred_round(&self) -> Round { self.safety_data.preferred_round }
58
59    /// Indicating whether the validator is validator set
60    pub fn in_validator_set(&self) -> bool { self.in_validator_set }
61
62    /// Return a copy of the safety data.
63    pub fn safety_data(&mut self) -> SafetyData { self.safety_data.clone() }
64}