Skip to main content

iota_config/
node.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::{IpAddr, Ipv4Addr, SocketAddr},
7    num::NonZeroUsize,
8    path::{Path, PathBuf},
9    sync::Arc,
10    time::Duration,
11};
12
13use anyhow::Result;
14use iota_keys::keypair_file::{read_authority_keypair_from_file, read_keypair_from_file};
15use iota_metrics::MetricGroups;
16use iota_names::config::IotaNamesConfig;
17use iota_sdk_types::Address;
18use iota_types::{
19    committee::EpochId,
20    crypto::{
21        AccountKeyPair, AuthorityKeyPair, AuthorityPublicKeyBytes, IotaKeyPair, KeypairTraits,
22        NetworkKeyPair, get_key_pair_from_rng,
23    },
24    messages_checkpoint::CheckpointSequenceNumber,
25    multiaddr::Multiaddr,
26    supported_protocol_versions::{Chain, SupportedProtocolVersions},
27    traffic_control::{PolicyConfig, RemoteFirewallConfig},
28};
29use once_cell::sync::OnceCell;
30use rand::rngs::OsRng;
31use serde::{Deserialize, Serialize};
32use starfish_config::Parameters as StarfishParameters;
33use tracing::info;
34
35use crate::{
36    Config, certificate_deny_config::CertificateDenyConfig, genesis,
37    migration_tx_data::MigrationTxData, object_storage_config::ObjectStoreConfig, p2p::P2pConfig,
38    transaction_deny_config::TransactionDenyConfig, verifier_signing_config::VerifierSigningConfig,
39};
40
41// Default max number of concurrent requests served
42pub const DEFAULT_GRPC_CONCURRENCY_LIMIT: usize = 20000000000;
43
44/// Default gas price of 1000 Nanos
45pub const DEFAULT_VALIDATOR_GAS_PRICE: u64 = iota_types::transaction::DEFAULT_VALIDATOR_GAS_PRICE;
46
47/// Default commission rate of 2%
48pub const DEFAULT_COMMISSION_RATE: u64 = 200;
49
50/// Default budget in MiB for the in-memory full-checkpoint-contents cache.
51pub const DEFAULT_FULL_CHECKPOINT_CONTENTS_CACHE_SIZE_MB: usize = 1024;
52
53#[derive(Clone, Debug, Deserialize, Serialize)]
54#[serde(rename_all = "kebab-case")]
55pub struct NodeConfig {
56    /// The public key bytes corresponding to the private key that the validator
57    /// holds to sign transactions.
58    #[serde(default = "default_authority_key_pair")]
59    pub authority_key_pair: AuthorityKeyPairWithPath,
60    /// The public key bytes corresponding to the private key that the validator
61    /// holds to sign consensus blocks.
62    #[serde(default = "default_key_pair")]
63    pub protocol_key_pair: KeyPairWithPath,
64    #[serde(default = "default_key_pair")]
65    pub account_key_pair: KeyPairWithPath,
66    /// The public key bytes corresponding to the private key that the validator
67    /// uses to establish TLS connections.
68    #[serde(default = "default_key_pair")]
69    pub network_key_pair: KeyPairWithPath,
70    pub db_path: PathBuf,
71
72    /// The network address for gRPC communication.
73    ///
74    /// Can be overwritten with args `listen-address` parameters.
75    #[serde(default = "default_grpc_address")]
76    pub network_address: Multiaddr,
77    #[serde(default = "default_json_rpc_address")]
78    pub json_rpc_address: SocketAddr,
79
80    /// The address for Prometheus metrics.
81    #[serde(default = "default_metrics_address")]
82    pub metrics_address: SocketAddr,
83
84    /// The address for the admin interface that is
85    /// run in the metrics separate runtime and provides access to
86    /// admin node commands such as logging and tracing options.
87    #[serde(default = "default_admin_interface_address")]
88    pub admin_interface_address: SocketAddr,
89
90    /// Configuration struct for the consensus.
91    #[serde(skip_serializing_if = "Option::is_none")]
92    pub consensus_config: Option<ConsensusConfig>,
93
94    /// Flag to enable index processing for a full node.
95    ///
96    /// If set to true, node creates `IndexStore` for transaction
97    /// data including ownership and balance information.
98    #[serde(default = "default_enable_index_processing")]
99    pub enable_index_processing: bool,
100
101    // only allow websocket connections for jsonrpc traffic
102    #[serde(default)]
103    /// Determines the jsonrpc server type as either:
104    /// - 'websocket' for a websocket based service (deprecated)
105    /// - 'http' for an http based service
106    /// - 'both' for both a websocket and http based service (deprecated)
107    pub jsonrpc_server_type: Option<ServerType>,
108
109    /// Flag to enable gRPC load shedding to manage and
110    /// mitigate overload conditions by shedding excess
111    /// load with `LoadShedLayer` middleware.
112    #[serde(default)]
113    pub grpc_load_shed: Option<bool>,
114
115    #[serde(default = "default_concurrency_limit")]
116    pub grpc_concurrency_limit: Option<usize>,
117
118    /// Configuration struct for P2P.
119    #[serde(default)]
120    pub p2p_config: P2pConfig,
121
122    /// Contains genesis location that might be `InPlace`
123    /// for reading all genesis data to memory or `InFile`,
124    /// and `OnceCell` pointer to a genesis struct.
125    pub genesis: Genesis,
126
127    /// Contains the path where to find the migration blob.
128    pub migration_tx_data_path: Option<PathBuf>,
129
130    /// Configuration for pruning of the authority store, to define when
131    /// an old data is removed from the storage space.
132    #[serde(default = "default_authority_store_pruning_config")]
133    pub authority_store_pruning_config: AuthorityStorePruningConfig,
134
135    /// Size of the broadcast channel used for notifying other systems of end of
136    /// epoch.
137    ///
138    /// If unspecified, this will default to `128`.
139    #[serde(default = "default_end_of_epoch_broadcast_channel_capacity")]
140    pub end_of_epoch_broadcast_channel_capacity: usize,
141
142    /// Configuration for the checkpoint executor for limiting
143    /// the number of checkpoints to execute concurrently,
144    /// and to allow for checkpoint post-processing.
145    #[serde(default)]
146    pub checkpoint_executor_config: CheckpointExecutorConfig,
147
148    #[serde(skip_serializing_if = "Option::is_none")]
149    pub metrics: Option<MetricsConfig>,
150
151    /// In a `iota-node` binary, this is set to
152    /// SupportedProtocolVersions::SYSTEM_DEFAULT in iota-node/src/main.rs.
153    /// It is present in the config so that it can be changed by tests in
154    /// order to test protocol upgrades.
155    #[serde(skip)]
156    pub supported_protocol_versions: Option<SupportedProtocolVersions>,
157
158    /// Configuration to manage database checkpoints,
159    /// including whether to perform checkpoints at the end of an epoch,
160    /// the path for storing checkpoints, and other related settings.
161    #[serde(default)]
162    pub db_checkpoint_config: DBCheckpointConfig,
163
164    /// Configuration for enabling/disabling expensive safety checks.
165    #[serde(default)]
166    pub expensive_safety_check_config: ExpensiveSafetyCheckConfig,
167
168    /// Configuration to specify rules for denying transactions
169    /// based on `objectsIDs`, `addresses`, or enable/disable many
170    /// features such as publishing new packages or using shared objects.
171    #[serde(default)]
172    pub transaction_deny_config: TransactionDenyConfig,
173
174    /// Config used to deny execution for certificate digests
175    /// know for crashing or hanging validator nodes.
176    ///
177    /// Should be used for a fast temporary fixes and
178    /// removed once the issue is fixed.
179    #[serde(default)]
180    pub certificate_deny_config: CertificateDenyConfig,
181
182    /// Used to determine how state debug information is dumped
183    /// when a node forks.
184    #[serde(default)]
185    pub state_debug_dump_config: StateDebugDumpConfig,
186
187    /// Configuration for writing state archive. If `ObjectStorage`
188    /// config is provided, `ArchiveWriter` will be created
189    /// for checkpoints archival.
190    #[serde(default)]
191    pub state_archive_write_config: StateArchiveConfig,
192
193    #[serde(default)]
194    pub state_archive_read_config: Vec<StateArchiveConfig>,
195
196    /// Determines if snapshot should be uploaded to the remote storage.
197    #[serde(default)]
198    pub state_snapshot_write_config: StateSnapshotConfig,
199
200    #[serde(default)]
201    pub indexer_max_subscriptions: Option<usize>,
202
203    #[serde(default = "default_transaction_kv_store_config")]
204    pub transaction_kv_store_read_config: TransactionKeyValueStoreReadConfig,
205
206    // TODO: write config seem to be unused.
207    #[serde(skip_serializing_if = "Option::is_none")]
208    pub transaction_kv_store_write_config: Option<TransactionKeyValueStoreWriteConfig>,
209
210    /// Configuration for defining thresholds and settings
211    /// for managing system overload conditions in a node.
212    #[serde(default = "default_authority_overload_config")]
213    pub authority_overload_config: AuthorityOverloadConfig,
214
215    /// Specifies the ending epoch for a node for debugging purposes.
216    ///
217    ///  Ignored if set by config, can be configured only by cli arguments.
218    #[serde(skip_serializing_if = "Option::is_none")]
219    pub run_with_range: Option<RunWithRange>,
220
221    // For killswitch use None
222    #[serde(
223        skip_serializing_if = "Option::is_none",
224        default = "default_traffic_controller_policy_config"
225    )]
226    pub policy_config: Option<PolicyConfig>,
227
228    #[serde(skip_serializing_if = "Option::is_none")]
229    pub firewall_config: Option<RemoteFirewallConfig>,
230
231    #[serde(default)]
232    pub execution_cache_config: ExecutionCacheConfig,
233
234    /// Memory budget in MiB for the in-memory cache of full checkpoint
235    /// contents, which serves the checkpoint executor's bulk transaction
236    /// loads and checkpoint-contents requests from state-sync peers. When
237    /// the budget is exceeded, the oldest checkpoints are evicted first.
238    /// Set to 0 to disable the cache; consumers then fall back to
239    /// reconstructing contents from the transaction and effects stores.
240    ///
241    /// The budget is accounted in serialized (BCS) bytes; the resident
242    /// memory of a full cache is somewhat higher than the configured value
243    /// due to in-memory representation overhead.
244    #[serde(default = "default_full_checkpoint_contents_cache_size_mb")]
245    pub full_checkpoint_contents_cache_size_mb: usize,
246
247    #[serde(default = "bool_true")]
248    pub enable_validator_tx_finalizer: bool,
249
250    /// Enables the pre-consensus soft-locking mechanism used by the
251    /// certificate-less (pcool) transaction flow (default: enabled).
252    ///
253    /// When disabled, post-consensus validation alone resolves owned-object
254    /// conflicts. Has no effect unless the pcool flow is enabled.
255    #[serde(default = "bool_true")]
256    pub enable_soft_locking: bool,
257
258    #[serde(default)]
259    pub verifier_signing_config: VerifierSigningConfig,
260
261    /// If a value is set, it determines if writes to DB can stall, which can
262    /// halt the whole process. By default, write stall is enabled on
263    /// validators but not on fullnodes.
264    #[serde(skip_serializing_if = "Option::is_none")]
265    pub enable_db_write_stall: Option<bool>,
266
267    #[serde(default, skip_serializing_if = "Option::is_none")]
268    pub iota_names_config: Option<IotaNamesConfig>,
269
270    /// Flag to enable the gRPC API.
271    #[serde(default)]
272    pub enable_grpc_api: bool,
273    #[serde(
274        default = "default_grpc_api_config",
275        skip_serializing_if = "Option::is_none"
276    )]
277    pub grpc_api_config: Option<GrpcApiConfig>,
278
279    /// Allow overriding the chain for testing purposes. For instance, it allows
280    /// you to create a test network that believes it is mainnet or testnet.
281    /// Attempting to override this value on production networks will result
282    /// in an error.
283    #[serde(skip_serializing_if = "Option::is_none")]
284    pub chain_override_for_testing: Option<Chain>,
285
286    /// Configuration for the validator client monitor that tracks
287    /// client-observed performance metrics for validators.
288    #[serde(default, skip_serializing_if = "Option::is_none")]
289    pub validator_client_monitor_config:
290        Option<crate::validator_client_monitor_config::ValidatorClientMonitorConfig>,
291}
292
293#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
294#[serde(rename_all = "kebab-case")]
295pub struct TlsConfig {
296    /// File path to a PEM formatted TLS certificate chain
297    cert: String,
298    /// File path to a PEM formatted TLS private key
299    key: String,
300}
301
302impl TlsConfig {
303    pub fn cert(&self) -> &str {
304        &self.cert
305    }
306
307    pub fn key(&self) -> &str {
308        &self.key
309    }
310}
311
312/// Configuration for the gRPC API service
313#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
314#[serde(rename_all = "kebab-case")]
315pub struct GrpcApiConfig {
316    /// The address to bind the gRPC server to
317    #[serde(default = "default_grpc_api_address")]
318    pub address: SocketAddr,
319
320    /// TLS configuration for the gRPC server.
321    ///
322    /// If not provided, the gRPC server will use plain TCP without TLS.
323    #[serde(skip_serializing_if = "Option::is_none")]
324    pub tls: Option<TlsConfig>,
325
326    /// Maximum message size for gRPC responses (in bytes)
327    #[serde(default = "default_grpc_api_max_message_size_bytes")]
328    pub max_message_size_bytes: u32,
329
330    /// Buffer size for broadcast channels used for streaming
331    #[serde(default = "default_grpc_api_broadcast_buffer_size")]
332    pub broadcast_buffer_size: u32,
333
334    /// Maximum number of concurrent subscribers to checkpoint streaming RPCs.
335    /// Once the cap is reached, additional subscribe requests are rejected
336    /// with `Unavailable` to protect the server from being overwhelmed by
337    /// unbounded streaming clients. Values below 1 are clamped to 1 at
338    /// server startup.
339    #[serde(default = "default_grpc_api_max_concurrent_stream_subscribers")]
340    pub max_concurrent_stream_subscribers: u32,
341
342    /// Maximum size for Move values when rendering to JSON
343    /// in bytes.
344    #[serde(default = "default_grpc_api_max_json_move_value_size")]
345    pub max_json_move_value_size: usize,
346
347    /// Maximum number of transactions allowed in a single ExecuteTransactions
348    /// batch request.
349    #[serde(default = "default_grpc_api_max_execute_transaction_batch_size")]
350    pub max_execute_transaction_batch_size: u32,
351
352    /// Maximum number of transactions allowed in a single SimulateTransactions
353    /// batch request.
354    #[serde(default = "default_grpc_api_max_simulate_transaction_batch_size")]
355    pub max_simulate_transaction_batch_size: u32,
356
357    /// Maximum allowed timeout in milliseconds for waiting for checkpoint
358    /// inclusion in ExecuteTransactions requests. Client-specified timeouts
359    /// are clamped to this value.
360    #[serde(default = "default_grpc_api_max_checkpoint_inclusion_timeout_ms")]
361    pub max_checkpoint_inclusion_timeout_ms: u64,
362}
363
364fn default_grpc_api_address() -> SocketAddr {
365    SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 50051)
366}
367
368fn default_grpc_api_broadcast_buffer_size() -> u32 {
369    100
370}
371
372fn default_grpc_api_max_concurrent_stream_subscribers() -> u32 {
373    1024
374}
375
376fn default_grpc_api_max_message_size_bytes() -> u32 {
377    128 * 1024 * 1024 // 128MB
378}
379
380fn default_grpc_api_max_json_move_value_size() -> usize {
381    1024 * 1024 // 1 MB
382}
383
384fn default_grpc_api_max_execute_transaction_batch_size() -> u32 {
385    20
386}
387
388fn default_grpc_api_max_simulate_transaction_batch_size() -> u32 {
389    20
390}
391
392fn default_grpc_api_max_checkpoint_inclusion_timeout_ms() -> u64 {
393    60_000 // 60 seconds
394}
395
396impl Default for GrpcApiConfig {
397    fn default() -> Self {
398        Self {
399            address: default_grpc_api_address(),
400            tls: None,
401            max_message_size_bytes: default_grpc_api_max_message_size_bytes(),
402            broadcast_buffer_size: default_grpc_api_broadcast_buffer_size(),
403            max_concurrent_stream_subscribers: default_grpc_api_max_concurrent_stream_subscribers(),
404            max_json_move_value_size: default_grpc_api_max_json_move_value_size(),
405            max_execute_transaction_batch_size: default_grpc_api_max_execute_transaction_batch_size(
406            ),
407            max_simulate_transaction_batch_size:
408                default_grpc_api_max_simulate_transaction_batch_size(),
409            max_checkpoint_inclusion_timeout_ms:
410                default_grpc_api_max_checkpoint_inclusion_timeout_ms(),
411        }
412    }
413}
414
415impl GrpcApiConfig {
416    // The default maximum uncompressed size in bytes for a message, based on
417    // tonic's default.
418    const GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE: u32 = 4 * 1024 * 1024; // 4MB
419    const GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES: u32 =
420        Self::GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE;
421
422    pub fn tls_config(&self) -> Option<&TlsConfig> {
423        self.tls.as_ref()
424    }
425
426    pub fn max_message_size_bytes(&self) -> u32 {
427        // Ensure max message size is at least the minimum allowed
428        self.max_message_size_bytes
429            .max(Self::GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES)
430    }
431
432    /// Calculate the maximum size for a message that can be
433    /// sent to a client, taking into account the client's max message size
434    /// preference.
435    pub fn max_message_size_client_bytes(&self, client_max_message_size_bytes: Option<u32>) -> u32 {
436        client_max_message_size_bytes
437            // if the client did not specify a max message size, use the tonic default receive
438            // message size
439            .unwrap_or(Self::GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE)
440            // clamp the value between the tonic default and the service max message size
441            .clamp(
442                Self::GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES,
443                self.max_message_size_bytes(),
444            )
445    }
446}
447
448#[derive(Clone, Debug, Default, Deserialize, Serialize)]
449#[serde(rename_all = "kebab-case")]
450pub struct ExecutionCacheConfig {
451    #[serde(default)]
452    pub writeback_cache: WritebackCacheConfig,
453}
454
455#[derive(Clone, Debug, Default, Deserialize, Serialize)]
456#[serde(rename_all = "kebab-case")]
457pub struct WritebackCacheConfig {
458    /// Maximum number of entries in each cache. (There are several
459    /// different caches).
460    #[serde(default, skip_serializing_if = "Option::is_none")]
461    pub max_cache_size: Option<u64>, // defaults to 100000
462
463    #[serde(default, skip_serializing_if = "Option::is_none")]
464    pub package_cache_size: Option<u64>, // defaults to 1000
465
466    #[serde(default, skip_serializing_if = "Option::is_none")]
467    pub object_cache_size: Option<u64>, // defaults to max_cache_size
468    #[serde(default, skip_serializing_if = "Option::is_none")]
469    pub marker_cache_size: Option<u64>, // defaults to object_cache_size
470    #[serde(default, skip_serializing_if = "Option::is_none")]
471    pub object_by_id_cache_size: Option<u64>, // defaults to object_cache_size
472
473    #[serde(default, skip_serializing_if = "Option::is_none")]
474    pub transaction_cache_size: Option<u64>, // defaults to max_cache_size
475    #[serde(default, skip_serializing_if = "Option::is_none")]
476    pub executed_effect_cache_size: Option<u64>, // defaults to transaction_cache_size
477    #[serde(default, skip_serializing_if = "Option::is_none")]
478    pub effect_cache_size: Option<u64>, // defaults to executed_effect_cache_size
479
480    #[serde(default, skip_serializing_if = "Option::is_none")]
481    pub events_cache_size: Option<u64>, // defaults to transaction_cache_size
482
483    #[serde(default, skip_serializing_if = "Option::is_none")]
484    pub transaction_objects_cache_size: Option<u64>, // defaults to 1000
485
486    /// Number of uncommitted transactions at which to pause consensus
487    /// handler.
488    #[serde(default, skip_serializing_if = "Option::is_none")]
489    pub backpressure_threshold: Option<u64>, // defaults to 100_000
490
491    /// Number of uncommitted transactions at which to refuse new
492    /// transaction submissions. Defaults to backpressure_threshold
493    /// if unset.
494    #[serde(default, skip_serializing_if = "Option::is_none")]
495    pub backpressure_threshold_for_rpc: Option<u64>, // defaults to backpressure_threshold
496
497    /// Percentage of `backpressure_threshold` at which graduated load shedding
498    /// based on writeback-cache pending transaction count begins. The
499    /// locally-calculated shedding percentage increases linearly from 0% at
500    /// `backpressure_threshold * backpressure_soft_limit_pct / 100` up to
501    /// 100% at the `backpressure_threshold` if the cache size continues to
502    /// increase. The calculated shedding percentage is broadcast to other
503    /// validators for a coordinated response. Defaults to 50.
504    #[serde(default, skip_serializing_if = "Option::is_none")]
505    pub backpressure_soft_limit_pct: Option<u32>,
506}
507
508impl WritebackCacheConfig {
509    pub fn max_cache_size(&self) -> u64 {
510        std::env::var("IOTA_CACHE_WRITEBACK_SIZE_MAX")
511            .ok()
512            .and_then(|s| s.parse().ok())
513            .or(self.max_cache_size)
514            .unwrap_or(100000)
515    }
516
517    pub fn package_cache_size(&self) -> u64 {
518        std::env::var("IOTA_CACHE_WRITEBACK_SIZE_PACKAGE")
519            .ok()
520            .and_then(|s| s.parse().ok())
521            .or(self.package_cache_size)
522            .unwrap_or(1000)
523    }
524
525    pub fn object_cache_size(&self) -> u64 {
526        std::env::var("IOTA_CACHE_WRITEBACK_SIZE_OBJECT")
527            .ok()
528            .and_then(|s| s.parse().ok())
529            .or(self.object_cache_size)
530            .unwrap_or_else(|| self.max_cache_size())
531    }
532
533    pub fn marker_cache_size(&self) -> u64 {
534        std::env::var("IOTA_CACHE_WRITEBACK_SIZE_MARKER")
535            .ok()
536            .and_then(|s| s.parse().ok())
537            .or(self.marker_cache_size)
538            .unwrap_or_else(|| self.object_cache_size())
539    }
540
541    pub fn object_by_id_cache_size(&self) -> u64 {
542        std::env::var("IOTA_CACHE_WRITEBACK_SIZE_OBJECT_BY_ID")
543            .ok()
544            .and_then(|s| s.parse().ok())
545            .or(self.object_by_id_cache_size)
546            .unwrap_or_else(|| self.object_cache_size())
547    }
548
549    pub fn transaction_cache_size(&self) -> u64 {
550        std::env::var("IOTA_CACHE_WRITEBACK_SIZE_TRANSACTION")
551            .ok()
552            .and_then(|s| s.parse().ok())
553            .or(self.transaction_cache_size)
554            .unwrap_or_else(|| self.max_cache_size())
555    }
556
557    pub fn executed_effect_cache_size(&self) -> u64 {
558        std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EXECUTED_EFFECT")
559            .ok()
560            .and_then(|s| s.parse().ok())
561            .or(self.executed_effect_cache_size)
562            .unwrap_or_else(|| self.transaction_cache_size())
563    }
564
565    pub fn effect_cache_size(&self) -> u64 {
566        std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EFFECT")
567            .ok()
568            .and_then(|s| s.parse().ok())
569            .or(self.effect_cache_size)
570            .unwrap_or_else(|| self.executed_effect_cache_size())
571    }
572
573    pub fn events_cache_size(&self) -> u64 {
574        std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EVENTS")
575            .ok()
576            .and_then(|s| s.parse().ok())
577            .or(self.events_cache_size)
578            .unwrap_or_else(|| self.transaction_cache_size())
579    }
580
581    pub fn transaction_objects_cache_size(&self) -> u64 {
582        std::env::var("IOTA_CACHE_WRITEBACK_SIZE_TRANSACTION_OBJECTS")
583            .ok()
584            .and_then(|s| s.parse().ok())
585            .or(self.transaction_objects_cache_size)
586            .unwrap_or(1000)
587    }
588
589    pub fn backpressure_threshold(&self) -> u64 {
590        std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_THRESHOLD")
591            .ok()
592            .and_then(|s| s.parse().ok())
593            .or(self.backpressure_threshold)
594            .unwrap_or(100_000)
595    }
596
597    pub fn backpressure_threshold_for_rpc(&self) -> u64 {
598        std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_THRESHOLD_FOR_RPC")
599            .ok()
600            .and_then(|s| s.parse().ok())
601            .or(self.backpressure_threshold_for_rpc)
602            .unwrap_or(self.backpressure_threshold())
603    }
604
605    pub fn backpressure_soft_limit_pct(&self) -> u32 {
606        std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_SOFT_LIMIT_PCT")
607            .ok()
608            .and_then(|s| s.parse().ok())
609            .or(self.backpressure_soft_limit_pct)
610            .unwrap_or(50)
611            .min(100)
612    }
613}
614
615#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
616#[serde(rename_all = "lowercase")]
617pub enum ServerType {
618    WebSocket,
619    Http,
620    Both,
621}
622
623#[derive(Clone, Debug, Deserialize, Serialize)]
624#[serde(rename_all = "kebab-case")]
625pub struct TransactionKeyValueStoreReadConfig {
626    #[serde(default = "default_base_url")]
627    pub base_url: String,
628
629    #[serde(default = "default_cache_size")]
630    pub cache_size: u64,
631}
632
633impl Default for TransactionKeyValueStoreReadConfig {
634    fn default() -> Self {
635        Self {
636            base_url: default_base_url(),
637            cache_size: default_cache_size(),
638        }
639    }
640}
641
642fn default_base_url() -> String {
643    "".to_string()
644}
645
646fn default_cache_size() -> u64 {
647    100_000
648}
649
650fn default_transaction_kv_store_config() -> TransactionKeyValueStoreReadConfig {
651    TransactionKeyValueStoreReadConfig::default()
652}
653
654fn default_authority_store_pruning_config() -> AuthorityStorePruningConfig {
655    AuthorityStorePruningConfig::default()
656}
657
658pub fn default_enable_index_processing() -> bool {
659    true
660}
661
662fn default_grpc_address() -> Multiaddr {
663    "/ip4/0.0.0.0/tcp/8080".parse().unwrap()
664}
665fn default_authority_key_pair() -> AuthorityKeyPairWithPath {
666    AuthorityKeyPairWithPath::new(get_key_pair_from_rng::<AuthorityKeyPair, _>(&mut OsRng).1)
667}
668
669fn default_key_pair() -> KeyPairWithPath {
670    KeyPairWithPath::new(
671        get_key_pair_from_rng::<AccountKeyPair, _>(&mut OsRng)
672            .1
673            .into(),
674    )
675}
676
677fn default_metrics_address() -> SocketAddr {
678    SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9184)
679}
680
681pub fn default_admin_interface_address() -> SocketAddr {
682    SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 1337)
683}
684
685pub fn default_json_rpc_address() -> SocketAddr {
686    SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9000)
687}
688
689pub fn default_grpc_api_config() -> Option<GrpcApiConfig> {
690    Some(GrpcApiConfig::default())
691}
692
693pub fn default_concurrency_limit() -> Option<usize> {
694    Some(DEFAULT_GRPC_CONCURRENCY_LIMIT)
695}
696
697pub fn default_end_of_epoch_broadcast_channel_capacity() -> usize {
698    128
699}
700
701pub fn default_full_checkpoint_contents_cache_size_mb() -> usize {
702    DEFAULT_FULL_CHECKPOINT_CONTENTS_CACHE_SIZE_MB
703}
704
705pub fn bool_true() -> bool {
706    true
707}
708
709impl Config for NodeConfig {}
710
711impl NodeConfig {
712    pub fn authority_key_pair(&self) -> &AuthorityKeyPair {
713        self.authority_key_pair.authority_keypair()
714    }
715
716    pub fn protocol_key_pair(&self) -> &NetworkKeyPair {
717        match self.protocol_key_pair.keypair() {
718            IotaKeyPair::Ed25519(kp) => kp,
719            other => {
720                panic!("invalid keypair type: {other:?}, only Ed25519 is allowed for protocol key")
721            }
722        }
723    }
724
725    pub fn network_key_pair(&self) -> &NetworkKeyPair {
726        match self.network_key_pair.keypair() {
727            IotaKeyPair::Ed25519(kp) => kp,
728            other => {
729                panic!("invalid keypair type: {other:?}, only Ed25519 is allowed for network key")
730            }
731        }
732    }
733
734    pub fn authority_public_key(&self) -> AuthorityPublicKeyBytes {
735        self.authority_key_pair().public().into()
736    }
737
738    pub fn db_path(&self) -> PathBuf {
739        self.db_path.join("live")
740    }
741
742    pub fn db_checkpoint_path(&self) -> PathBuf {
743        self.db_path.join("db_checkpoints")
744    }
745
746    pub fn archive_path(&self) -> PathBuf {
747        self.db_path.join("archive")
748    }
749
750    pub fn snapshot_path(&self) -> PathBuf {
751        self.db_path.join("snapshot")
752    }
753
754    pub fn network_address(&self) -> &Multiaddr {
755        &self.network_address
756    }
757
758    pub fn consensus_config(&self) -> Option<&ConsensusConfig> {
759        self.consensus_config.as_ref()
760    }
761
762    pub fn genesis(&self) -> Result<&genesis::Genesis> {
763        self.genesis.genesis()
764    }
765
766    pub fn load_migration_tx_data(&self) -> Result<MigrationTxData> {
767        let Some(location) = &self.migration_tx_data_path else {
768            anyhow::bail!("no file location set");
769        };
770
771        // Load from file
772        let migration_tx_data = MigrationTxData::load(location)?;
773
774        // Validate migration content in order to avoid corrupted or malicious data
775        migration_tx_data.validate_from_genesis(self.genesis.genesis()?)?;
776        Ok(migration_tx_data)
777    }
778
779    pub fn iota_address(&self) -> Address {
780        (&self.account_key_pair.keypair().public()).into()
781    }
782
783    pub fn archive_reader_config(&self) -> Vec<ArchiveReaderConfig> {
784        self.state_archive_read_config
785            .iter()
786            .flat_map(|config| {
787                config
788                    .object_store_config
789                    .as_ref()
790                    .map(|remote_store_config| ArchiveReaderConfig {
791                        remote_store_config: remote_store_config.clone(),
792                        download_concurrency: NonZeroUsize::new(config.concurrency)
793                            .unwrap_or(NonZeroUsize::new(5).unwrap()),
794                        use_for_pruning_watermark: config.use_for_pruning_watermark,
795                    })
796            })
797            .collect()
798    }
799
800    pub fn jsonrpc_server_type(&self) -> ServerType {
801        self.jsonrpc_server_type.unwrap_or(ServerType::Http)
802    }
803}
804
805#[derive(Debug, Clone, Deserialize, Serialize)]
806#[serde(rename_all = "kebab-case")]
807pub struct ConsensusConfig {
808    /// Base consensus DB path for all epochs.
809    pub db_path: PathBuf,
810
811    /// The number of epochs for which to retain the consensus DBs.
812    /// Setting it to 0 will make a consensus DB getting dropped
813    /// as soon as system is switched to a new epoch.
814    pub db_retention_epochs: Option<u64>,
815
816    /// Pruner will run on every epoch change but it will also check
817    /// periodically on every `db_pruner_period_secs` seconds to see
818    /// if there are any epoch DBs to remove.
819    pub db_pruner_period_secs: Option<u64>,
820
821    /// Hard limit on the number of pending transactions to submit to
822    /// consensus, including those in submission wait. Used as the upper
823    /// bound for graduated pre-consensus load shedding
824    /// (`graduated_load_shedding_soft_limit_pct`) in the certificate-less
825    /// (P-COOL) mode, and as the threshold for the binary
826    /// cutoff in `ConsensusAdapter::check_consensus_overload()` in both
827    /// certificate-less and certificate-based flows.
828    ///
829    /// Default to 20_000 inflight limit, assuming 20_000 txn tps * 1 sec
830    /// consensus latency.
831    pub max_pending_transactions: Option<usize>,
832
833    /// When defined caps the calculated submission position to the
834    /// max_submit_position.
835    ///
836    /// Even if the is elected to submit from a higher
837    /// position than this, it will "reset" to the max_submit_position.
838    pub max_submit_position: Option<usize>,
839
840    /// The submit delay step to consensus defined in milliseconds.
841    ///
842    /// When provided it will override the current back off logic otherwise the
843    /// default backoff logic will be applied based on consensus latency
844    /// estimates.
845    pub submit_delay_step_override_millis: Option<u64>,
846
847    /// Parameters for Starfish consensus
848    #[serde(skip_serializing_if = "Option::is_none", alias = "starfish_parameters")]
849    pub parameters: Option<StarfishParameters>,
850
851    /// Percentage of `max_pending_transactions` (hard limit) defining the soft
852    /// limit at which graduated pre-consensus load shedding begins. When
853    /// in-flight transactions are at or below the soft limit, no shedding
854    /// occurs; above it, the shedding rate scales linearly from 0% to 100% at
855    /// `max_pending_transactions`. Used in the certificate-less (P-COOL) mode.
856    #[serde(skip_serializing_if = "Option::is_none")]
857    pub graduated_load_shedding_soft_limit_pct: Option<u32>,
858}
859
860impl ConsensusConfig {
861    pub fn db_path(&self) -> &Path {
862        &self.db_path
863    }
864
865    /// Returns the hard limit on the number of pending transactions to submit
866    /// to consensus, including those in submission wait. Defaults to 20_000
867    /// inflight limit, assuming 20_000 txn tps * 1 sec consensus latency.
868    pub fn max_pending_transactions(&self) -> usize {
869        self.max_pending_transactions.unwrap_or(20_000)
870    }
871
872    /// Returns the percentage of `max_pending_transactions` (hard limit)
873    /// defining the soft limit at which graduated pre-consensus load
874    /// shedding begins. Defaults to 50%. Used in the certificate-less
875    /// (P-COOL) mode.
876    pub fn graduated_load_shedding_soft_limit_pct(&self) -> u32 {
877        self.graduated_load_shedding_soft_limit_pct
878            .unwrap_or(50)
879            .min(100)
880    }
881
882    pub fn submit_delay_step_override(&self) -> Option<Duration> {
883        self.submit_delay_step_override_millis
884            .map(Duration::from_millis)
885    }
886
887    pub fn db_retention_epochs(&self) -> u64 {
888        self.db_retention_epochs.unwrap_or(0)
889    }
890
891    pub fn db_pruner_period(&self) -> Duration {
892        // Default to 1 hour
893        self.db_pruner_period_secs
894            .map(Duration::from_secs)
895            .unwrap_or(Duration::from_secs(3_600))
896    }
897}
898
899#[derive(Clone, Debug, Deserialize, Serialize)]
900#[serde(rename_all = "kebab-case")]
901pub struct CheckpointExecutorConfig {
902    /// Upper bound on the number of checkpoints that can be concurrently
903    /// executed.
904    ///
905    /// If unspecified, this will default to `200`
906    #[serde(default = "default_checkpoint_execution_max_concurrency")]
907    pub checkpoint_execution_max_concurrency: usize,
908
909    /// Number of seconds to wait for effects of a batch of transactions
910    /// before logging a warning. Note that we will continue to retry
911    /// indefinitely.
912    ///
913    /// If unspecified, this will default to `10`.
914    #[serde(default = "default_local_execution_timeout_sec")]
915    pub local_execution_timeout_sec: u64,
916
917    /// Optional directory used for data ingestion pipeline.
918    ///
919    /// When specified, each executed checkpoint will be saved in a local
920    /// directory for post-processing
921    #[serde(default, skip_serializing_if = "Option::is_none")]
922    pub data_ingestion_dir: Option<PathBuf>,
923}
924
925#[derive(Clone, Debug, Default, Deserialize, Serialize)]
926#[serde(rename_all = "kebab-case")]
927pub struct ExpensiveSafetyCheckConfig {
928    /// If enabled, at epoch boundary, we will check that the storage
929    /// fund balance is always identical to the sum of the storage
930    /// rebate of all live objects, and that the total IOTA in the network
931    /// remains the same.
932    #[serde(default)]
933    enable_epoch_iota_conservation_check: bool,
934
935    /// If enabled, we will check that the total IOTA in all input objects of a
936    /// tx (both the Move part and the storage rebate) matches the total IOTA
937    /// in all output objects of the tx + gas fees.
938    #[serde(default)]
939    enable_deep_per_tx_iota_conservation_check: bool,
940
941    /// Disable epoch IOTA conservation check even when we are running in debug
942    /// mode.
943    #[serde(default)]
944    force_disable_epoch_iota_conservation_check: bool,
945
946    /// If enabled, at epoch boundary, we will check that the accumulated
947    /// live object state matches the end of epoch root state digest.
948    #[serde(default)]
949    enable_state_consistency_check: bool,
950
951    /// Disable state consistency check even when we are running in debug mode.
952    #[serde(default)]
953    force_disable_state_consistency_check: bool,
954
955    #[serde(default)]
956    enable_secondary_index_checks: bool,
957    // TODO: Add more expensive checks here
958}
959
960impl ExpensiveSafetyCheckConfig {
961    pub fn new_enable_all() -> Self {
962        Self {
963            enable_epoch_iota_conservation_check: true,
964            enable_deep_per_tx_iota_conservation_check: true,
965            force_disable_epoch_iota_conservation_check: false,
966            enable_state_consistency_check: true,
967            force_disable_state_consistency_check: false,
968            enable_secondary_index_checks: false, // Disable by default for now
969        }
970    }
971
972    pub fn new_disable_all() -> Self {
973        Self {
974            enable_epoch_iota_conservation_check: false,
975            enable_deep_per_tx_iota_conservation_check: false,
976            force_disable_epoch_iota_conservation_check: true,
977            enable_state_consistency_check: false,
978            force_disable_state_consistency_check: true,
979            enable_secondary_index_checks: false,
980        }
981    }
982
983    pub fn force_disable_epoch_iota_conservation_check(&mut self) {
984        self.force_disable_epoch_iota_conservation_check = true;
985    }
986
987    pub fn enable_epoch_iota_conservation_check(&self) -> bool {
988        (self.enable_epoch_iota_conservation_check || cfg!(debug_assertions))
989            && !self.force_disable_epoch_iota_conservation_check
990    }
991
992    pub fn force_disable_state_consistency_check(&mut self) {
993        self.force_disable_state_consistency_check = true;
994    }
995
996    pub fn enable_state_consistency_check(&self) -> bool {
997        (self.enable_state_consistency_check || cfg!(debug_assertions))
998            && !self.force_disable_state_consistency_check
999    }
1000
1001    pub fn enable_deep_per_tx_iota_conservation_check(&self) -> bool {
1002        self.enable_deep_per_tx_iota_conservation_check || cfg!(debug_assertions)
1003    }
1004
1005    pub fn enable_secondary_index_checks(&self) -> bool {
1006        self.enable_secondary_index_checks
1007    }
1008}
1009
1010fn default_checkpoint_execution_max_concurrency() -> usize {
1011    4
1012}
1013
1014fn default_local_execution_timeout_sec() -> u64 {
1015    30
1016}
1017
1018impl Default for CheckpointExecutorConfig {
1019    fn default() -> Self {
1020        Self {
1021            checkpoint_execution_max_concurrency: default_checkpoint_execution_max_concurrency(),
1022            local_execution_timeout_sec: default_local_execution_timeout_sec(),
1023            data_ingestion_dir: None,
1024        }
1025    }
1026}
1027
1028#[derive(Debug, Clone, Deserialize, Serialize)]
1029#[serde(rename_all = "kebab-case")]
1030pub struct AuthorityStorePruningConfig {
1031    /// number of the latest epoch dbs to retain
1032    #[serde(default = "default_num_latest_epoch_dbs_to_retain")]
1033    pub num_latest_epoch_dbs_to_retain: usize,
1034    /// number of epochs to keep the latest version of objects for.
1035    /// Note that a zero value corresponds to an aggressive pruner.
1036    /// This mode is experimental and needs to be used with caution.
1037    /// Use `u64::MAX` to disable the pruner for the objects.
1038    #[serde(default)]
1039    pub num_epochs_to_retain: u64,
1040    /// enables periodic background compaction for old SST files whose last
1041    /// modified time is older than `periodic_compaction_threshold_days`
1042    /// days. That ensures that all sst files eventually go through the
1043    /// compaction process
1044    #[serde(
1045        default = "default_periodic_compaction_threshold_days",
1046        skip_serializing_if = "Option::is_none"
1047    )]
1048    pub periodic_compaction_threshold_days: Option<usize>,
1049    /// number of epochs to keep the latest version of transactions and effects
1050    /// for
1051    #[serde(skip_serializing_if = "Option::is_none")]
1052    pub num_epochs_to_retain_for_checkpoints: Option<u64>,
1053    /// Enables the compaction filter for pruning the objects table.
1054    /// If disabled, a range deletion approach is used instead.
1055    /// While it is generally safe to switch between the two modes,
1056    /// switching from the compaction filter approach back to range deletion
1057    /// may result in some old versions that will never be pruned.
1058    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1059    pub enable_compaction_filter: bool,
1060    #[serde(skip_serializing_if = "Option::is_none")]
1061    pub num_epochs_to_retain_for_indexes: Option<u64>,
1062}
1063
1064fn default_num_latest_epoch_dbs_to_retain() -> usize {
1065    3
1066}
1067
1068fn default_periodic_compaction_threshold_days() -> Option<usize> {
1069    Some(1)
1070}
1071
1072impl Default for AuthorityStorePruningConfig {
1073    fn default() -> Self {
1074        Self {
1075            num_latest_epoch_dbs_to_retain: default_num_latest_epoch_dbs_to_retain(),
1076            num_epochs_to_retain: 0,
1077            periodic_compaction_threshold_days: None,
1078            num_epochs_to_retain_for_checkpoints: if cfg!(msim) { Some(2) } else { None },
1079            enable_compaction_filter: cfg!(test) || cfg!(msim),
1080            num_epochs_to_retain_for_indexes: None,
1081        }
1082    }
1083}
1084
1085impl AuthorityStorePruningConfig {
1086    pub fn set_num_epochs_to_retain(&mut self, num_epochs_to_retain: u64) {
1087        self.num_epochs_to_retain = num_epochs_to_retain;
1088    }
1089
1090    pub fn set_num_epochs_to_retain_for_checkpoints(&mut self, num_epochs_to_retain: Option<u64>) {
1091        self.num_epochs_to_retain_for_checkpoints = num_epochs_to_retain;
1092    }
1093
1094    pub fn num_epochs_to_retain_for_checkpoints(&self) -> Option<u64> {
1095        self.num_epochs_to_retain_for_checkpoints
1096            // if n less than 2, coerce to 2 and log
1097            .map(|n| {
1098                if n < 2 {
1099                    info!("num_epochs_to_retain_for_checkpoints must be at least 2, rounding up from {}", n);
1100                    2
1101                } else {
1102                    n
1103                }
1104            })
1105    }
1106}
1107
1108#[derive(Debug, Clone, Deserialize, Serialize)]
1109#[serde(rename_all = "kebab-case")]
1110pub struct MetricsConfig {
1111    #[serde(skip_serializing_if = "Option::is_none")]
1112    pub push_interval_seconds: Option<u64>,
1113    #[serde(skip_serializing_if = "Option::is_none")]
1114    pub push_url: Option<String>,
1115    #[serde(skip_serializing_if = "Option::is_none")]
1116    pub groups: Option<MetricGroups>,
1117}
1118
1119#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1120#[serde(rename_all = "kebab-case")]
1121pub struct DBCheckpointConfig {
1122    #[serde(default)]
1123    pub perform_db_checkpoints_at_epoch_end: bool,
1124    #[serde(skip_serializing_if = "Option::is_none")]
1125    pub checkpoint_path: Option<PathBuf>,
1126    #[serde(skip_serializing_if = "Option::is_none")]
1127    pub object_store_config: Option<ObjectStoreConfig>,
1128    #[serde(skip_serializing_if = "Option::is_none")]
1129    pub perform_index_db_checkpoints_at_epoch_end: Option<bool>,
1130    #[serde(skip_serializing_if = "Option::is_none")]
1131    pub prune_and_compact_before_upload: Option<bool>,
1132}
1133
1134#[derive(Debug, Clone)]
1135pub struct ArchiveReaderConfig {
1136    pub remote_store_config: ObjectStoreConfig,
1137    pub download_concurrency: NonZeroUsize,
1138    pub use_for_pruning_watermark: bool,
1139}
1140
1141#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1142#[serde(rename_all = "kebab-case")]
1143pub struct StateArchiveConfig {
1144    #[serde(skip_serializing_if = "Option::is_none")]
1145    pub object_store_config: Option<ObjectStoreConfig>,
1146    pub concurrency: usize,
1147    pub use_for_pruning_watermark: bool,
1148}
1149
1150/// Configuration for the per-epoch state-snapshot publisher.
1151///
1152/// **Operator note (V2 snapshot publishing).** A node configured to publish
1153/// V2 snapshots must have a perpetual store containing no pre-V2
1154/// (`StoreObjectV1`) rows. This means a snapshot-publishing node must have
1155/// either synced from genesis under V2 or been restored from a V2 snapshot.
1156/// There is no on-disk backfill: a fresh sync is the only supported path.
1157#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1158#[serde(rename_all = "kebab-case")]
1159pub struct StateSnapshotConfig {
1160    #[serde(skip_serializing_if = "Option::is_none")]
1161    pub object_store_config: Option<ObjectStoreConfig>,
1162    pub concurrency: usize,
1163}
1164
1165#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1166#[serde(rename_all = "kebab-case")]
1167pub struct TransactionKeyValueStoreWriteConfig {
1168    pub aws_access_key_id: String,
1169    pub aws_secret_access_key: String,
1170    pub aws_region: String,
1171    pub table_name: String,
1172    pub bucket_name: String,
1173    pub concurrency: usize,
1174}
1175
1176/// Configuration for the threshold(s) at which we consider the system
1177/// to be overloaded. When one of the threshold is passed, the node may
1178/// stop processing new transactions and/or certificates until the congestion
1179/// resolves.
1180#[derive(Clone, Debug, Deserialize, Serialize)]
1181#[serde(rename_all = "kebab-case")]
1182pub struct AuthorityOverloadConfig {
1183    /// Maximum time a transaction can wait in the transaction manager execution
1184    /// queue before it triggers an overload detection on the object it depends
1185    /// on.
1186    #[serde(default = "default_max_txn_age_in_queue")]
1187    pub max_txn_age_in_queue: Duration,
1188
1189    /// The interval of checking overload signal.
1190    #[serde(default = "default_overload_monitor_interval")]
1191    pub overload_monitor_interval: Duration,
1192
1193    /// The execution queueing latency when entering load shedding mode.
1194    #[serde(default = "default_execution_queue_latency_soft_limit")]
1195    pub execution_queue_latency_soft_limit: Duration,
1196
1197    /// The execution queueing latency when entering aggressive load shedding
1198    /// mode.
1199    #[serde(default = "default_execution_queue_latency_hard_limit")]
1200    pub execution_queue_latency_hard_limit: Duration,
1201
1202    /// The maximum percentage of transactions to shed in load shedding mode.
1203    #[serde(default = "default_max_load_shedding_percentage")]
1204    pub max_load_shedding_percentage: u32,
1205
1206    /// When in aggressive load shedding mode, the minimum percentage of
1207    /// transactions to shed.
1208    #[serde(default = "default_min_load_shedding_percentage_above_hard_limit")]
1209    pub min_load_shedding_percentage_above_hard_limit: u32,
1210
1211    /// If transaction ready rate is below this rate, we consider the validator
1212    /// is well under used, and will not enter load shedding mode.
1213    #[serde(default = "default_safe_transaction_ready_rate")]
1214    pub safe_transaction_ready_rate: u32,
1215
1216    /// When set to true, transaction signing may be rejected when the validator
1217    /// is overloaded.
1218    #[serde(default = "default_check_system_overload_at_signing")]
1219    pub check_system_overload_at_signing: bool,
1220
1221    /// When set to true, transaction execution may be rejected when the
1222    /// validator is overloaded.
1223    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1224    pub check_system_overload_at_execution: bool,
1225
1226    /// Reject a transaction if transaction manager queue length is above this
1227    /// threshold. 100_000 = 10k TPS * 5s resident time in transaction
1228    /// manager (pending + executing) * 2.
1229    #[serde(default = "default_max_transaction_manager_queue_length")]
1230    pub max_transaction_manager_queue_length: usize,
1231
1232    /// Reject a transaction if the number of pending transactions depending on
1233    /// the object is above the threshold.
1234    #[serde(default = "default_max_transaction_manager_per_object_queue_length")]
1235    pub max_transaction_manager_per_object_queue_length: usize,
1236
1237    /// Percentage of `max_transaction_manager_queue_length` at which graduated
1238    /// load shedding begins in the certificate-less (P-COOL) mode. Read
1239    /// via the same-named accessor, which clamps the value to <=100.
1240    #[serde(default = "default_max_transaction_manager_queue_length_soft_limit_pct")]
1241    pub max_transaction_manager_queue_length_soft_limit_pct: u32,
1242}
1243
1244impl AuthorityOverloadConfig {
1245    /// Returns the soft-limit percentage, clamped to <=100 to guard against
1246    /// out-of-range operator-supplied values.
1247    pub fn max_transaction_manager_queue_length_soft_limit_pct(&self) -> u32 {
1248        self.max_transaction_manager_queue_length_soft_limit_pct
1249            .min(100)
1250    }
1251}
1252
1253fn default_max_txn_age_in_queue() -> Duration {
1254    Duration::from_millis(500)
1255}
1256
1257fn default_overload_monitor_interval() -> Duration {
1258    Duration::from_secs(10)
1259}
1260
1261fn default_execution_queue_latency_soft_limit() -> Duration {
1262    Duration::from_secs(1)
1263}
1264
1265fn default_execution_queue_latency_hard_limit() -> Duration {
1266    Duration::from_secs(10)
1267}
1268
1269fn default_max_load_shedding_percentage() -> u32 {
1270    95
1271}
1272
1273fn default_min_load_shedding_percentage_above_hard_limit() -> u32 {
1274    50
1275}
1276
1277fn default_safe_transaction_ready_rate() -> u32 {
1278    100
1279}
1280
1281fn default_check_system_overload_at_signing() -> bool {
1282    true
1283}
1284
1285fn default_max_transaction_manager_queue_length() -> usize {
1286    100_000
1287}
1288
1289fn default_max_transaction_manager_queue_length_soft_limit_pct() -> u32 {
1290    50
1291}
1292
1293fn default_max_transaction_manager_per_object_queue_length() -> usize {
1294    20
1295}
1296
1297impl Default for AuthorityOverloadConfig {
1298    fn default() -> Self {
1299        Self {
1300            max_txn_age_in_queue: default_max_txn_age_in_queue(),
1301            overload_monitor_interval: default_overload_monitor_interval(),
1302            execution_queue_latency_soft_limit: default_execution_queue_latency_soft_limit(),
1303            execution_queue_latency_hard_limit: default_execution_queue_latency_hard_limit(),
1304            max_load_shedding_percentage: default_max_load_shedding_percentage(),
1305            min_load_shedding_percentage_above_hard_limit:
1306                default_min_load_shedding_percentage_above_hard_limit(),
1307            safe_transaction_ready_rate: default_safe_transaction_ready_rate(),
1308            check_system_overload_at_signing: true,
1309            check_system_overload_at_execution: false,
1310            max_transaction_manager_queue_length: default_max_transaction_manager_queue_length(),
1311            max_transaction_manager_queue_length_soft_limit_pct:
1312                default_max_transaction_manager_queue_length_soft_limit_pct(),
1313            max_transaction_manager_per_object_queue_length:
1314                default_max_transaction_manager_per_object_queue_length(),
1315        }
1316    }
1317}
1318
1319fn default_authority_overload_config() -> AuthorityOverloadConfig {
1320    AuthorityOverloadConfig::default()
1321}
1322
1323fn default_traffic_controller_policy_config() -> Option<PolicyConfig> {
1324    Some(PolicyConfig::default_dos_protection_policy())
1325}
1326
1327#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1328pub struct Genesis {
1329    #[serde(flatten)]
1330    location: Option<GenesisLocation>,
1331
1332    #[serde(skip)]
1333    genesis: once_cell::sync::OnceCell<genesis::Genesis>,
1334}
1335
1336impl Genesis {
1337    pub fn new(genesis: genesis::Genesis) -> Self {
1338        Self {
1339            location: Some(GenesisLocation::InPlace {
1340                genesis: Box::new(genesis),
1341            }),
1342            genesis: Default::default(),
1343        }
1344    }
1345
1346    pub fn new_from_file<P: Into<PathBuf>>(path: P) -> Self {
1347        Self {
1348            location: Some(GenesisLocation::File {
1349                genesis_file_location: path.into(),
1350            }),
1351            genesis: Default::default(),
1352        }
1353    }
1354
1355    pub fn new_empty() -> Self {
1356        Self {
1357            location: None,
1358            genesis: Default::default(),
1359        }
1360    }
1361
1362    pub fn genesis(&self) -> Result<&genesis::Genesis> {
1363        match &self.location {
1364            Some(GenesisLocation::InPlace { genesis }) => Ok(genesis),
1365            Some(GenesisLocation::File {
1366                genesis_file_location,
1367            }) => self
1368                .genesis
1369                .get_or_try_init(|| genesis::Genesis::load(genesis_file_location)),
1370            None => anyhow::bail!("no genesis location set"),
1371        }
1372    }
1373}
1374
1375#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1376#[serde(untagged)]
1377enum GenesisLocation {
1378    InPlace {
1379        genesis: Box<genesis::Genesis>,
1380    },
1381    File {
1382        #[serde(rename = "genesis-file-location")]
1383        genesis_file_location: PathBuf,
1384    },
1385}
1386
1387/// Wrapper struct for IotaKeyPair that can be deserialized from a file path.
1388/// Used by network, worker, and account keypair.
1389#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
1390pub struct KeyPairWithPath {
1391    #[serde(flatten)]
1392    location: KeyPairLocation,
1393
1394    #[serde(skip)]
1395    keypair: OnceCell<Arc<IotaKeyPair>>,
1396}
1397
1398#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1399#[serde(untagged)]
1400enum KeyPairLocation {
1401    InPlace {
1402        #[serde(with = "bech32_formatted_keypair")]
1403        value: Arc<IotaKeyPair>,
1404    },
1405    File {
1406        path: PathBuf,
1407    },
1408}
1409
1410impl KeyPairWithPath {
1411    pub fn new(kp: IotaKeyPair) -> Self {
1412        let cell: OnceCell<Arc<IotaKeyPair>> = OnceCell::new();
1413        let arc_kp = Arc::new(kp);
1414        // OK to unwrap panic because authority should not start without all keypairs
1415        // loaded.
1416        cell.set(arc_kp.clone()).expect("failed to set keypair");
1417        Self {
1418            location: KeyPairLocation::InPlace { value: arc_kp },
1419            keypair: cell,
1420        }
1421    }
1422
1423    pub fn new_from_path(path: PathBuf) -> Self {
1424        let cell: OnceCell<Arc<IotaKeyPair>> = OnceCell::new();
1425        // OK to unwrap panic because authority should not start without all keypairs
1426        // loaded.
1427        cell.set(Arc::new(read_keypair_from_file(&path).unwrap_or_else(
1428            |e| panic!("invalid keypair file at path {:?}: {e}", &path),
1429        )))
1430        .expect("failed to set keypair");
1431        Self {
1432            location: KeyPairLocation::File { path },
1433            keypair: cell,
1434        }
1435    }
1436
1437    pub fn keypair(&self) -> &IotaKeyPair {
1438        self.keypair
1439            .get_or_init(|| match &self.location {
1440                KeyPairLocation::InPlace { value } => value.clone(),
1441                KeyPairLocation::File { path } => {
1442                    // OK to unwrap panic because authority should not start without all keypairs
1443                    // loaded.
1444                    Arc::new(
1445                        read_keypair_from_file(path).unwrap_or_else(|e| {
1446                            panic!("invalid keypair file at path {path:?}: {e}")
1447                        }),
1448                    )
1449                }
1450            })
1451            .as_ref()
1452    }
1453}
1454
1455/// Wrapper struct for AuthorityKeyPair that can be deserialized from a file
1456/// path.
1457#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
1458pub struct AuthorityKeyPairWithPath {
1459    #[serde(flatten)]
1460    location: AuthorityKeyPairLocation,
1461
1462    #[serde(skip)]
1463    keypair: OnceCell<Arc<AuthorityKeyPair>>,
1464}
1465
1466#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1467#[serde(untagged)]
1468enum AuthorityKeyPairLocation {
1469    InPlace { value: Arc<AuthorityKeyPair> },
1470    File { path: PathBuf },
1471}
1472
1473impl AuthorityKeyPairWithPath {
1474    pub fn new(kp: AuthorityKeyPair) -> Self {
1475        let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1476        let arc_kp = Arc::new(kp);
1477        // OK to unwrap panic because authority should not start without all keypairs
1478        // loaded.
1479        cell.set(arc_kp.clone())
1480            .expect("failed to set authority keypair");
1481        Self {
1482            location: AuthorityKeyPairLocation::InPlace { value: arc_kp },
1483            keypair: cell,
1484        }
1485    }
1486
1487    pub fn new_from_path(path: PathBuf) -> Self {
1488        let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1489        // OK to unwrap panic because authority should not start without all keypairs
1490        // loaded.
1491        cell.set(Arc::new(
1492            read_authority_keypair_from_file(&path)
1493                .unwrap_or_else(|_| panic!("invalid authority keypair file at path {:?}", &path)),
1494        ))
1495        .expect("failed to set authority keypair");
1496        Self {
1497            location: AuthorityKeyPairLocation::File { path },
1498            keypair: cell,
1499        }
1500    }
1501
1502    pub fn authority_keypair(&self) -> &AuthorityKeyPair {
1503        self.keypair
1504            .get_or_init(|| match &self.location {
1505                AuthorityKeyPairLocation::InPlace { value } => value.clone(),
1506                AuthorityKeyPairLocation::File { path } => {
1507                    // OK to unwrap panic because authority should not start without all keypairs
1508                    // loaded.
1509                    Arc::new(
1510                        read_authority_keypair_from_file(path).unwrap_or_else(|_| {
1511                            panic!("invalid authority keypair file {:?}", &path)
1512                        }),
1513                    )
1514                }
1515            })
1516            .as_ref()
1517    }
1518}
1519
1520/// Configurations which determine how we dump state debug info.
1521/// Debug info is dumped when a node forks.
1522#[derive(Clone, Debug, Deserialize, Serialize, Default)]
1523#[serde(rename_all = "kebab-case")]
1524pub struct StateDebugDumpConfig {
1525    #[serde(skip_serializing_if = "Option::is_none")]
1526    pub dump_file_directory: Option<PathBuf>,
1527}
1528
1529#[cfg(test)]
1530mod tests {
1531    use std::path::PathBuf;
1532
1533    use fastcrypto::traits::KeyPair;
1534    use iota_keys::keypair_file::{write_authority_keypair_to_file, write_keypair_to_file};
1535    use iota_types::crypto::{
1536        AuthorityKeyPair, IotaKeyPair, NetworkKeyPair, get_key_pair_from_rng,
1537    };
1538    use rand::{SeedableRng, rngs::StdRng};
1539
1540    use super::Genesis;
1541    use crate::NodeConfig;
1542
1543    #[test]
1544    fn serialize_genesis_from_file() {
1545        let g = Genesis::new_from_file("path/to/file");
1546
1547        let s = serde_yaml::to_string(&g).unwrap();
1548        assert_eq!("---\ngenesis-file-location: path/to/file\n", s);
1549        let loaded_genesis: Genesis = serde_yaml::from_str(&s).unwrap();
1550        assert_eq!(g, loaded_genesis);
1551    }
1552
1553    #[test]
1554    fn fullnode_template() {
1555        const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1556
1557        let _template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1558    }
1559
1560    #[test]
1561    fn enable_soft_locking_defaults_to_enabled() {
1562        // The template omits `enable-soft-locking`, so this exercises the serde
1563        // default and pins the documented "default: enabled" contract.
1564        const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1565
1566        let config: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1567        assert!(config.enable_soft_locking);
1568    }
1569
1570    #[test]
1571    fn load_key_pairs_to_node_config() {
1572        let authority_key_pair: AuthorityKeyPair =
1573            get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1574        let protocol_key_pair: NetworkKeyPair =
1575            get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1576        let network_key_pair: NetworkKeyPair =
1577            get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1578
1579        write_authority_keypair_to_file(&authority_key_pair, PathBuf::from("authority.key"))
1580            .unwrap();
1581        write_keypair_to_file(
1582            &IotaKeyPair::Ed25519(protocol_key_pair.copy()),
1583            PathBuf::from("protocol.key"),
1584        )
1585        .unwrap();
1586        write_keypair_to_file(
1587            &IotaKeyPair::Ed25519(network_key_pair.copy()),
1588            PathBuf::from("network.key"),
1589        )
1590        .unwrap();
1591
1592        const TEMPLATE: &str = include_str!("../data/fullnode-template-with-path.yaml");
1593        let template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1594        assert_eq!(
1595            template.authority_key_pair().public(),
1596            authority_key_pair.public()
1597        );
1598        assert_eq!(
1599            template.network_key_pair().public(),
1600            network_key_pair.public()
1601        );
1602        assert_eq!(
1603            template.protocol_key_pair().public(),
1604            protocol_key_pair.public()
1605        );
1606    }
1607}
1608
1609// RunWithRange is used to specify the ending epoch/checkpoint to process.
1610// this is intended for use with disaster recovery debugging and verification
1611// workflows, never in normal operations
1612#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
1613pub enum RunWithRange {
1614    Epoch(EpochId),
1615    Checkpoint(CheckpointSequenceNumber),
1616}
1617
1618impl RunWithRange {
1619    // is epoch_id > RunWithRange::Epoch
1620    pub fn is_epoch_gt(&self, epoch_id: EpochId) -> bool {
1621        matches!(self, RunWithRange::Epoch(e) if epoch_id > *e)
1622    }
1623
1624    pub fn matches_checkpoint(&self, seq_num: CheckpointSequenceNumber) -> bool {
1625        matches!(self, RunWithRange::Checkpoint(seq) if *seq == seq_num)
1626    }
1627
1628    pub fn into_checkpoint_bound(self) -> Option<CheckpointSequenceNumber> {
1629        match self {
1630            RunWithRange::Epoch(_) => None,
1631            RunWithRange::Checkpoint(seq) => Some(seq),
1632        }
1633    }
1634}
1635
1636/// A serde helper module used with #[serde(with = "...")] to change the
1637/// de/serialization format of an `IotaKeyPair` to Bech32 when written to or
1638/// read from a node config.
1639mod bech32_formatted_keypair {
1640    use std::ops::Deref;
1641
1642    use iota_types::crypto::{EncodeDecodeBase64, IotaKeyPair};
1643    use serde::{Deserialize, Deserializer, Serializer};
1644
1645    pub fn serialize<S, T>(kp: &T, serializer: S) -> Result<S::Ok, S::Error>
1646    where
1647        S: Serializer,
1648        T: Deref<Target = IotaKeyPair>,
1649    {
1650        use serde::ser::Error;
1651
1652        // Serialize the keypair to a Bech32 string
1653        let s = kp.encode().map_err(Error::custom)?;
1654
1655        serializer.serialize_str(&s)
1656    }
1657
1658    pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
1659    where
1660        D: Deserializer<'de>,
1661        T: From<IotaKeyPair>,
1662    {
1663        use serde::de::Error;
1664
1665        let s = String::deserialize(deserializer)?;
1666
1667        // Try to deserialize the keypair from a Bech32 formatted string
1668        IotaKeyPair::decode(&s)
1669            .or_else(|_| {
1670                // For backwards compatibility try Base64 if Bech32 failed
1671                IotaKeyPair::decode_base64(&s)
1672            })
1673            .map(Into::into)
1674            .map_err(Error::custom)
1675    }
1676}