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