Skip to main content

consensus_core/
context.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{sync::Arc, time::SystemTime};
5
6use consensus_config::{AuthorityIndex, Committee, ConsensusProtocolConfig, Parameters};
7use consensus_config::{NetworkKeyPair, ProtocolKeyPair};
8use consensus_types::block::BlockTimestampMs;
9use tokio::time::Instant;
10
11use crate::metrics::Metrics;
12use crate::metrics::test_metrics;
13
14/// Context contains per-epoch configuration and metrics shared by all components
15/// of this authority.
16#[derive(Clone)]
17pub struct Context {
18    /// Timestamp of the start of the current epoch.
19    pub epoch_start_timestamp_ms: u64,
20    /// Index of this authority in the committee.
21    pub own_index: AuthorityIndex,
22    /// Committee of the current epoch.
23    pub committee: Committee,
24    /// Parameters of this authority.
25    pub parameters: Parameters,
26    /// Protocol configuration of current epoch.
27    pub protocol_config: ConsensusProtocolConfig,
28    /// Metrics of this authority.
29    pub metrics: Arc<Metrics>,
30    /// Access to local clock
31    pub clock: Arc<Clock>,
32}
33
34impl Context {
35    pub(crate) fn new(
36        epoch_start_timestamp_ms: u64,
37        own_index: Option<AuthorityIndex>,
38        committee: Committee,
39        parameters: Parameters,
40        protocol_config: ConsensusProtocolConfig,
41        metrics: Arc<Metrics>,
42        clock: Arc<Clock>,
43    ) -> Self {
44        let own_index = if let Some(own_index) = own_index {
45            own_index
46        } else {
47            // If no index is provided, then this is an observer node. We assign a max index to it as a special value.
48            AuthorityIndex::MAX
49        };
50
51        Self {
52            epoch_start_timestamp_ms,
53            own_index,
54            committee,
55            parameters,
56            protocol_config,
57            metrics,
58            clock,
59        }
60    }
61
62    /// Create a test context with a committee of given size and even stake
63    pub fn new_for_test(committee_size: usize) -> (Self, Vec<(NetworkKeyPair, ProtocolKeyPair)>) {
64        Self::new_with_test_options(committee_size, true)
65    }
66
67    /// Create a test context with a committee of given size and even stake
68    pub fn new_with_test_options(
69        committee_size: usize,
70        unused_port: bool,
71    ) -> (Self, Vec<(NetworkKeyPair, ProtocolKeyPair)>) {
72        let (committee, keypairs) = consensus_config::local_committee_and_keys_with_test_options(
73            0,
74            vec![1; committee_size],
75            unused_port,
76        );
77        let metrics = test_metrics();
78        let temp_dir = mysten_common::tempdir().unwrap();
79        let clock = Arc::new(Clock::default());
80
81        let context = Context::new(
82            0,
83            Some(AuthorityIndex::new_for_test(0)),
84            committee,
85            Parameters {
86                db_path: temp_dir.keep(),
87                ..Default::default()
88            },
89            ConsensusProtocolConfig::for_testing(),
90            metrics,
91            clock,
92        );
93        (context, keypairs)
94    }
95
96    pub fn with_epoch_start_timestamp_ms(mut self, epoch_start_timestamp_ms: u64) -> Self {
97        self.epoch_start_timestamp_ms = epoch_start_timestamp_ms;
98        self
99    }
100
101    pub fn with_authority_index(mut self, authority: AuthorityIndex) -> Self {
102        self.own_index = authority;
103        self
104    }
105
106    pub fn with_committee(mut self, committee: Committee) -> Self {
107        self.committee = committee;
108        self
109    }
110
111    pub fn with_parameters(mut self, parameters: Parameters) -> Self {
112        self.parameters = parameters;
113        self
114    }
115
116    pub fn with_protocol_config(mut self, protocol_config: ConsensusProtocolConfig) -> Self {
117        self.protocol_config = protocol_config;
118        self
119    }
120
121    /// Returns true if this node is a validator (i.e., part of the committee).
122    pub fn is_validator(&self) -> bool {
123        self.committee.is_valid_index(self.own_index)
124    }
125
126    /// Returns true if this node is an observer (i.e., not part of the committee).
127    pub fn is_observer(&self) -> bool {
128        !self.is_validator()
129    }
130}
131
132/// A clock that allows to derive the current UNIX system timestamp while guaranteeing that timestamp
133/// will be monotonically incremented, tolerating ntp and system clock changes and corrections.
134/// Explicitly avoid to make `[Clock]` cloneable to ensure that a single instance is shared behind an `[Arc]`
135/// wherever is needed in order to make sure that consecutive calls to receive the system timestamp
136/// will remain monotonically increasing.
137pub struct Clock {
138    initial_instant: Instant,
139    initial_system_time: SystemTime,
140    // `clock_drift` should be used only for testing
141    clock_drift: BlockTimestampMs,
142}
143
144impl Default for Clock {
145    fn default() -> Self {
146        Self {
147            initial_instant: Instant::now(),
148            initial_system_time: SystemTime::now(),
149            clock_drift: 0,
150        }
151    }
152}
153
154impl Clock {
155    pub fn new_for_test(clock_drift: BlockTimestampMs) -> Self {
156        Self {
157            initial_instant: Instant::now(),
158            initial_system_time: SystemTime::now(),
159            clock_drift,
160        }
161    }
162
163    // Returns the current time expressed as UNIX timestamp in milliseconds.
164    // Calculated with Tokio Instant to ensure monotonicity,
165    // and to allow testing with tokio clock.
166    pub(crate) fn timestamp_utc_ms(&self) -> BlockTimestampMs {
167        if cfg!(not(any(msim, test))) {
168            assert_eq!(
169                self.clock_drift, 0,
170                "Clock drift should not be set in non testing environments."
171            );
172        }
173
174        let now: Instant = Instant::now();
175        let monotonic_system_time = self
176            .initial_system_time
177            .checked_add(
178                now.checked_duration_since(self.initial_instant)
179                    .unwrap_or_else(|| {
180                        panic!(
181                            "current instant ({:?}) < initial instant ({:?})",
182                            now, self.initial_instant
183                        )
184                    }),
185            )
186            .expect("Computing system time should not overflow");
187        monotonic_system_time
188            .duration_since(SystemTime::UNIX_EPOCH)
189            .unwrap_or_else(|_| {
190                panic!(
191                    "system time ({:?}) < UNIX_EPOCH ({:?})",
192                    monotonic_system_time,
193                    SystemTime::UNIX_EPOCH,
194                )
195            })
196            .as_millis() as BlockTimestampMs
197            + self.clock_drift
198    }
199}