1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

use consensus_types::{common::Round, safety_data::SafetyData};
use diem_types::waypoint::Waypoint;
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter};

/// Public representation of the internal state of SafetyRules for monitoring / debugging purposes.
/// This does not include sensitive data like private keys.
/// @TODO add hash of ledger info (waypoint)
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct ConsensusState {
    safety_data: SafetyData,
    waypoint: Waypoint,
    in_validator_set: bool,
}

impl Display for ConsensusState {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(
            f,
            "ConsensusState: [\n\
             \tepoch = {},
             \tlast_voted_round = {},\n\
             \tpreferred_round = {}\n\
             \twaypoint = {}\n\
             \tin_validator_set = {}\n\
             ]",
            self.epoch(),
            self.last_voted_round(),
            self.preferred_round(),
            self.waypoint,
            self.in_validator_set,
        )
    }
}

impl ConsensusState {
    pub fn new(safety_data: SafetyData, waypoint: Waypoint, in_validator_set: bool) -> Self {
        Self {
            safety_data,
            waypoint,
            in_validator_set,
        }
    }

    /// Returns the current epoch
    pub fn epoch(&self) -> u64 {
        self.safety_data.epoch
    }

    /// Returns the last round that was voted on
    pub fn last_voted_round(&self) -> Round {
        self.safety_data.last_voted_round
    }

    /// A "preferred block" is the two-chain head with the highest block round. The expectation is
    /// that a new proposal's parent is higher or equal to the preferred_round.
    pub fn preferred_round(&self) -> Round {
        self.safety_data.preferred_round
    }

    /// The round of the highest QuorumCert.
    pub fn one_chain_round(&self) -> Round {
        self.safety_data.one_chain_round
    }

    /// Last known checkpoint this should map to a LedgerInfo that contains a new ValidatorSet
    pub fn waypoint(&self) -> Waypoint {
        self.waypoint
    }

    /// Indicating whether the validator is validator set
    pub fn in_validator_set(&self) -> bool {
        self.in_validator_set
    }

    /// Return a copy of the safety data.
    pub fn safety_data(&mut self) -> SafetyData {
        self.safety_data.clone()
    }
}