Skip to main content

iota_config/
p2p.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::{
6    net::SocketAddr,
7    num::{NonZeroU32, NonZeroU64},
8    time::Duration,
9};
10
11use iota_multiaddr::Multiaddr;
12use iota_sdk_types::CheckpointDigest;
13use iota_types::messages_checkpoint::CheckpointSequenceNumber;
14use serde::{Deserialize, Serialize};
15
16#[derive(Clone, Debug, Deserialize, Serialize)]
17#[serde(rename_all = "kebab-case")]
18pub struct P2pConfig {
19    /// The address that the p2p network will bind on.
20    #[serde(default = "default_listen_address")]
21    pub listen_address: SocketAddr,
22    /// The external address other nodes can use to reach this node.
23    /// This will be shared with other peers through the discovery service
24    #[serde(skip_serializing_if = "Option::is_none")]
25    pub external_address: Option<Multiaddr>,
26    /// SeedPeers are preferred and the node will always try to ensure a
27    /// connection is established with these nodes.
28    #[serde(skip_serializing_if = "Vec::is_empty", default)]
29    pub seed_peers: Vec<SeedPeer>,
30    #[serde(skip_serializing_if = "Option::is_none")]
31    pub anemo_config: Option<anemo::Config>,
32    #[serde(skip_serializing_if = "Option::is_none")]
33    pub state_sync: Option<StateSyncConfig>,
34    #[serde(skip_serializing_if = "Option::is_none")]
35    pub discovery: Option<DiscoveryConfig>,
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub randomness: Option<RandomnessConfig>,
38    /// Size in bytes above which network messages are considered excessively
39    /// large. Excessively large messages will still be handled, but logged
40    /// and reported in metrics for debugging.
41    ///
42    /// If unspecified, this will default to 8 MiB.
43    #[serde(skip_serializing_if = "Option::is_none")]
44    pub excessive_message_size: Option<usize>,
45}
46
47fn default_listen_address() -> SocketAddr {
48    "0.0.0.0:8084".parse().unwrap()
49}
50
51impl Default for P2pConfig {
52    fn default() -> Self {
53        Self {
54            listen_address: default_listen_address(),
55            external_address: Default::default(),
56            seed_peers: Default::default(),
57            anemo_config: Default::default(),
58            state_sync: None,
59            discovery: None,
60            randomness: None,
61            excessive_message_size: None,
62        }
63    }
64}
65
66impl P2pConfig {
67    pub fn excessive_message_size(&self) -> usize {
68        const EXCESSIVE_MESSAGE_SIZE: usize = 32 << 20;
69
70        self.excessive_message_size
71            .unwrap_or(EXCESSIVE_MESSAGE_SIZE)
72    }
73
74    pub fn set_discovery_config(mut self, discovery_config: DiscoveryConfig) -> Self {
75        self.discovery = Some(discovery_config);
76        self
77    }
78}
79
80#[derive(Clone, Debug, Deserialize, Serialize)]
81#[serde(rename_all = "kebab-case")]
82pub struct SeedPeer {
83    #[serde(skip_serializing_if = "Option::is_none")]
84    pub peer_id: Option<anemo::PeerId>,
85    pub address: Multiaddr,
86}
87
88#[derive(Clone, Debug, Deserialize, Serialize)]
89#[serde(rename_all = "kebab-case")]
90pub struct AllowlistedPeer {
91    pub peer_id: anemo::PeerId,
92    #[serde(skip_serializing_if = "Option::is_none")]
93    pub address: Option<Multiaddr>,
94}
95
96#[derive(Clone, Debug, Default, Deserialize, Serialize)]
97#[serde(rename_all = "kebab-case")]
98pub struct StateSyncConfig {
99    /// List of "known-good" checkpoints that state sync will be forced to use.
100    /// State sync will skip verification of pinned checkpoints, and reject
101    /// checkpoints with digests that don't match pinned values for a given
102    /// sequence number.
103    ///
104    /// This can be used:
105    /// - in case of a fork, to prevent the node from syncing to the wrong chain.
106    /// - in case of a network stall, to force the node to proceed with a manually-injected
107    ///   checkpoint.
108    #[serde(skip_serializing_if = "Vec::is_empty", default)]
109    pub pinned_checkpoints: Vec<(CheckpointSequenceNumber, CheckpointDigest)>,
110
111    /// Query peers for their latest checkpoint every interval period.
112    ///
113    /// If unspecified, this will default to `5,000` milliseconds.
114    #[serde(skip_serializing_if = "Option::is_none")]
115    pub interval_period_ms: Option<u64>,
116
117    /// Size of the StateSync actor's mailbox.
118    ///
119    /// If unspecified, this will default to `1,024`.
120    #[serde(skip_serializing_if = "Option::is_none")]
121    pub mailbox_capacity: Option<usize>,
122
123    /// Size of the broadcast channel use for notifying other systems of newly
124    /// sync'ed checkpoints.
125    ///
126    /// If unspecified, this will default to `1,024`.
127    #[serde(skip_serializing_if = "Option::is_none")]
128    pub synced_checkpoint_broadcast_channel_capacity: Option<usize>,
129
130    /// Set the upper bound on the number of checkpoint headers to be downloaded
131    /// concurrently.
132    ///
133    /// If unspecified, this will default to `400`.
134    #[serde(skip_serializing_if = "Option::is_none")]
135    pub checkpoint_header_download_concurrency: Option<usize>,
136
137    /// Set the upper bound on the number of checkpoint contents to be
138    /// downloaded concurrently.
139    ///
140    /// If unspecified, this will default to `400`.
141    #[serde(skip_serializing_if = "Option::is_none")]
142    pub checkpoint_content_download_concurrency: Option<usize>,
143
144    /// Set the upper bound on the number of individual transactions contained
145    /// in checkpoint contents to be downloaded concurrently. This limit
146    /// applies in addition to `checkpoint_content_download_concurrency`. A
147    /// checkpoint with more transactions than this value is still downloaded
148    /// when no other checkpoint contents are being downloaded, so this one
149    /// checkpoint can go over the bound.
150    ///
151    /// If unspecified, this will default to `50,000`.
152    #[serde(skip_serializing_if = "Option::is_none")]
153    pub checkpoint_content_download_tx_concurrency: Option<u64>,
154
155    /// Set the timeout that should be used when sending most state-sync RPC
156    /// requests.
157    ///
158    /// If unspecified, this will default to `10,000` milliseconds.
159    #[serde(skip_serializing_if = "Option::is_none")]
160    pub timeout_ms: Option<u64>,
161
162    /// Set the timeout that should be used when sending RPC requests to sync
163    /// checkpoint contents.
164    ///
165    /// If unspecified, this will default to `10,000` milliseconds.
166    #[serde(skip_serializing_if = "Option::is_none")]
167    pub checkpoint_content_timeout_ms: Option<u64>,
168
169    /// Per-peer rate-limit (in requests/sec) for the PushCheckpointSummary RPC.
170    ///
171    /// If unspecified, this will default to no limit.
172    #[serde(skip_serializing_if = "Option::is_none")]
173    pub push_checkpoint_summary_rate_limit: Option<NonZeroU32>,
174
175    /// Per-peer rate-limit (in requests/sec) for the GetCheckpointSummary RPC.
176    ///
177    /// If unspecified, this will default to no limit.
178    #[serde(skip_serializing_if = "Option::is_none")]
179    pub get_checkpoint_summary_rate_limit: Option<NonZeroU32>,
180
181    /// Per-peer rate-limit (in requests/sec) for the GetCheckpointContents RPC.
182    ///
183    /// If unspecified, this will default to no limit.
184    #[serde(skip_serializing_if = "Option::is_none")]
185    pub get_checkpoint_contents_rate_limit: Option<NonZeroU32>,
186
187    /// Per-peer inflight limit for the GetCheckpointContents RPC.
188    ///
189    /// If unspecified, this will default to no limit.
190    #[serde(skip_serializing_if = "Option::is_none")]
191    pub get_checkpoint_contents_inflight_limit: Option<usize>,
192
193    /// Per-checkpoint inflight limit for the GetCheckpointContents RPC. This is
194    /// enforced globally across all peers.
195    ///
196    /// If unspecified, this will default to no limit.
197    #[serde(skip_serializing_if = "Option::is_none")]
198    pub get_checkpoint_contents_per_checkpoint_limit: Option<usize>,
199
200    /// The amount of time to wait before retry if there are no peers to sync
201    /// content from. If unspecified, this will set to default value
202    #[serde(skip_serializing_if = "Option::is_none")]
203    pub wait_interval_when_no_peer_to_sync_content_ms: Option<u64>,
204
205    /// Stop syncing checkpoints more than this many above the executed
206    /// watermark, and resume as execution catches up. Bounds the disk space
207    /// held by checkpoints that are synced but not yet executed, since only
208    /// executed checkpoints can be pruned. Applies to checkpoint summaries and
209    /// contents, and to sync from peers and from the checkpoint archive
210    /// alike.
211    ///
212    /// If unspecified, this will default to `100,000`.
213    #[serde(skip_serializing_if = "Option::is_none")]
214    pub max_checkpoints_ahead_of_execution: Option<NonZeroU64>,
215
216    /// Maximum lookahead (in checkpoint sequence numbers) above the highest
217    /// verified checkpoint for storing unverified checkpoint summaries
218    /// received from peers. Summaries further ahead are fetched again once
219    /// state sync reaches them.
220    ///
221    /// If unspecified, this will default to `1,000`.
222    #[serde(skip_serializing_if = "Option::is_none")]
223    pub max_checkpoint_lookahead: Option<NonZeroU64>,
224
225    /// Maximum size in bytes of a request to any state sync RPC as received,
226    /// and of a checkpoint summary from a peer once decompressed. Larger
227    /// requests are rejected, and larger summaries are neither stored nor
228    /// synced from peers, so this must stay above the size of the largest
229    /// real summary.
230    ///
231    /// If unspecified, this will default to `262,144` (256 KiB). Must be at
232    /// least [`MIN_CHECKPOINT_SUMMARY_SIZE`].
233    #[serde(skip_serializing_if = "Option::is_none")]
234    pub max_checkpoint_summary_size: Option<usize>,
235}
236
237/// The smallest accepted `max-checkpoint-summary-size`.
238// The handshake carries two summaries, and an end-of-epoch summary for a
239// committee of 100 members is about 11 KiB.
240pub const MIN_CHECKPOINT_SUMMARY_SIZE: usize = 64 * 1024;
241
242impl StateSyncConfig {
243    pub fn interval_period(&self) -> Duration {
244        const INTERVAL_PERIOD_MS: u64 = 5_000; // 5 seconds
245
246        Duration::from_millis(self.interval_period_ms.unwrap_or(INTERVAL_PERIOD_MS))
247    }
248
249    pub fn mailbox_capacity(&self) -> usize {
250        const MAILBOX_CAPACITY: usize = 1_024;
251
252        self.mailbox_capacity.unwrap_or(MAILBOX_CAPACITY)
253    }
254
255    pub fn synced_checkpoint_broadcast_channel_capacity(&self) -> usize {
256        const SYNCED_CHECKPOINT_BROADCAST_CHANNEL_CAPACITY: usize = 1_024;
257
258        self.synced_checkpoint_broadcast_channel_capacity
259            .unwrap_or(SYNCED_CHECKPOINT_BROADCAST_CHANNEL_CAPACITY)
260    }
261
262    pub fn checkpoint_header_download_concurrency(&self) -> usize {
263        const CHECKPOINT_HEADER_DOWNLOAD_CONCURRENCY: usize = 400;
264
265        self.checkpoint_header_download_concurrency
266            .unwrap_or(CHECKPOINT_HEADER_DOWNLOAD_CONCURRENCY)
267    }
268
269    pub fn checkpoint_content_download_concurrency(&self) -> usize {
270        const CHECKPOINT_CONTENT_DOWNLOAD_CONCURRENCY: usize = 400;
271
272        self.checkpoint_content_download_concurrency
273            .unwrap_or(CHECKPOINT_CONTENT_DOWNLOAD_CONCURRENCY)
274    }
275
276    pub fn checkpoint_content_download_tx_concurrency(&self) -> u64 {
277        const CHECKPOINT_CONTENT_DOWNLOAD_TX_CONCURRENCY: u64 = 50_000;
278
279        self.checkpoint_content_download_tx_concurrency
280            .unwrap_or(CHECKPOINT_CONTENT_DOWNLOAD_TX_CONCURRENCY)
281    }
282
283    pub fn timeout(&self) -> Duration {
284        const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
285
286        self.timeout_ms
287            .map(Duration::from_millis)
288            .unwrap_or(DEFAULT_TIMEOUT)
289    }
290
291    pub fn checkpoint_content_timeout(&self) -> Duration {
292        const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60);
293
294        self.checkpoint_content_timeout_ms
295            .map(Duration::from_millis)
296            .unwrap_or(DEFAULT_TIMEOUT)
297    }
298
299    pub fn max_checkpoints_ahead_of_execution(&self) -> u64 {
300        const MAX_CHECKPOINTS_AHEAD_OF_EXECUTION: u64 = 100_000;
301
302        self.max_checkpoints_ahead_of_execution
303            .map(NonZeroU64::get)
304            .unwrap_or(MAX_CHECKPOINTS_AHEAD_OF_EXECUTION)
305    }
306
307    pub fn max_checkpoint_lookahead(&self) -> u64 {
308        const DEFAULT_MAX_CHECKPOINT_LOOKAHEAD: u64 = 1_000;
309
310        self.max_checkpoint_lookahead
311            .map(NonZeroU64::get)
312            .unwrap_or(DEFAULT_MAX_CHECKPOINT_LOOKAHEAD)
313    }
314
315    pub fn max_checkpoint_summary_size(&self) -> usize {
316        const DEFAULT_MAX_CHECKPOINT_SUMMARY_SIZE: usize = 256 * 1024;
317
318        self.max_checkpoint_summary_size
319            .unwrap_or(DEFAULT_MAX_CHECKPOINT_SUMMARY_SIZE)
320    }
321
322    pub fn wait_interval_when_no_peer_to_sync_content(&self) -> Duration {
323        self.wait_interval_when_no_peer_to_sync_content_ms
324            .map(Duration::from_millis)
325            .unwrap_or(self.default_wait_interval_when_no_peer_to_sync_content())
326    }
327
328    fn default_wait_interval_when_no_peer_to_sync_content(&self) -> Duration {
329        if cfg!(msim) {
330            Duration::from_secs(5)
331        } else {
332            Duration::from_secs(10)
333        }
334    }
335
336    pub fn randomized_for_testing() -> Self {
337        use rand::RngExt;
338        let mut rng = rand::rng();
339        let config = Self {
340            mailbox_capacity: Some(rng.random_range(16..=2048)),
341            synced_checkpoint_broadcast_channel_capacity: Some(rng.random_range(16..=2048)),
342            checkpoint_header_download_concurrency: Some(rng.random_range(10..=500)),
343            checkpoint_content_download_concurrency: Some(rng.random_range(10..=500)),
344            ..Default::default()
345        };
346        tracing::info!(
347            mailbox_capacity = config.mailbox_capacity.unwrap(),
348            broadcast_capacity = config.synced_checkpoint_broadcast_channel_capacity.unwrap(),
349            header_concurrency = config.checkpoint_header_download_concurrency.unwrap(),
350            content_concurrency = config.checkpoint_content_download_concurrency.unwrap(),
351            "StateSyncConfig::randomized_for_testing"
352        );
353        config
354    }
355}
356
357/// Access Type of a node.
358/// AccessType info is shared in the discovery process.
359/// * If the node marks itself as Public, other nodes may try to connect to it.
360/// * If the node marks itself as Private, only nodes that have it in their `allowlisted_peers` or
361///   `seed_peers` will try to connect to it.
362/// * If not set, defaults to Public.
363///
364/// AccessType is useful when a network of nodes want to stay private. To
365/// achieve this, mark every node in this network as `Private` and
366/// allowlist/seed them to each other.
367#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
368pub enum AccessType {
369    Public,
370    Private,
371}
372
373#[derive(Clone, Debug, Default, Deserialize, Serialize)]
374#[serde(rename_all = "kebab-case")]
375pub struct DiscoveryConfig {
376    /// Query peers for their latest checkpoint every interval period.
377    ///
378    /// If unspecified, this will default to `5,000` milliseconds.
379    #[serde(skip_serializing_if = "Option::is_none")]
380    pub interval_period_ms: Option<u64>,
381
382    /// Target number of concurrent connections to establish.
383    ///
384    /// If unspecified, this will default to `4`.
385    #[serde(skip_serializing_if = "Option::is_none")]
386    pub target_concurrent_connections: Option<usize>,
387
388    /// Number of peers to query each interval.
389    ///
390    /// Sets the number of peers, to be randomly selected, that are queried for
391    /// their known peers each interval.
392    ///
393    /// If unspecified, this will default to `1`.
394    #[serde(skip_serializing_if = "Option::is_none")]
395    pub peers_to_query: Option<usize>,
396
397    /// Maximum number of peers kept in the discovery table of known peers.
398    ///
399    /// When the table grows past this number, the peers with the oldest
400    /// timestamps are removed first.
401    ///
402    /// If unspecified, this will default to `10,000`.
403    #[serde(skip_serializing_if = "Option::is_none")]
404    pub max_known_peers: Option<usize>,
405
406    /// Timeout for individual peer query requests in discovery protocol.
407    ///
408    /// If unspecified, this will default to `1` second.
409    #[serde(skip_serializing_if = "Option::is_none")]
410    pub peer_query_timeout_sec: Option<u64>,
411
412    /// Per-peer rate-limit (in requests/sec) for the GetKnownPeers RPC.
413    ///
414    /// If unspecified, this will default to no limit.
415    #[serde(skip_serializing_if = "Option::is_none")]
416    pub get_known_peers_rate_limit: Option<NonZeroU32>,
417
418    /// See docstring for `AccessType`.
419    #[serde(skip_serializing_if = "Option::is_none")]
420    pub access_type: Option<AccessType>,
421
422    /// Like `seed_peers` in `P2pConfig`, allowlisted peers will always be
423    /// allowed to establish connection with this node regardless of the
424    /// concurrency limit. Unlike `seed_peers`, a node does not reach out to
425    /// `allowlisted_peers` preferentially. It is also used to determine if
426    /// a peer is accessible when its AccessType is Private. For example, a
427    /// node will ignore a peer with Private AccessType if the peer is not in
428    /// its `allowlisted_peers`. Namely, the node will not try to establish
429    /// connections to this peer, nor advertise this peer's info to other
430    /// peers in the network.
431    #[serde(skip_serializing_if = "Vec::is_empty", default)]
432    pub allowlisted_peers: Vec<AllowlistedPeer>,
433
434    /// Maximum number of concurrent address verification attempts.
435    /// This prevents overwhelming the network when verifying many peers at
436    /// once.
437    ///
438    /// If unspecified, this will default to `10`.
439    #[serde(skip_serializing_if = "Option::is_none")]
440    pub max_concurrent_address_verifications: Option<usize>,
441
442    /// Timeout for individual address verification attempts.
443    ///
444    /// If unspecified, this will default to `3` seconds.
445    #[serde(skip_serializing_if = "Option::is_none")]
446    pub address_verification_timeout_sec: Option<u64>,
447
448    /// Total timeout for all address verification attempts to prevent DoS
449    /// attacks.
450    ///
451    /// If unspecified, this will default to `8` seconds.
452    #[serde(skip_serializing_if = "Option::is_none")]
453    pub address_verification_total_timeout_sec: Option<u64>,
454
455    /// Cooldown period in seconds for peers whose address verification failed.
456    /// During this period, new peer info from the same peer will be ignored.
457    /// Set to 0 to disable the cooldown feature entirely.
458    ///
459    /// If unspecified, this will default to `600` seconds (10 minutes).
460    #[serde(skip_serializing_if = "Option::is_none")]
461    pub address_verification_failure_cooldown_sec: Option<u64>,
462
463    /// Interval for cleaning up old entries from the verification failure
464    /// cooldown list.
465    ///
466    /// If unspecified, this will default to `300` seconds (5 minutes).
467    #[serde(skip_serializing_if = "Option::is_none")]
468    pub cooldown_cleanup_interval_sec: Option<u64>,
469
470    /// Whether to allow private IP and local DNS addresses (e.g., 192.168.0.1,
471    /// localhost, .local) when verifying peer addresses.
472    #[serde(skip_serializing_if = "Option::is_none")]
473    pub allow_private_addresses: Option<bool>,
474}
475
476impl DiscoveryConfig {
477    pub fn interval_period(&self) -> Duration {
478        const INTERVAL_PERIOD_MS: u64 = 10_000; // 10 seconds
479
480        Duration::from_millis(self.interval_period_ms.unwrap_or(INTERVAL_PERIOD_MS))
481    }
482
483    pub fn target_concurrent_connections(&self) -> usize {
484        const TARGET_CONCURRENT_CONNECTIONS: usize = 4;
485
486        self.target_concurrent_connections
487            .unwrap_or(TARGET_CONCURRENT_CONNECTIONS)
488    }
489
490    pub fn peers_to_query(&self) -> usize {
491        const PEERS_TO_QUERY: usize = 1;
492
493        self.peers_to_query.unwrap_or(PEERS_TO_QUERY)
494    }
495
496    pub fn max_known_peers(&self) -> usize {
497        const MAX_KNOWN_PEERS: usize = 10_000;
498
499        self.max_known_peers.unwrap_or(MAX_KNOWN_PEERS)
500    }
501
502    pub fn peer_query_timeout(&self) -> Duration {
503        const PEER_QUERY_TIMEOUT_SEC: u64 = 1;
504
505        Duration::from_secs(
506            self.peer_query_timeout_sec
507                .unwrap_or(PEER_QUERY_TIMEOUT_SEC),
508        )
509    }
510
511    pub fn access_type(&self) -> AccessType {
512        // defaults None to Public
513        self.access_type.unwrap_or(AccessType::Public)
514    }
515
516    pub fn max_concurrent_address_verifications(&self) -> usize {
517        const MAX_CONCURRENT_ADDRESS_VERIFICATIONS: usize = 10;
518
519        self.max_concurrent_address_verifications
520            .unwrap_or(MAX_CONCURRENT_ADDRESS_VERIFICATIONS)
521    }
522
523    pub fn address_verification_timeout(&self) -> Duration {
524        const ADDRESS_VERIFICATION_TIMEOUT_SEC: u64 = 3;
525
526        Duration::from_secs(
527            self.address_verification_timeout_sec
528                .unwrap_or(ADDRESS_VERIFICATION_TIMEOUT_SEC),
529        )
530    }
531
532    pub fn address_verification_total_timeout(&self) -> Duration {
533        const ADDRESS_VERIFICATION_TOTAL_TIMEOUT_SEC: u64 = 8;
534
535        Duration::from_secs(
536            self.address_verification_total_timeout_sec
537                .unwrap_or(ADDRESS_VERIFICATION_TOTAL_TIMEOUT_SEC),
538        )
539    }
540
541    pub fn address_verification_failure_cooldown(&self) -> Duration {
542        const ADDRESS_VERIFICATION_FAILURE_COOLDOWN_SEC: u64 = 600; // 10 minutes
543
544        Duration::from_secs(
545            self.address_verification_failure_cooldown_sec
546                .unwrap_or(ADDRESS_VERIFICATION_FAILURE_COOLDOWN_SEC),
547        )
548    }
549
550    pub fn cooldown_cleanup_interval(&self) -> Duration {
551        const COOLDOWN_CLEANUP_INTERVAL_SEC: u64 = 300; // 5 minutes
552
553        Duration::from_secs(
554            self.cooldown_cleanup_interval_sec
555                .unwrap_or(COOLDOWN_CLEANUP_INTERVAL_SEC),
556        )
557    }
558
559    /// Returns true if address verification cooldown is enabled (cooldown > 0)
560    pub fn is_address_verification_cooldown_enabled(&self) -> bool {
561        self.address_verification_failure_cooldown_sec
562            .unwrap_or(600)
563            > 0
564    }
565
566    /// Whether to allow private IP and local DNS addresses (e.g., 192.168.0.1,
567    /// localhost, .local) when verifying peer addresses.
568    pub fn allow_private_addresses(&self) -> bool {
569        self.allow_private_addresses.unwrap_or(false)
570    }
571}
572
573#[derive(Clone, Debug, Default, Deserialize, Serialize)]
574#[serde(rename_all = "kebab-case")]
575pub struct RandomnessConfig {
576    /// Maximum number of rounds ahead of our most recent completed round for
577    /// which we should accept partial signatures from other validators.
578    ///
579    /// If unspecified, this will default to 50.
580    #[serde(skip_serializing_if = "Option::is_none")]
581    pub max_partial_sigs_rounds_ahead: Option<u64>,
582
583    /// Maximum number of rounds for which partial signatures should be
584    /// concurrently sent.
585    ///
586    /// If unspecified, this will default to 20.
587    #[serde(skip_serializing_if = "Option::is_none")]
588    pub max_partial_sigs_concurrent_sends: Option<usize>,
589
590    /// Interval at which to retry sending partial signatures until the round is
591    /// complete.
592    ///
593    /// If unspecified, this will default to `5,000` milliseconds.
594    #[serde(skip_serializing_if = "Option::is_none")]
595    pub partial_signature_retry_interval_ms: Option<u64>,
596
597    /// Size of the Randomness actor's mailbox for the node's own messages. This
598    /// should be set large enough to never overflow unless a bug is
599    /// encountered.
600    ///
601    /// If unspecified, this will default to `1,000,000`.
602    #[serde(skip_serializing_if = "Option::is_none")]
603    pub mailbox_capacity: Option<usize>,
604
605    /// Size of the Randomness actor's mailbox for signatures received from
606    /// peers. Requests that arrive while it is full are rejected, and the peer
607    /// retries them.
608    ///
609    /// If unspecified, this will default to `10,000`.
610    #[serde(skip_serializing_if = "Option::is_none")]
611    pub peer_mailbox_capacity: Option<usize>,
612
613    /// Maximum number of requests from one peer that may wait in the peer
614    /// mailbox. Further requests from that peer are rejected, and the peer
615    /// retries them.
616    ///
617    /// If unspecified, this will default to 40.
618    #[serde(skip_serializing_if = "Option::is_none")]
619    pub max_queued_requests_per_peer: Option<usize>,
620
621    /// Per-peer inflight limit for the SendPartialSignatures RPC.
622    ///
623    /// If unspecified, this will default to 20.
624    #[serde(skip_serializing_if = "Option::is_none")]
625    pub send_partial_signatures_inflight_limit: Option<usize>,
626
627    /// Maximum proportion of total peer weight to ignore in case of byzantine
628    /// behavior.
629    ///
630    /// If unspecified, this will default to 0.2.
631    #[serde(skip_serializing_if = "Option::is_none")]
632    pub max_ignored_peer_weight_factor: Option<f64>,
633}
634
635impl RandomnessConfig {
636    pub fn max_partial_sigs_rounds_ahead(&self) -> u64 {
637        const MAX_PARTIAL_SIGS_ROUNDS_AHEAD: u64 = 50;
638
639        self.max_partial_sigs_rounds_ahead
640            .unwrap_or(MAX_PARTIAL_SIGS_ROUNDS_AHEAD)
641    }
642
643    pub fn max_partial_sigs_concurrent_sends(&self) -> usize {
644        const MAX_PARTIAL_SIGS_CONCURRENT_SENDS: usize = 20;
645
646        self.max_partial_sigs_concurrent_sends
647            .unwrap_or(MAX_PARTIAL_SIGS_CONCURRENT_SENDS)
648    }
649    pub fn partial_signature_retry_interval(&self) -> Duration {
650        const PARTIAL_SIGNATURE_RETRY_INTERVAL: u64 = 5_000; // 5 seconds
651
652        Duration::from_millis(
653            self.partial_signature_retry_interval_ms
654                .unwrap_or(PARTIAL_SIGNATURE_RETRY_INTERVAL),
655        )
656    }
657
658    pub fn mailbox_capacity(&self) -> usize {
659        const MAILBOX_CAPACITY: usize = 1_000_000;
660
661        self.mailbox_capacity.unwrap_or(MAILBOX_CAPACITY)
662    }
663
664    pub fn peer_mailbox_capacity(&self) -> usize {
665        const PEER_MAILBOX_CAPACITY: usize = 10_000;
666
667        self.peer_mailbox_capacity.unwrap_or(PEER_MAILBOX_CAPACITY)
668    }
669
670    pub fn max_queued_requests_per_peer(&self) -> usize {
671        const MAX_QUEUED_REQUESTS_PER_PEER: usize = 40;
672
673        self.max_queued_requests_per_peer
674            .unwrap_or(MAX_QUEUED_REQUESTS_PER_PEER)
675    }
676
677    pub fn send_partial_signatures_inflight_limit(&self) -> usize {
678        const SEND_PARTIAL_SIGNATURES_INFLIGHT_LIMIT: usize = 20;
679
680        self.send_partial_signatures_inflight_limit
681            .unwrap_or(SEND_PARTIAL_SIGNATURES_INFLIGHT_LIMIT)
682    }
683
684    pub fn max_ignored_peer_weight_factor(&self) -> f64 {
685        const MAX_IGNORED_PEER_WEIGHT_FACTOR: f64 = 0.2;
686
687        self.max_ignored_peer_weight_factor
688            .unwrap_or(MAX_IGNORED_PEER_WEIGHT_FACTOR)
689    }
690}