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    /// Tonic network settings.
109    #[serde(default = "TonicParameters::default")]
110    pub tonic: TonicParameters,
111
112    /// Observer node settings.
113    #[serde(default = "ObserverParameters::default")]
114    pub observer: ObserverParameters,
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
227impl Default for Parameters {
228    fn default() -> Self {
229        Self {
230            db_path: PathBuf::default(),
231            leader_timeout: Parameters::default_leader_timeout(),
232            min_round_delay: Parameters::default_min_round_delay(),
233            max_forward_time_drift: Parameters::default_max_forward_time_drift(),
234            max_blocks_per_sync: Parameters::default_max_blocks_per_sync(),
235            max_blocks_per_fetch: Parameters::default_max_blocks_per_fetch(),
236            sync_last_known_own_block_timeout:
237                Parameters::default_sync_last_known_own_block_timeout(),
238            round_prober_interval_ms: Parameters::default_round_prober_interval_ms(),
239            round_prober_request_timeout_ms: Parameters::default_round_prober_request_timeout_ms(),
240            propagation_delay_stop_proposal_threshold:
241                Parameters::default_propagation_delay_stop_proposal_threshold(),
242            dag_state_cached_rounds: Parameters::default_dag_state_cached_rounds(),
243            commit_sync_parallel_fetches: Parameters::default_commit_sync_parallel_fetches(),
244            commit_sync_batch_size: Parameters::default_commit_sync_batch_size(),
245            commit_sync_batches_ahead: Parameters::default_commit_sync_batches_ahead(),
246            commit_sync_request_timeout: Parameters::default_commit_sync_request_timeout(),
247            commit_sync_probe_timeout: Parameters::default_commit_sync_probe_timeout(),
248            tonic: TonicParameters::default(),
249            observer: ObserverParameters::default(),
250            internal: InternalParameters::default(),
251            listen_address_override: None,
252        }
253    }
254}
255
256/// Represents a peer observer node with its network key and address.
257#[derive(Clone, Debug, Deserialize, Serialize)]
258pub struct PeerRecord {
259    /// Network public key of the peer observer node (hex-encoded).
260    #[serde(
261        serialize_with = "serialize_public_key_as_hex",
262        deserialize_with = "deserialize_public_key_from_hex"
263    )]
264    pub public_key: NetworkPublicKey,
265    /// Multi-address of the peer observer node.
266    pub address: Multiaddr,
267}
268
269fn serialize_public_key_as_hex<S>(key: &NetworkPublicKey, serializer: S) -> Result<S::Ok, S::Error>
270where
271    S: serde::Serializer,
272{
273    use fastcrypto::encoding::Encoding;
274    let hex_str = fastcrypto::encoding::Hex::encode(key.to_bytes());
275    serializer.serialize_str(&hex_str)
276}
277
278fn deserialize_public_key_from_hex<'de, D>(deserializer: D) -> Result<NetworkPublicKey, D::Error>
279where
280    D: serde::Deserializer<'de>,
281{
282    use fastcrypto::{encoding::Encoding, traits::ToFromBytes};
283    let hex_str = String::deserialize(deserializer)?;
284    let bytes = fastcrypto::encoding::Hex::decode(&hex_str).map_err(serde::de::Error::custom)?;
285    let inner_key = fastcrypto::ed25519::Ed25519PublicKey::from_bytes(bytes.as_ref())
286        .map_err(serde::de::Error::custom)?;
287    Ok(NetworkPublicKey::new(inner_key))
288}
289
290#[derive(Clone, Debug, Deserialize, Serialize)]
291pub struct TonicParameters {
292    /// Keepalive interval and timeouts for both client and server.
293    ///
294    /// If unspecified, this will default to 5s.
295    #[serde(default = "TonicParameters::default_keepalive_interval")]
296    pub keepalive_interval: Duration,
297
298    /// Size of various per-connection buffers.
299    ///
300    /// If unspecified, this will default to 32MiB.
301    #[serde(default = "TonicParameters::default_connection_buffer_size")]
302    pub connection_buffer_size: usize,
303
304    /// Messages over this size threshold will increment a counter.
305    ///
306    /// If unspecified, this will default to 16MiB.
307    #[serde(default = "TonicParameters::default_excessive_message_size")]
308    pub excessive_message_size: usize,
309
310    /// Hard message size limit for both requests and responses.
311    /// This value is higher than strictly necessary, to allow overheads.
312    /// Message size targets and soft limits are computed based on this value.
313    ///
314    /// If unspecified, this will default to 1GiB.
315    #[serde(default = "TonicParameters::default_message_size_limit")]
316    pub message_size_limit: usize,
317}
318
319impl TonicParameters {
320    fn default_keepalive_interval() -> Duration {
321        Duration::from_secs(10)
322    }
323
324    fn default_connection_buffer_size() -> usize {
325        32 << 20
326    }
327
328    fn default_excessive_message_size() -> usize {
329        16 << 20
330    }
331
332    fn default_message_size_limit() -> usize {
333        64 << 20
334    }
335}
336
337impl Default for TonicParameters {
338    fn default() -> Self {
339        Self {
340            keepalive_interval: TonicParameters::default_keepalive_interval(),
341            connection_buffer_size: TonicParameters::default_connection_buffer_size(),
342            excessive_message_size: TonicParameters::default_excessive_message_size(),
343            message_size_limit: TonicParameters::default_message_size_limit(),
344        }
345    }
346}
347
348/// Observer node configuration parameters.
349#[derive(Clone, Debug, Deserialize, Serialize)]
350pub struct ObserverParameters {
351    /// Port for the observer server. If configured, then the node will run the observer server on this port.
352    ///
353    /// If unspecified, this will default to `None`.
354    #[serde(default = "ObserverParameters::default_server_port")]
355    pub server_port: Option<u16>,
356
357    /// Allowlist of observer public keys (hex encoded). If empty, all observers are allowed.
358    /// If non-empty, only observers with these public keys will be allowed to connect.
359    ///
360    /// If unspecified, this will default to an empty Vec (no allowlist, all observers allowed).
361    #[serde(default = "ObserverParameters::default_allowlist")]
362    pub allowlist: Vec<String>,
363
364    /// List of observer peers to connect to when acting as an observer client.
365    /// Each record contains the network public key and multi-address of a peer observer server.
366    ///
367    /// If unspecified, this will default to an empty Vec.
368    #[serde(default = "ObserverParameters::default_peers")]
369    pub peers: Vec<PeerRecord>,
370}
371
372impl ObserverParameters {
373    pub fn is_server_enabled(&self) -> bool {
374        self.server_port.is_some()
375    }
376
377    fn default_server_port() -> Option<u16> {
378        None
379    }
380
381    fn default_allowlist() -> Vec<String> {
382        Vec::new()
383    }
384
385    fn default_peers() -> Vec<PeerRecord> {
386        Vec::new()
387    }
388}
389
390impl Default for ObserverParameters {
391    fn default() -> Self {
392        Self {
393            server_port: ObserverParameters::default_server_port(),
394            allowlist: ObserverParameters::default_allowlist(),
395            peers: ObserverParameters::default_peers(),
396        }
397    }
398}
399
400/// Internal parameters unrelated to operating a consensus node in the real world.
401#[derive(Clone, Debug, Deserialize, Serialize)]
402pub struct InternalParameters {
403    /// Whether to skip equivocation validation, when testing with equivocators.
404    #[serde(default = "InternalParameters::default_skip_equivocation_validation")]
405    pub skip_equivocation_validation: bool,
406}
407
408impl InternalParameters {
409    fn default_skip_equivocation_validation() -> bool {
410        false
411    }
412}
413
414impl Default for InternalParameters {
415    fn default() -> Self {
416        Self {
417            skip_equivocation_validation: InternalParameters::default_skip_equivocation_validation(
418            ),
419        }
420    }
421}