Skip to main content

starfish_config/
parameters.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::{path::PathBuf, time::Duration};
6
7use serde::{Deserialize, Serialize};
8
9/// Ceiling on the number of headers, and on the number of shards, a bundle may
10/// declare. Enforced while decoding, before the entries are materialised, so a
11/// peer cannot make the decoder build a vector far larger than the configured
12/// caps allow it to keep. Both caps are validated against it at startup.
13pub const MAX_HEADERS_OR_SHARDS_PER_BUNDLE: usize = 1024;
14
15/// Ceiling on the headers a fetch response may carry, for header sync and
16/// commit sync alike. The server truncates its response to its own
17/// `max_headers_per_header_sync_fetch` or `max_headers_per_commit_sync_fetch`,
18/// both validated against this at startup, so a client can reject a response
19/// past it as misbehaviour while still accepting a peer configured above its
20/// own cap. Enforced while decoding each response message, before its entries
21/// are materialised.
22pub const HEADERS_PER_FETCH_CEILING: usize = 1024;
23
24/// Ceiling on the transaction entries a fetch request or response may carry,
25/// for transaction sync and regular commit sync alike. A client requests at
26/// most its own `max_transactions_per_transaction_sync_fetch` or
27/// `max_transactions_per_commit_sync_fetch`, both validated against this at
28/// startup, and the server returns at most one entry per requested reference.
29/// Enforced while decoding each message, before its entries are materialised.
30pub const TRANSACTIONS_PER_FETCH_CEILING: usize = 1024;
31
32/// Ceiling on the commits a commit-sync fetch may request, for regular and
33/// fast commit sync alike. A client requests at most its own
34/// `commit_sync_batch_size` or `fast_commit_sync_batch_size` commits, both
35/// validated against this at startup. Enforced while decoding each response
36/// message, before its entries are materialised.
37pub const COMMITS_PER_FETCH_CEILING: usize = 1024;
38
39/// Operational configurations of a consensus authority.
40///
41/// All fields should tolerate inconsistencies among authorities, without
42/// affecting safety of the protocol. Otherwise, they need to be part of IOTA
43/// protocol config or epoch state on-chain.
44///
45/// NOTE: fields with default values are specified in the serde default
46/// functions. Most operators should not need to specify any field, except
47/// db_path.
48#[derive(Clone, Debug, Deserialize, Serialize)]
49pub struct Parameters {
50    /// Path to consensus DB for this epoch. Required when initializing
51    /// consensus. This is calculated based on user configuration for base
52    /// directory.
53    #[serde(skip)]
54    pub db_path: PathBuf,
55
56    /// Time to wait for parent round leader before sealing a block, from when
57    /// parent round has a quorum.
58    #[serde(default = "Parameters::default_leader_timeout")]
59    pub leader_timeout: Duration,
60
61    /// Sustained spacing between own blocks: long-run production never exceeds
62    /// one block per `min_block_delay`. This avoids generating too many rounds
63    /// when latency is low. This is especially necessary for tests running
64    /// locally. If setting a non-default value, it should be set low enough
65    /// to avoid reducing round rate and increasing latency in realistic and
66    /// distributed configurations.
67    #[serde(default = "Parameters::default_min_block_delay")]
68    pub min_block_delay: Duration,
69
70    /// Soft counterpart of `leader_timeout`: after this duration we are
71    /// willing to propose a block even without a strong-vote quorum, to avoid
72    /// liveness stalls when leader data is slow to propagate. Fires earlier
73    /// than `leader_timeout` and does not force block creation on its own.
74    #[serde(default = "Parameters::default_soft_leader_timeout")]
75    pub soft_leader_timeout: Duration,
76
77    /// Window bounding own block production together with `min_block_delay`:
78    /// idle time accrues budget for bursts of up to `block_rate_window /
79    /// min_block_delay` back-to-back blocks, letting a validator that fell
80    /// behind catch up on rounds instead of skipping them. Set at or below
81    /// `min_block_delay` to disable bursting (fixed spacing between blocks).
82    #[serde(default = "Parameters::default_block_rate_window")]
83    pub block_rate_window: Duration,
84
85    /// Number of block headers to fetch per commit sync request.
86    #[serde(default = "Parameters::default_max_headers_per_commit_sync_fetch")]
87    pub max_headers_per_commit_sync_fetch: usize,
88
89    /// Number of transactions to fetch per commit sync request.
90    #[serde(default = "Parameters::default_max_transactions_per_commit_sync_fetch")]
91    pub max_transactions_per_commit_sync_fetch: usize,
92
93    /// Number of block headers to fetch per header sync (periodic or live)
94    /// request.
95    #[serde(default = "Parameters::default_max_headers_per_header_sync_fetch")]
96    pub max_headers_per_header_sync_fetch: usize,
97
98    /// Number of transactions to fetch per transaction sync request.
99    #[serde(default = "Parameters::default_max_transactions_per_transaction_sync_fetch")]
100    pub max_transactions_per_transaction_sync_fetch: usize,
101
102    /// Time to wait during node start up until the node has synced the last
103    /// proposed block via the network peers. When set to `0` the sync
104    /// mechanism is disabled. This property is meant to be used for amnesia
105    /// recovery.
106    #[serde(default = "Parameters::default_sync_last_known_own_block_timeout")]
107    pub sync_last_known_own_block_timeout: Duration,
108
109    /// The number of rounds of blocks to be kept in the Dag state cache per
110    /// authority. The larger the number the more the blocks that will be
111    /// kept in memory allowing minimising any potential disk access.
112    /// Value should be at minimum 50 rounds to ensure node performance, but
113    /// being too large can be expensive in memory usage.
114    #[serde(default = "Parameters::default_dag_state_cached_rounds")]
115    pub dag_state_cached_rounds: u32,
116
117    /// Rounds a header from a far-future-bounded source may lead the locally
118    /// accepted frontier, in addition to `dag_state_cached_rounds`, before it
119    /// is dropped as too far ahead to connect.
120    #[serde(default = "Parameters::default_peer_round_ahead_margin")]
121    pub peer_round_ahead_margin: u32,
122
123    // Number of authorities commit syncer fetches in parallel.
124    // Both commits in a range and blocks referenced by the commits are fetched per authority.
125    #[serde(default = "Parameters::default_commit_sync_parallel_fetches")]
126    pub commit_sync_parallel_fetches: usize,
127
128    // Number of commits to fetch in a batch, also the maximum number of commits returned per
129    // fetch. If this value is set too small, fetching becomes inefficient.
130    // If this value is set too large, it can result in load imbalance and stragglers.
131    #[serde(default = "Parameters::default_commit_sync_batch_size")]
132    pub commit_sync_batch_size: u32,
133
134    // This affects the maximum number of commit batches being fetched, and those fetched but not
135    // processed as consensus output, before throttling of outgoing commit fetches starts.
136    #[serde(default = "Parameters::default_commit_sync_batches_ahead")]
137    pub commit_sync_batches_ahead: usize,
138
139    /// Maximum number of commits scanned and replayed per batch during
140    /// recovery, bounding peak memory when a large unprocessed range is
141    /// replayed at startup.
142    #[serde(default = "Parameters::default_commit_recovery_batch_size")]
143    pub commit_recovery_batch_size: u32,
144
145    /// Maximum number of headers to be included in a bundle. Headers exceeding
146    /// the max allowed limit will be truncated.
147    #[serde(default = "Parameters::default_max_headers_per_bundle")]
148    pub max_headers_per_bundle: usize,
149
150    /// Maximum number of transaction shards to be included in a bundle. Shards
151    /// exceeding the max allowed limit will be truncated.
152    #[serde(default = "Parameters::default_max_shards_per_bundle")]
153    pub max_shards_per_bundle: usize,
154
155    /// Tonic network settings.
156    #[serde(default = "TonicParameters::default")]
157    pub tonic: TonicParameters,
158
159    /// Number of commits requested per fast commit sync fetch. A response may
160    /// carry up to twice this many, since it extends past the requested end to
161    /// reach a certifiable commit. Set too small, fetching is inefficient and
162    /// the server has little room to reach one; set too large, it causes load
163    /// imbalance and stragglers.
164    #[serde(default = "Parameters::default_fast_commit_sync_batch_size")]
165    pub fast_commit_sync_batch_size: u32,
166
167    // Gap threshold for switching between commit syncers. When the gap between quorum and local
168    // commit index is larger than this threshold, FastCommitSyncer fetches. Otherwise,
169    // CommitSyncer fetches.
170    #[serde(default = "Parameters::default_commit_sync_gap_threshold")]
171    pub commit_sync_gap_threshold: u32,
172
173    /// Enable FastCommitSyncer for faster recovery from large commit gaps.
174    /// Enabled by default; operators can disable it locally if bugs are
175    /// discovered.
176    #[serde(default = "Parameters::default_enable_fast_commit_syncer")]
177    pub enable_fast_commit_syncer: bool,
178
179    /// Reconnect block streams after fast commit sync reinitializes consensus,
180    /// discarding bundles buffered against the previous state. Enabled by
181    /// default; operators can disable it locally. Has no effect unless
182    /// `enable_fast_commit_syncer` is also enabled, since only fast sync
183    /// signals the reset.
184    #[serde(default = "Parameters::default_enable_block_stream_reset_on_fast_sync_exit")]
185    pub enable_block_stream_reset_on_fast_sync_exit: bool,
186
187    /// Ask commit-sync peers that have voted for the end of the requested
188    /// range before those that have not, since a vote means the peer has
189    /// solidified every commit in the range. Peers without an observed vote
190    /// are ordered behind; each fetch round tries a bounded number of peers,
191    /// so on a committee larger than that bound they can stay outside the
192    /// round until their votes are observed. The header fetch that
193    /// reinitializes the node at the end of fast sync likewise asks peers that
194    /// have voted for the last commit first. Enabled by default; disabling it
195    /// leaves peers in the order `enable_peer_responsiveness_ranking` gives
196    /// them.
197    #[serde(default = "Parameters::default_enable_commit_sync_peer_selection_by_commit_votes")]
198    pub enable_commit_sync_peer_selection_by_commit_votes: bool,
199
200    /// Enable adaptive acknowledgment filtering for StarfishSpeed.
201    /// Local heuristic that leaves out of leader blocks the acknowledgments
202    /// that the voters are not expected to hold at the next round, judged
203    /// from how soon they acknowledged recent blocks. Voters count by how
204    /// often this node's blocks reference them. Deferred acknowledgments go
205    /// into later blocks.
206    #[serde(default = "Parameters::default_enable_starfish_speed_adaptive_acknowledgments")]
207    pub enable_starfish_speed_adaptive_acknowledgments: bool,
208
209    /// Prefer more responsive peers when the transactions synchronizer, the
210    /// commit syncer and the header synchronizer select peers to fetch from.
211    /// Responses are verified the same way regardless, so it cannot affect
212    /// safety. Enabled by default; disabling it selects peers in a uniform
213    /// random order.
214    #[serde(default = "Parameters::default_enable_peer_responsiveness_ranking")]
215    pub enable_peer_responsiveness_ranking: bool,
216
217    /// Ask only a bounded number of peers that recently supplied a new header
218    /// or referenced a missing one to push more headers from that author.
219    #[serde(default = "Parameters::default_enable_bounded_header_advertisement")]
220    pub enable_bounded_header_advertisement: bool,
221
222    /// Ask only the fastest peers that together provide enough shards and
223    /// stake for reconstruction. Enabled by default; disabling it asks every
224    /// peer.
225    #[serde(default = "Parameters::default_enable_shard_peer_selection")]
226    pub enable_shard_peer_selection: bool,
227
228    /// Port for the DAG visualizer gRPC server (localhost only).
229    /// When set, starts a debugging server for real-time DAG visualization.
230    /// Only has an effect when the `dag-visualizer` feature is compiled in.
231    /// Disabled by default (None).
232    #[serde(default)]
233    pub dag_visualizer_port: Option<u16>,
234
235    /// Maximum number of rounds the last commit's leader may run ahead of the
236    /// last solid commit's leader before the node stops accepting new block
237    /// bundles and restricts header fetching, until solidification catches up.
238    #[serde(default = "Parameters::default_solid_commit_lag_threshold")]
239    pub solid_commit_lag_threshold: u32,
240
241    /// Maximum number of shards from one relaying authority retained across
242    /// all pending shard accumulators. At the budget, admitting a new shard
243    /// from the authority evicts its oldest retained one, so reconstructor
244    /// memory stays bounded by `committee size × budget × shard size`
245    /// regardless of how far commits run ahead of solidification.
246    #[serde(default = "Parameters::default_shard_budget_per_authority")]
247    pub shard_budget_per_authority: u32,
248
249    /// Maximum transaction payload bytes one fast commit-sync response carries.
250    /// A fetch covering more commits than this is answered with the commits
251    /// whose payloads fit, and the requester asks for the rest in its next
252    /// fetch. When the range's first commit exceeds this on its own it is
253    /// still served whole. A requester stops reading a response once it passes
254    /// this and its first commit is complete.
255    #[serde(default = "Parameters::default_max_fast_commit_sync_transaction_bytes")]
256    pub max_fast_commit_sync_transaction_bytes: usize,
257}
258
259impl Parameters {
260    /// Threshold for the number of commits sent to the consumer but not yet
261    /// handled, above which commit producers (commit syncers, commit observer
262    /// recovery) pause to let the consumer catch up.
263    pub fn unhandled_commits_threshold(&self) -> u32 {
264        self.commit_sync_batch_size * (self.commit_sync_batches_ahead as u32)
265    }
266
267    pub(crate) fn default_leader_timeout() -> Duration {
268        Duration::from_millis(200)
269    }
270
271    pub(crate) fn default_min_block_delay() -> Duration {
272        if cfg!(msim) || std::env::var("__TEST_ONLY_CONSENSUS_USE_LONG_MIN_BLOCK_DELAY").is_ok() {
273            // Checkpoint building and execution cannot keep up with high commit rate in
274            // simtests, leading to long reconfiguration delays. This is because
275            // simtest is single threaded, and spending too much time in
276            // consensus can lead to starvation elsewhere.
277            Duration::from_millis(400)
278        } else if cfg!(test) {
279            // Avoid excessive CPU, data and logs in tests.
280            Duration::from_millis(250)
281        } else {
282            // For production, use min delay between block being set to 50ms, reducing the
283            // block rate to 20 blocks/sec
284            Duration::from_millis(50)
285        }
286    }
287
288    pub(crate) fn default_soft_leader_timeout() -> Duration {
289        Duration::from_millis(5)
290    }
291
292    pub(crate) fn default_block_rate_window() -> Duration {
293        Duration::from_secs(2)
294    }
295
296    /// Burst capacity: maximum number of own blocks within `block_rate_window`
297    /// (40 in production, 5 in msim, 8 in tests with the default window).
298    pub fn block_rate_burst(&self) -> u64 {
299        let interval_ms = self.min_block_delay.as_millis().max(1) as u64;
300        (self.block_rate_window.as_millis() as u64 / interval_ms).max(1)
301    }
302
303    /// Highest round a header from a far-future-bounded source may have,
304    /// relative to the accepted `frontier`, to still be close enough to
305    /// connect; headers above this are too far ahead and dropped.
306    pub fn far_future_round_ceiling(&self, frontier: u32) -> u32 {
307        frontier
308            .saturating_add(self.dag_state_cached_rounds)
309            .saturating_add(self.peer_round_ahead_margin)
310    }
311
312    /// Maximum number of block headers served per fetch request, depending on
313    /// whether the request comes from commit sync or the header synchronizer.
314    pub fn max_headers_per_fetch(&self, commit_sync: bool) -> usize {
315        if commit_sync {
316            self.max_headers_per_commit_sync_fetch
317        } else {
318            self.max_headers_per_header_sync_fetch
319        }
320    }
321
322    /// Validates local consensus parameters, rejecting zero values that can
323    /// lead to synchronization problems. Returns a description of the first
324    /// offending field.
325    pub fn validate(&self) -> Result<(), String> {
326        let positive_fields = [
327            (
328                "max_headers_per_commit_sync_fetch",
329                self.max_headers_per_commit_sync_fetch as u128,
330            ),
331            (
332                "max_transactions_per_commit_sync_fetch",
333                self.max_transactions_per_commit_sync_fetch as u128,
334            ),
335            (
336                "max_headers_per_header_sync_fetch",
337                self.max_headers_per_header_sync_fetch as u128,
338            ),
339            (
340                "max_transactions_per_transaction_sync_fetch",
341                self.max_transactions_per_transaction_sync_fetch as u128,
342            ),
343            (
344                "dag_state_cached_rounds",
345                self.dag_state_cached_rounds as u128,
346            ),
347            (
348                "commit_sync_parallel_fetches",
349                self.commit_sync_parallel_fetches as u128,
350            ),
351            (
352                "commit_sync_batch_size",
353                self.commit_sync_batch_size as u128,
354            ),
355            (
356                "commit_recovery_batch_size",
357                self.commit_recovery_batch_size as u128,
358            ),
359            (
360                "commit_sync_batches_ahead",
361                self.commit_sync_batches_ahead as u128,
362            ),
363            (
364                "max_headers_per_bundle",
365                self.max_headers_per_bundle as u128,
366            ),
367            ("max_shards_per_bundle", self.max_shards_per_bundle as u128),
368            (
369                "fast_commit_sync_batch_size",
370                self.fast_commit_sync_batch_size as u128,
371            ),
372            (
373                "max_fast_commit_sync_transaction_bytes",
374                self.max_fast_commit_sync_transaction_bytes as u128,
375            ),
376            (
377                "tonic.connection_buffer_size",
378                self.tonic.connection_buffer_size as u128,
379            ),
380            (
381                "tonic.excessive_message_size",
382                self.tonic.excessive_message_size as u128,
383            ),
384            (
385                "tonic.message_size_limit",
386                self.tonic.message_size_limit as u128,
387            ),
388            (
389                "tonic.keepalive_interval",
390                self.tonic.keepalive_interval.as_nanos(),
391            ),
392            (
393                "shard_budget_per_authority",
394                self.shard_budget_per_authority as u128,
395            ),
396        ];
397        for (name, value) in positive_fields {
398            if value == 0 {
399                return Err(format!("{name} must be positive"));
400            }
401        }
402        let bundle_fields = [
403            ("max_headers_per_bundle", self.max_headers_per_bundle),
404            ("max_shards_per_bundle", self.max_shards_per_bundle),
405        ];
406        for (name, value) in bundle_fields {
407            if value > MAX_HEADERS_OR_SHARDS_PER_BUNDLE {
408                return Err(format!(
409                    "{name} must not exceed {MAX_HEADERS_OR_SHARDS_PER_BUNDLE}"
410                ));
411            }
412        }
413        let header_fetch_fields = [
414            (
415                "max_headers_per_header_sync_fetch",
416                self.max_headers_per_header_sync_fetch,
417            ),
418            (
419                "max_headers_per_commit_sync_fetch",
420                self.max_headers_per_commit_sync_fetch,
421            ),
422        ];
423        for (name, value) in header_fetch_fields {
424            if value > HEADERS_PER_FETCH_CEILING {
425                return Err(format!(
426                    "{name} must not exceed {HEADERS_PER_FETCH_CEILING}"
427                ));
428            }
429        }
430        let transaction_fetch_fields = [
431            (
432                "max_transactions_per_transaction_sync_fetch",
433                self.max_transactions_per_transaction_sync_fetch,
434            ),
435            (
436                "max_transactions_per_commit_sync_fetch",
437                self.max_transactions_per_commit_sync_fetch,
438            ),
439        ];
440        for (name, value) in transaction_fetch_fields {
441            if value > TRANSACTIONS_PER_FETCH_CEILING {
442                return Err(format!(
443                    "{name} must not exceed {TRANSACTIONS_PER_FETCH_CEILING}"
444                ));
445            }
446        }
447        let commit_fetch_fields = [
448            ("commit_sync_batch_size", self.commit_sync_batch_size),
449            (
450                "fast_commit_sync_batch_size",
451                self.fast_commit_sync_batch_size,
452            ),
453        ];
454        for (name, value) in commit_fetch_fields {
455            if value as usize > COMMITS_PER_FETCH_CEILING {
456                return Err(format!(
457                    "{name} must not exceed {COMMITS_PER_FETCH_CEILING}"
458                ));
459            }
460        }
461        Ok(())
462    }
463
464    // Maximum number of block headers to fetch per commit sync request.
465    pub(crate) fn default_max_headers_per_commit_sync_fetch() -> usize {
466        if cfg!(msim) {
467            // Exercise hitting blocks per fetch limit.
468            10
469        } else {
470            1000
471        }
472    }
473
474    // Maximum number of transactions to fetch per commit sync request.
475    pub(crate) fn default_max_transactions_per_commit_sync_fetch() -> usize {
476        if cfg!(msim) {
477            // Exercise hitting transactions per fetch limit.
478            10
479        } else {
480            1000
481        }
482    }
483
484    // Maximum number of block headers to fetch per header sync (periodic or
485    // live) request.
486    pub(crate) fn default_max_headers_per_header_sync_fetch() -> usize {
487        if cfg!(msim) {
488            // Exercise hitting blocks per fetch limit.
489            10
490        } else {
491            // TODO: This might should match the value of block headers in the bundle.
492            100
493        }
494    }
495
496    // Maximum number of transactions to fetch per transaction sync request.
497    pub(crate) fn default_max_transactions_per_transaction_sync_fetch() -> usize {
498        if cfg!(msim) { 10 } else { 1000 }
499    }
500
501    pub(crate) fn default_sync_last_known_own_block_timeout() -> Duration {
502        if cfg!(msim) {
503            Duration::from_millis(500)
504        } else {
505            // Here we prioritise liveness over the complete de-risking of block
506            // equivocation. 5 seconds in the majority of cases should be good
507            // enough for this given a healthy network.
508            Duration::from_secs(5)
509        }
510    }
511
512    pub(crate) fn default_dag_state_cached_rounds() -> u32 {
513        if cfg!(msim) {
514            // Exercise reading blocks from store.
515            5
516        } else {
517            500
518        }
519    }
520
521    pub(crate) fn default_peer_round_ahead_margin() -> u32 {
522        1000
523    }
524
525    pub(crate) fn default_commit_sync_parallel_fetches() -> usize {
526        8
527    }
528
529    pub(crate) fn default_commit_sync_batch_size() -> u32 {
530        if cfg!(msim) {
531            // Exercise commit sync.
532            5
533        } else {
534            100
535        }
536    }
537
538    pub(crate) fn default_commit_recovery_batch_size() -> u32 {
539        if cfg!(msim) { 3 } else { 250 }
540    }
541
542    pub(crate) fn default_commit_sync_batches_ahead() -> usize {
543        // This is set to be a multiple of default commit_sync_parallel_fetches to allow
544        // fetching ahead, while keeping the total number of inflight fetches
545        // and unprocessed fetched commits limited.
546        32
547    }
548
549    pub(crate) fn default_max_headers_per_bundle() -> usize {
550        150
551    }
552
553    pub(crate) fn default_max_shards_per_bundle() -> usize {
554        150
555    }
556
557    pub(crate) fn default_fast_commit_sync_batch_size() -> u32 {
558        if cfg!(msim) {
559            // Exercise fast commit sync.
560            5
561        } else {
562            // Sized so that commit_sync_parallel_fetches ranges fit under the
563            // unhandled-commits threshold (8 x 400 <= 3200), letting fast sync
564            // actually run its fetches in parallel. The server chunks larger
565            // responses across multiple messages either way.
566            400
567        }
568    }
569
570    pub(crate) fn default_commit_sync_gap_threshold() -> u32 {
571        if cfg!(msim) {
572            // Use smaller threshold for testing.
573            10
574        } else {
575            // When gap > 1000, FastCommitSyncer is more efficient.
576            // When gap <= 1000, CommitSyncer handles incremental sync.
577            1000
578        }
579    }
580
581    pub(crate) fn default_enable_fast_commit_syncer() -> bool {
582        // Enabled by default. Operators can disable it locally if bugs are discovered,
583        // without waiting for a protocol upgrade.
584        true
585    }
586
587    pub(crate) fn default_enable_block_stream_reset_on_fast_sync_exit() -> bool {
588        true
589    }
590
591    pub(crate) fn default_enable_commit_sync_peer_selection_by_commit_votes() -> bool {
592        // Enabled by default. Ordering only, so it cannot diverge consensus.
593        true
594    }
595
596    pub(crate) fn default_enable_starfish_speed_adaptive_acknowledgments() -> bool {
597        true
598    }
599
600    pub(crate) fn default_enable_peer_responsiveness_ranking() -> bool {
601        true
602    }
603
604    pub(crate) fn default_enable_bounded_header_advertisement() -> bool {
605        true
606    }
607
608    pub(crate) fn default_enable_shard_peer_selection() -> bool {
609        true
610    }
611
612    pub(crate) fn default_solid_commit_lag_threshold() -> u32 {
613        // The healthy gap is a few rounds at most; 500 rounds (a few minutes of
614        // commits) is far above live jitter yet caps how long a solidification
615        // stall can keep widening the shard/payload retention window.
616        500
617    }
618
619    pub(crate) fn default_max_fast_commit_sync_transaction_bytes() -> usize {
620        64 * 1024 * 1024
621    }
622
623    pub(crate) fn default_shard_budget_per_authority() -> u32 {
624        // Honest need per authority is one shard per slot times a few rounds
625        // until decode, well under the budget at any realistic committee size.
626        // Worst-case total pool ≈ 3 × budget × the maximum payload size.
627        1000
628    }
629}
630
631impl Default for Parameters {
632    fn default() -> Self {
633        Self {
634            db_path: PathBuf::default(),
635            leader_timeout: Parameters::default_leader_timeout(),
636            min_block_delay: Parameters::default_min_block_delay(),
637            soft_leader_timeout: Parameters::default_soft_leader_timeout(),
638            block_rate_window: Parameters::default_block_rate_window(),
639            max_headers_per_commit_sync_fetch:
640                Parameters::default_max_headers_per_commit_sync_fetch(),
641            max_transactions_per_commit_sync_fetch:
642                Parameters::default_max_transactions_per_commit_sync_fetch(),
643            max_headers_per_header_sync_fetch:
644                Parameters::default_max_headers_per_header_sync_fetch(),
645            max_transactions_per_transaction_sync_fetch:
646                Parameters::default_max_transactions_per_transaction_sync_fetch(),
647            sync_last_known_own_block_timeout:
648                Parameters::default_sync_last_known_own_block_timeout(),
649            dag_state_cached_rounds: Parameters::default_dag_state_cached_rounds(),
650            peer_round_ahead_margin: Parameters::default_peer_round_ahead_margin(),
651            commit_sync_parallel_fetches: Parameters::default_commit_sync_parallel_fetches(),
652            commit_sync_batch_size: Parameters::default_commit_sync_batch_size(),
653            commit_sync_batches_ahead: Parameters::default_commit_sync_batches_ahead(),
654            commit_recovery_batch_size: Parameters::default_commit_recovery_batch_size(),
655            max_headers_per_bundle: Parameters::default_max_headers_per_bundle(),
656            max_shards_per_bundle: Parameters::default_max_shards_per_bundle(),
657            tonic: TonicParameters::default(),
658            fast_commit_sync_batch_size: Parameters::default_fast_commit_sync_batch_size(),
659            commit_sync_gap_threshold: Parameters::default_commit_sync_gap_threshold(),
660            enable_fast_commit_syncer: Parameters::default_enable_fast_commit_syncer(),
661            enable_block_stream_reset_on_fast_sync_exit:
662                Parameters::default_enable_block_stream_reset_on_fast_sync_exit(),
663            enable_commit_sync_peer_selection_by_commit_votes:
664                Parameters::default_enable_commit_sync_peer_selection_by_commit_votes(),
665            enable_starfish_speed_adaptive_acknowledgments:
666                Parameters::default_enable_starfish_speed_adaptive_acknowledgments(),
667            enable_peer_responsiveness_ranking:
668                Parameters::default_enable_peer_responsiveness_ranking(),
669            enable_bounded_header_advertisement:
670                Parameters::default_enable_bounded_header_advertisement(),
671            enable_shard_peer_selection: Parameters::default_enable_shard_peer_selection(),
672            dag_visualizer_port: None,
673            solid_commit_lag_threshold: Parameters::default_solid_commit_lag_threshold(),
674            shard_budget_per_authority: Parameters::default_shard_budget_per_authority(),
675            max_fast_commit_sync_transaction_bytes:
676                Parameters::default_max_fast_commit_sync_transaction_bytes(),
677        }
678    }
679}
680
681#[derive(Clone, Debug, Deserialize, Serialize)]
682pub struct TonicParameters {
683    /// Keepalive interval and timeouts for both client and server.
684    ///
685    /// If unspecified, this will default to 5s.
686    #[serde(default = "TonicParameters::default_keepalive_interval")]
687    pub keepalive_interval: Duration,
688
689    /// Size of various per-connection buffers.
690    ///
691    /// If unspecified, this will default to 32MiB.
692    #[serde(default = "TonicParameters::default_connection_buffer_size")]
693    pub connection_buffer_size: usize,
694
695    /// Response messages over this wire size, prefix plus compressed payload,
696    /// increment a counter.
697    ///
698    /// If unspecified, this will default to 16MiB.
699    #[serde(default = "TonicParameters::default_excessive_message_size")]
700    pub excessive_message_size: usize,
701
702    /// Hard message size limit for both requests and responses.
703    /// This value is higher than strictly necessary, to allow overheads.
704    /// Message size targets and soft limits are computed based on this value.
705    ///
706    /// If unspecified, this will default to 64MiB.
707    #[serde(default = "TonicParameters::default_message_size_limit")]
708    pub message_size_limit: usize,
709
710    /// Maximum number of concurrent HTTP/2 streams a peer may open on a single
711    /// connection. Bounds per-connection request fan-out.
712    ///
713    /// If unspecified, this will default to 64. `0` disables the limit, leaving
714    /// the transport default.
715    #[serde(default = "TonicParameters::default_max_concurrent_streams")]
716    pub max_concurrent_streams: u32,
717
718    /// Server-side fallback deadline for requests that omit a `grpc-timeout`
719    /// header. The long-lived block-subscription stream is always exempt.
720    ///
721    /// If unspecified, this will default to 120s. A zero duration disables the
722    /// fallback deadline.
723    #[serde(default = "TonicParameters::default_request_timeout")]
724    pub request_timeout: Duration,
725
726    /// Hard size limit for request messages: inbound requests when decoding
727    /// and outbound requests when encoding. Consensus requests are small (ref
728    /// lists); large payloads belong to responses, bounded by
729    /// `message_size_limit`. A smaller request bound shrinks the memory a
730    /// single in-flight request can pin before its handler runs.
731    ///
732    /// If unspecified, this will default to 1MiB. `0` falls back to
733    /// `message_size_limit`.
734    #[serde(
735        default = "TonicParameters::default_max_request_message_size",
736        alias = "max_inbound_message_size"
737    )]
738    pub max_request_message_size: usize,
739
740    /// Per-peer, per-RPC admission caps for the inbound consensus server.
741    #[serde(default)]
742    pub admission: AdmissionParameters,
743
744    /// Deadline for receiving the request message that opens a block
745    /// subscription stream. A peer that opens the stream and withholds the
746    /// request is disconnected once it expires; the stream itself stays exempt
747    /// from `request_timeout`.
748    ///
749    /// If unspecified, this will default to 30s. A zero duration disables the
750    /// deadline.
751    #[serde(default = "TonicParameters::default_subscribe_request_timeout")]
752    pub subscribe_request_timeout: Duration,
753}
754
755impl TonicParameters {
756    /// Hard size limit for request messages, `message_size_limit` when
757    /// `max_request_message_size` is `0`.
758    pub fn request_message_size_limit(&self) -> usize {
759        if self.max_request_message_size == 0 {
760            self.message_size_limit
761        } else {
762            self.max_request_message_size
763        }
764    }
765
766    fn default_keepalive_interval() -> Duration {
767        Duration::from_secs(5)
768    }
769
770    fn default_connection_buffer_size() -> usize {
771        32 << 20
772    }
773
774    fn default_excessive_message_size() -> usize {
775        16 << 20
776    }
777
778    fn default_message_size_limit() -> usize {
779        64 << 20
780    }
781
782    fn default_max_concurrent_streams() -> u32 {
783        64
784    }
785
786    fn default_request_timeout() -> Duration {
787        Duration::from_secs(120)
788    }
789
790    fn default_max_request_message_size() -> usize {
791        1 << 20
792    }
793
794    fn default_subscribe_request_timeout() -> Duration {
795        Duration::from_secs(30)
796    }
797}
798
799impl Default for TonicParameters {
800    fn default() -> Self {
801        Self {
802            keepalive_interval: TonicParameters::default_keepalive_interval(),
803            connection_buffer_size: TonicParameters::default_connection_buffer_size(),
804            excessive_message_size: TonicParameters::default_excessive_message_size(),
805            message_size_limit: TonicParameters::default_message_size_limit(),
806            max_concurrent_streams: TonicParameters::default_max_concurrent_streams(),
807            request_timeout: TonicParameters::default_request_timeout(),
808            max_request_message_size: TonicParameters::default_max_request_message_size(),
809            admission: AdmissionParameters::default(),
810            subscribe_request_timeout: TonicParameters::default_subscribe_request_timeout(),
811        }
812    }
813}
814
815/// Per-peer, per-RPC concurrency caps for the inbound consensus gRPC server.
816///
817/// Each per-peer cap bounds how many concurrent requests of one RPC group a
818/// single committee peer (keyed on its authenticated authority index) may have
819/// in flight; a peer cannot consume another peer's budget. Commit fetches also
820/// have a node-wide cap, `max_commit_fetches_total`. These are local,
821/// non-protocol parameters — heterogeneous values across authorities are safe,
822/// so they can be rolled out and tuned per node.
823///
824/// The defaults are sized for ~100-validator committees and the local
825/// synchronizer fan-out toward one server. `0` turns a cap off; each cap is
826/// checked on its own.
827#[derive(Clone, Debug, Deserialize, Serialize)]
828pub struct AdmissionParameters {
829    /// Max concurrent block-subscription streams per peer.
830    ///
831    /// If unspecified, this will default to 2.
832    #[serde(default = "AdmissionParameters::default_max_subscriptions_per_peer")]
833    pub max_subscriptions_per_peer: u32,
834
835    /// Max concurrent header fetches per peer
836    /// (`fetch_block_headers` + `fetch_latest_block_headers`).
837    ///
838    /// If unspecified, this will default to 32.
839    #[serde(default = "AdmissionParameters::default_max_header_fetches_per_peer")]
840    pub max_header_fetches_per_peer: u32,
841
842    /// Max concurrent transaction fetches per peer (`fetch_transactions`).
843    ///
844    /// If unspecified, this will default to 16.
845    #[serde(default = "AdmissionParameters::default_max_transaction_fetches_per_peer")]
846    pub max_transaction_fetches_per_peer: u32,
847
848    /// Max concurrent commit fetches per peer
849    /// (`fetch_commits` + `fetch_commits_and_transactions`).
850    ///
851    /// If unspecified, this will default to 8.
852    #[serde(default = "AdmissionParameters::default_max_commit_fetches_per_peer")]
853    pub max_commit_fetches_per_peer: u32,
854
855    /// Max concurrent commit fetches across all peers, not counting each
856    /// peer's first one, which is always granted. A fast commit-sync response
857    /// holds its commits and certifier headers until it has been sent, and
858    /// reads its transactions from the store while it is being sent, so this
859    /// caps what serving them can cost the node at once, beyond one response
860    /// per peer.
861    ///
862    /// If unspecified, this will default to 16.
863    #[serde(default = "AdmissionParameters::default_max_commit_fetches_total")]
864    pub max_commit_fetches_total: u32,
865}
866
867impl AdmissionParameters {
868    fn default_max_subscriptions_per_peer() -> u32 {
869        2
870    }
871
872    fn default_max_header_fetches_per_peer() -> u32 {
873        32
874    }
875
876    fn default_max_transaction_fetches_per_peer() -> u32 {
877        16
878    }
879
880    fn default_max_commit_fetches_per_peer() -> u32 {
881        Parameters::default_commit_sync_parallel_fetches() as u32
882    }
883
884    fn default_max_commit_fetches_total() -> u32 {
885        2 * AdmissionParameters::default_max_commit_fetches_per_peer()
886    }
887}
888
889impl Default for AdmissionParameters {
890    fn default() -> Self {
891        Self {
892            max_subscriptions_per_peer: AdmissionParameters::default_max_subscriptions_per_peer(),
893            max_header_fetches_per_peer: AdmissionParameters::default_max_header_fetches_per_peer(),
894            max_transaction_fetches_per_peer:
895                AdmissionParameters::default_max_transaction_fetches_per_peer(),
896            max_commit_fetches_per_peer: AdmissionParameters::default_max_commit_fetches_per_peer(),
897            max_commit_fetches_total: AdmissionParameters::default_max_commit_fetches_total(),
898        }
899    }
900}