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