consensus_config/
parameters.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{path::PathBuf, time::Duration};
5
6use mysten_network::Multiaddr;
7use serde::{Deserialize, Serialize};
8
9use crate::NetworkPublicKey;
10
11/// Operational configurations of a consensus authority.
12///
13/// All fields should tolerate inconsistencies among authorities, without affecting safety of the
14/// protocol. Otherwise, they need to be part of Sui protocol config or epoch state on-chain.
15///
16/// NOTE: fields with default values are specified in the serde default functions. Most operators
17/// should not need to specify any field, except db_path.
18#[derive(Clone, Debug, Deserialize, Serialize)]
19pub struct Parameters {
20    /// Path to consensus DB for this epoch. Required when initializing consensus.
21    /// This is calculated based on user configuration for base directory.
22    #[serde(skip)]
23    pub db_path: PathBuf,
24
25    /// Time to wait for parent round leader before sealing a block, from when parent round
26    /// has a quorum.
27    #[serde(default = "Parameters::default_leader_timeout")]
28    pub leader_timeout: Duration,
29
30    /// Minimum delay between rounds, to avoid generating too many rounds when latency is low.
31    /// This is especially necessary for tests running locally.
32    /// If setting a non-default value, it should be set low enough to avoid reducing
33    /// round rate and increasing latency in realistic and distributed configurations.
34    #[serde(default = "Parameters::default_min_round_delay")]
35    pub min_round_delay: Duration,
36
37    /// Maximum forward time drift (how far in future) allowed for received blocks.
38    #[serde(default = "Parameters::default_max_forward_time_drift")]
39    pub max_forward_time_drift: Duration,
40
41    /// Max number of blocks to fetch per block sync request.
42    /// Block sync requests have very short (~2s) timeouts.
43    /// So this value should be limited to allow the requests
44    /// to finish on hosts with good network with this timeout.
45    /// Usually a host sends 14-16 blocks per sec to a peer, so
46    /// sending 32 blocks in 2 seconds should be reasonable.
47    #[serde(default = "Parameters::default_max_blocks_per_sync")]
48    pub max_blocks_per_sync: usize,
49
50    /// Max number of blocks to fetch per commit sync request.
51    #[serde(default = "Parameters::default_max_blocks_per_fetch")]
52    pub max_blocks_per_fetch: usize,
53
54    /// Time to wait during node start up until the node has synced the last proposed block via the
55    /// network peers. When set to `0` the sync mechanism is disabled. This property is meant to be
56    /// used for amnesia recovery.
57    #[serde(default = "Parameters::default_sync_last_known_own_block_timeout")]
58    pub sync_last_known_own_block_timeout: Duration,
59
60    /// Interval in milliseconds to probe highest received rounds of peers.
61    #[serde(default = "Parameters::default_round_prober_interval_ms")]
62    pub round_prober_interval_ms: u64,
63
64    /// Timeout in milliseconds for a round prober request.
65    #[serde(default = "Parameters::default_round_prober_request_timeout_ms")]
66    pub round_prober_request_timeout_ms: u64,
67
68    /// Proposing new block is stopped when the propagation delay is greater than this threshold.
69    /// Propagation delay is the difference between the round of the last proposed block and the
70    /// the highest round from this authority that is received by all validators in a quorum.
71    #[serde(default = "Parameters::default_propagation_delay_stop_proposal_threshold")]
72    pub propagation_delay_stop_proposal_threshold: u32,
73
74    /// The number of rounds of blocks to be kept in the Dag state cache per authority. The larger
75    /// the number the more the blocks that will be kept in memory allowing minimising any potential
76    /// disk access.
77    /// Value should be at minimum 50 rounds to ensure node performance, but being too large can be
78    /// expensive in memory usage.
79    #[serde(default = "Parameters::default_dag_state_cached_rounds")]
80    pub dag_state_cached_rounds: u32,
81
82    // Number of authorities commit syncer fetches in parallel.
83    // Both commits in a range and blocks referenced by the commits are fetched per authority.
84    #[serde(default = "Parameters::default_commit_sync_parallel_fetches")]
85    pub commit_sync_parallel_fetches: usize,
86
87    // Number of commits to fetch in a batch, also the maximum number of commits returned per fetch.
88    // If this value is set too small, fetching becomes inefficient.
89    // If this value is set too large, it can result in load imbalance and stragglers.
90    #[serde(default = "Parameters::default_commit_sync_batch_size")]
91    pub commit_sync_batch_size: u32,
92
93    // This affects the maximum number of commit batches being fetched, and those fetched but not
94    // processed as consensus output, before throttling of outgoing commit fetches starts.
95    #[serde(default = "Parameters::default_commit_sync_batches_ahead")]
96    pub commit_sync_batches_ahead: usize,
97
98    // Base per-request timeout for commit sync fetches. The actual timeout grows progressively
99    // with a multiplier to allow larger commit batches to finish downloading.
100    #[serde(default = "Parameters::default_commit_sync_request_timeout")]
101    pub commit_sync_request_timeout: Duration,
102
103    // Timeout for the connectivity probe against a peer before committing to a full fetch.
104    // Should be short to quickly skip unreachable peers.
105    #[serde(default = "Parameters::default_commit_sync_probe_timeout")]
106    pub commit_sync_probe_timeout: Duration,
107
108    /// Whether to use FIFO compaction for RocksDB.
109    #[serde(default = "Parameters::default_use_fifo_compaction")]
110    pub use_fifo_compaction: bool,
111
112    /// Tonic network settings.
113    #[serde(default = "TonicParameters::default")]
114    pub tonic: TonicParameters,
115
116    /// Internal consensus parameters.
117    #[serde(default = "InternalParameters::default")]
118    pub internal: InternalParameters,
119
120    /// Override for the address to listen on. When set, this is used instead of
121    /// deriving from the committee address.
122    #[serde(skip)]
123    pub listen_address_override: Option<Multiaddr>,
124}
125
126impl Parameters {
127    pub(crate) fn default_leader_timeout() -> Duration {
128        Duration::from_millis(200)
129    }
130
131    pub(crate) fn default_min_round_delay() -> Duration {
132        if cfg!(msim) || std::env::var("__TEST_ONLY_CONSENSUS_USE_LONG_MIN_ROUND_DELAY").is_ok() {
133            // Checkpoint building and execution cannot keep up with high commit rate in simtests,
134            // leading to long reconfiguration delays. This is because simtest is single threaded,
135            // and spending too much time in consensus can lead to starvation elsewhere.
136            Duration::from_millis(400)
137        } else if cfg!(test) {
138            // Avoid excessive CPU, data and logs in tests.
139            Duration::from_millis(250)
140        } else {
141            Duration::from_millis(50)
142        }
143    }
144
145    pub(crate) fn default_max_forward_time_drift() -> Duration {
146        Duration::from_millis(500)
147    }
148
149    pub(crate) fn default_max_blocks_per_sync() -> usize {
150        if cfg!(msim) {
151            // Exercise hitting blocks per sync limit.
152            4
153        } else {
154            32
155        }
156    }
157
158    pub(crate) fn default_max_blocks_per_fetch() -> usize {
159        if cfg!(msim) {
160            // Exercise hitting blocks per fetch limit.
161            10
162        } else {
163            1000
164        }
165    }
166
167    pub(crate) fn default_sync_last_known_own_block_timeout() -> Duration {
168        if cfg!(msim) {
169            Duration::from_millis(500)
170        } else {
171            // Here we prioritise liveness over the complete de-risking of block equivocation. 5 seconds
172            // in the majority of cases should be good enough for this given a healthy network.
173            Duration::from_secs(5)
174        }
175    }
176
177    pub(crate) fn default_round_prober_interval_ms() -> u64 {
178        if cfg!(msim) { 1000 } else { 5000 }
179    }
180
181    pub(crate) fn default_round_prober_request_timeout_ms() -> u64 {
182        if cfg!(msim) { 800 } else { 4000 }
183    }
184
185    pub(crate) fn default_propagation_delay_stop_proposal_threshold() -> u32 {
186        // Propagation delay is usually 0 round in production.
187        if cfg!(msim) { 2 } else { 5 }
188    }
189
190    pub(crate) fn default_dag_state_cached_rounds() -> u32 {
191        if cfg!(msim) {
192            // Exercise reading blocks from store.
193            5
194        } else {
195            500
196        }
197    }
198
199    pub(crate) fn default_commit_sync_parallel_fetches() -> usize {
200        8
201    }
202
203    pub(crate) fn default_commit_sync_batch_size() -> u32 {
204        if cfg!(msim) {
205            // Exercise commit sync.
206            5
207        } else {
208            100
209        }
210    }
211
212    pub(crate) fn default_commit_sync_request_timeout() -> Duration {
213        Duration::from_secs(10)
214    }
215
216    pub(crate) fn default_commit_sync_probe_timeout() -> Duration {
217        Duration::from_secs(2)
218    }
219
220    pub(crate) fn default_commit_sync_batches_ahead() -> usize {
221        // This is set to be a multiple of default commit_sync_parallel_fetches to allow fetching ahead,
222        // while keeping the total number of inflight fetches and unprocessed fetched commits limited.
223        32
224    }
225
226    pub(crate) fn default_use_fifo_compaction() -> bool {
227        true
228    }
229}
230
231impl Default for Parameters {
232    fn default() -> Self {
233        Self {
234            db_path: PathBuf::default(),
235            leader_timeout: Parameters::default_leader_timeout(),
236            min_round_delay: Parameters::default_min_round_delay(),
237            max_forward_time_drift: Parameters::default_max_forward_time_drift(),
238            max_blocks_per_sync: Parameters::default_max_blocks_per_sync(),
239            max_blocks_per_fetch: Parameters::default_max_blocks_per_fetch(),
240            sync_last_known_own_block_timeout:
241                Parameters::default_sync_last_known_own_block_timeout(),
242            round_prober_interval_ms: Parameters::default_round_prober_interval_ms(),
243            round_prober_request_timeout_ms: Parameters::default_round_prober_request_timeout_ms(),
244            propagation_delay_stop_proposal_threshold:
245                Parameters::default_propagation_delay_stop_proposal_threshold(),
246            dag_state_cached_rounds: Parameters::default_dag_state_cached_rounds(),
247            commit_sync_parallel_fetches: Parameters::default_commit_sync_parallel_fetches(),
248            commit_sync_batch_size: Parameters::default_commit_sync_batch_size(),
249            commit_sync_batches_ahead: Parameters::default_commit_sync_batches_ahead(),
250            commit_sync_request_timeout: Parameters::default_commit_sync_request_timeout(),
251            commit_sync_probe_timeout: Parameters::default_commit_sync_probe_timeout(),
252            use_fifo_compaction: Parameters::default_use_fifo_compaction(),
253            tonic: TonicParameters::default(),
254            internal: InternalParameters::default(),
255            listen_address_override: None,
256        }
257    }
258}
259
260/// Represents a peer observer node with its network key and address.
261#[derive(Clone, Debug, Deserialize, Serialize)]
262pub struct PeerRecord {
263    /// Network public key of the peer observer node (hex-encoded).
264    #[serde(
265        serialize_with = "serialize_public_key_as_hex",
266        deserialize_with = "deserialize_public_key_from_hex"
267    )]
268    pub public_key: NetworkPublicKey,
269    /// Multi-address of the peer observer node.
270    pub address: Multiaddr,
271}
272
273fn serialize_public_key_as_hex<S>(key: &NetworkPublicKey, serializer: S) -> Result<S::Ok, S::Error>
274where
275    S: serde::Serializer,
276{
277    use fastcrypto::encoding::Encoding;
278    let hex_str = fastcrypto::encoding::Hex::encode(key.to_bytes());
279    serializer.serialize_str(&hex_str)
280}
281
282fn deserialize_public_key_from_hex<'de, D>(deserializer: D) -> Result<NetworkPublicKey, D::Error>
283where
284    D: serde::Deserializer<'de>,
285{
286    use fastcrypto::{encoding::Encoding, traits::ToFromBytes};
287    let hex_str = String::deserialize(deserializer)?;
288    let bytes = fastcrypto::encoding::Hex::decode(&hex_str).map_err(serde::de::Error::custom)?;
289    let inner_key = fastcrypto::ed25519::Ed25519PublicKey::from_bytes(bytes.as_ref())
290        .map_err(serde::de::Error::custom)?;
291    Ok(NetworkPublicKey::new(inner_key))
292}
293
294#[derive(Clone, Debug, Deserialize, Serialize)]
295pub struct TonicParameters {
296    /// Keepalive interval and timeouts for both client and server.
297    ///
298    /// If unspecified, this will default to 5s.
299    #[serde(default = "TonicParameters::default_keepalive_interval")]
300    pub keepalive_interval: Duration,
301
302    /// Size of various per-connection buffers.
303    ///
304    /// If unspecified, this will default to 32MiB.
305    #[serde(default = "TonicParameters::default_connection_buffer_size")]
306    pub connection_buffer_size: usize,
307
308    /// Messages over this size threshold will increment a counter.
309    ///
310    /// If unspecified, this will default to 16MiB.
311    #[serde(default = "TonicParameters::default_excessive_message_size")]
312    pub excessive_message_size: usize,
313
314    /// Hard message size limit for both requests and responses.
315    /// This value is higher than strictly necessary, to allow overheads.
316    /// Message size targets and soft limits are computed based on this value.
317    ///
318    /// If unspecified, this will default to 1GiB.
319    #[serde(default = "TonicParameters::default_message_size_limit")]
320    pub message_size_limit: usize,
321
322    /// Port for the observer server. If configured, then the node will run the observer server on this port.
323    ///
324    /// If unspecified, this will default to `None`.
325    #[serde(default = "TonicParameters::default_observer_server_port")]
326    pub observer_server_port: Option<u16>,
327
328    /// Allowlist of observer public keys (hex encoded). If empty, all observers are allowed.
329    /// If non-empty, only observers with these public keys will be allowed to connect.
330    ///
331    /// If unspecified, this will default to an empty Vec (no allowlist, all observers allowed).
332    #[serde(default = "TonicParameters::default_observer_allowlist")]
333    pub observer_allowlist: Vec<String>,
334
335    /// List of observer peers to connect to when acting as an observer client.
336    /// Each record contains the network public key and multi-address of a peer observer server.
337    ///
338    /// If unspecified, this will default to an empty Vec.
339    #[serde(default = "TonicParameters::default_observer_peers")]
340    pub observer_peers: Vec<PeerRecord>,
341}
342
343impl TonicParameters {
344    pub fn is_observer_server_enabled(&self) -> bool {
345        self.observer_server_port.is_some()
346    }
347
348    fn default_keepalive_interval() -> Duration {
349        Duration::from_secs(10)
350    }
351
352    fn default_connection_buffer_size() -> usize {
353        32 << 20
354    }
355
356    fn default_excessive_message_size() -> usize {
357        16 << 20
358    }
359
360    fn default_message_size_limit() -> usize {
361        64 << 20
362    }
363
364    fn default_observer_server_port() -> Option<u16> {
365        None
366    }
367
368    fn default_observer_allowlist() -> Vec<String> {
369        Vec::new()
370    }
371
372    fn default_observer_peers() -> Vec<PeerRecord> {
373        Vec::new()
374    }
375}
376
377impl Default for TonicParameters {
378    fn default() -> Self {
379        Self {
380            keepalive_interval: TonicParameters::default_keepalive_interval(),
381            connection_buffer_size: TonicParameters::default_connection_buffer_size(),
382            excessive_message_size: TonicParameters::default_excessive_message_size(),
383            message_size_limit: TonicParameters::default_message_size_limit(),
384            observer_server_port: TonicParameters::default_observer_server_port(),
385            observer_allowlist: TonicParameters::default_observer_allowlist(),
386            observer_peers: TonicParameters::default_observer_peers(),
387        }
388    }
389}
390
391/// Internal parameters unrelated to operating a consensus node in the real world.
392#[derive(Clone, Debug, Deserialize, Serialize)]
393pub struct InternalParameters {
394    /// Whether to skip equivocation validation, when testing with equivocators.
395    #[serde(default = "InternalParameters::default_skip_equivocation_validation")]
396    pub skip_equivocation_validation: bool,
397}
398
399impl InternalParameters {
400    fn default_skip_equivocation_validation() -> bool {
401        false
402    }
403}
404
405impl Default for InternalParameters {
406    fn default() -> Self {
407        Self {
408            skip_equivocation_validation: InternalParameters::default_skip_equivocation_validation(
409            ),
410        }
411    }
412}