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(
693        get_key_pair_from_rng::<AccountKeyPair, _>(&mut OsRng)
694            .1
695            .into(),
696    )
697}
698
699fn default_metrics_address() -> SocketAddr {
700    SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9184)
701}
702
703pub fn default_admin_interface_address() -> SocketAddr {
704    SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 1337)
705}
706
707pub fn default_json_rpc_address() -> SocketAddr {
708    SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9000)
709}
710
711pub fn default_grpc_api_config() -> Option<GrpcApiConfig> {
712    Some(GrpcApiConfig::default())
713}
714
715pub fn default_grpc_concurrency_limit_per_core() -> NonZeroUsize {
716    NonZeroUsize::new(1000).unwrap()
717}
718
719pub fn default_end_of_epoch_broadcast_channel_capacity() -> usize {
720    128
721}
722
723pub fn default_full_checkpoint_contents_cache_size_mb() -> usize {
724    DEFAULT_FULL_CHECKPOINT_CONTENTS_CACHE_SIZE_MB
725}
726
727pub fn bool_true() -> bool {
728    true
729}
730
731impl Config for NodeConfig {}
732
733impl NodeConfig {
734    pub fn authority_key_pair(&self) -> &AuthorityKeyPair {
735        self.authority_key_pair.authority_keypair()
736    }
737
738    pub fn protocol_key_pair(&self) -> &NetworkKeyPair {
739        self.protocol_key_pair.ed25519_keypair()
740    }
741
742    pub fn network_key_pair(&self) -> &NetworkKeyPair {
743        self.network_key_pair.ed25519_keypair()
744    }
745
746    pub fn authority_public_key(&self) -> AuthorityPublicKeyBytes {
747        self.authority_key_pair().public().into()
748    }
749
750    pub fn db_path(&self) -> PathBuf {
751        self.db_path.join("live")
752    }
753
754    pub fn db_checkpoint_path(&self) -> PathBuf {
755        self.db_path.join("db_checkpoints")
756    }
757
758    pub fn snapshot_path(&self) -> PathBuf {
759        self.db_path.join("snapshot")
760    }
761
762    pub fn network_address(&self) -> &Multiaddr {
763        &self.network_address
764    }
765
766    pub fn consensus_config(&self) -> Option<&ConsensusConfig> {
767        self.consensus_config.as_ref()
768    }
769
770    pub fn genesis(&self) -> Result<&genesis::Genesis> {
771        self.genesis.genesis()
772    }
773
774    pub fn load_migration_tx_data(&self) -> Result<MigrationTxData> {
775        let Some(location) = &self.migration_tx_data_path else {
776            anyhow::bail!("no file location set");
777        };
778
779        // Load from file
780        let migration_tx_data = MigrationTxData::load(location)?;
781
782        // Validate migration content in order to avoid corrupted or malicious data
783        migration_tx_data.validate_from_genesis(self.genesis.genesis()?)?;
784        Ok(migration_tx_data)
785    }
786
787    pub fn iota_address(&self) -> Address {
788        self.account_key_pair
789            .keypair()
790            .public_key()
791            .derive_address()
792    }
793
794    pub fn checkpoint_archive_config(&self) -> Option<&CheckpointArchiveConfig> {
795        self.checkpoint_archive_config.as_ref()
796    }
797
798    pub fn jsonrpc_server_type(&self) -> ServerType {
799        self.jsonrpc_server_type.unwrap_or(ServerType::Http)
800    }
801}
802
803#[derive(Debug, Clone, Deserialize, Serialize)]
804#[serde(rename_all = "kebab-case")]
805pub struct ConsensusConfig {
806    /// Base consensus DB path for all epochs.
807    pub db_path: PathBuf,
808
809    /// The number of epochs for which to retain the consensus DBs.
810    /// Setting it to 0 will make a consensus DB getting dropped
811    /// as soon as system is switched to a new epoch.
812    pub db_retention_epochs: Option<u64>,
813
814    /// Pruner will run on every epoch change but it will also check
815    /// periodically on every `db_pruner_period_secs` seconds to see
816    /// if there are any epoch DBs to remove.
817    pub db_pruner_period_secs: Option<u64>,
818
819    /// Hard limit on the number of pending transactions to submit to
820    /// consensus, including those in submission wait. Used as the upper
821    /// bound for graduated pre-consensus load shedding
822    /// (`graduated_load_shedding_soft_limit_pct`) in the certificate-less
823    /// (P-COOL) mode, and as the threshold for the binary
824    /// cutoff in `ConsensusAdapter::check_consensus_overload()` in both
825    /// certificate-less and certificate-based flows.
826    ///
827    /// Default to 20_000 inflight limit, assuming 20_000 txn tps * 1 sec
828    /// consensus latency.
829    pub max_pending_transactions: Option<usize>,
830
831    /// When defined caps the calculated submission position to the
832    /// max_submit_position.
833    ///
834    /// Even if the is elected to submit from a higher
835    /// position than this, it will "reset" to the max_submit_position.
836    pub max_submit_position: Option<usize>,
837
838    /// The submit delay step to consensus defined in milliseconds.
839    ///
840    /// When provided it will override the current back off logic otherwise the
841    /// default backoff logic will be applied based on consensus latency
842    /// estimates.
843    pub submit_delay_step_override_millis: Option<u64>,
844
845    /// Parameters for Starfish consensus
846    #[serde(skip_serializing_if = "Option::is_none", alias = "starfish_parameters")]
847    pub parameters: Option<StarfishParameters>,
848
849    /// Percentage of `max_pending_transactions` (hard limit) defining the soft
850    /// limit at which graduated pre-consensus load shedding begins. When
851    /// in-flight transactions are at or below the soft limit, no shedding
852    /// occurs; above it, the shedding rate scales linearly from 0% to 100% at
853    /// `max_pending_transactions`. Used in the certificate-less (P-COOL) mode.
854    #[serde(skip_serializing_if = "Option::is_none")]
855    pub graduated_load_shedding_soft_limit_pct: Option<u32>,
856}
857
858impl ConsensusConfig {
859    pub fn db_path(&self) -> &Path {
860        &self.db_path
861    }
862
863    /// Returns the hard limit on the number of pending transactions to submit
864    /// to consensus, including those in submission wait. Defaults to 20_000
865    /// inflight limit, assuming 20_000 txn tps * 1 sec consensus latency.
866    pub fn max_pending_transactions(&self) -> usize {
867        self.max_pending_transactions.unwrap_or(20_000)
868    }
869
870    /// Returns the percentage of `max_pending_transactions` (hard limit)
871    /// defining the soft limit at which graduated pre-consensus load
872    /// shedding begins. Defaults to 50%. Used in the certificate-less
873    /// (P-COOL) mode.
874    pub fn graduated_load_shedding_soft_limit_pct(&self) -> u32 {
875        self.graduated_load_shedding_soft_limit_pct
876            .unwrap_or(50)
877            .min(100)
878    }
879
880    pub fn submit_delay_step_override(&self) -> Option<Duration> {
881        self.submit_delay_step_override_millis
882            .map(Duration::from_millis)
883    }
884
885    pub fn db_retention_epochs(&self) -> u64 {
886        self.db_retention_epochs.unwrap_or(0)
887    }
888
889    pub fn db_pruner_period(&self) -> Duration {
890        // Default to 1 hour
891        self.db_pruner_period_secs
892            .map(Duration::from_secs)
893            .unwrap_or(Duration::from_secs(3_600))
894    }
895}
896
897#[derive(Clone, Debug, Deserialize, Serialize)]
898#[serde(rename_all = "kebab-case")]
899pub struct CheckpointExecutorConfig {
900    /// Upper bound on the number of checkpoints that can be concurrently
901    /// executed.
902    ///
903    /// If unspecified, this will default to `200`
904    #[serde(default = "default_checkpoint_execution_max_concurrency")]
905    pub checkpoint_execution_max_concurrency: usize,
906
907    /// Number of seconds to wait for effects of a batch of transactions
908    /// before logging a warning. Note that we will continue to retry
909    /// indefinitely.
910    ///
911    /// If unspecified, this will default to `10`.
912    #[serde(default = "default_local_execution_timeout_sec")]
913    pub local_execution_timeout_sec: u64,
914
915    /// Optional directory used for data ingestion pipeline.
916    ///
917    /// When specified, each executed checkpoint will be saved in a local
918    /// directory for post-processing
919    #[serde(default, skip_serializing_if = "Option::is_none")]
920    pub data_ingestion_dir: Option<PathBuf>,
921}
922
923#[derive(Clone, Debug, Default, Deserialize, Serialize)]
924#[serde(rename_all = "kebab-case")]
925pub struct ExpensiveSafetyCheckConfig {
926    /// If enabled, at epoch boundary, we will check that the storage
927    /// fund balance is always identical to the sum of the storage
928    /// rebate of all live objects, and that the total IOTA in the network
929    /// remains the same.
930    #[serde(default)]
931    enable_epoch_iota_conservation_check: bool,
932
933    /// If enabled, we will check that the total IOTA in all input objects of a
934    /// tx (both the Move part and the storage rebate) matches the total IOTA
935    /// in all output objects of the tx + gas fees.
936    #[serde(default)]
937    enable_deep_per_tx_iota_conservation_check: bool,
938
939    /// Disable epoch IOTA conservation check even when we are running in debug
940    /// mode.
941    #[serde(default)]
942    force_disable_epoch_iota_conservation_check: bool,
943
944    /// If enabled, at epoch boundary, we will check that the accumulated
945    /// live object state matches the end of epoch root state digest.
946    #[serde(default)]
947    enable_state_consistency_check: bool,
948
949    /// Disable state consistency check even when we are running in debug mode.
950    #[serde(default)]
951    force_disable_state_consistency_check: bool,
952
953    #[serde(default)]
954    enable_secondary_index_checks: bool,
955    // TODO: Add more expensive checks here
956}
957
958impl ExpensiveSafetyCheckConfig {
959    pub fn new_enable_all() -> Self {
960        Self {
961            enable_epoch_iota_conservation_check: true,
962            enable_deep_per_tx_iota_conservation_check: true,
963            force_disable_epoch_iota_conservation_check: false,
964            enable_state_consistency_check: true,
965            force_disable_state_consistency_check: false,
966            enable_secondary_index_checks: false, // Disable by default for now
967        }
968    }
969
970    pub fn new_disable_all() -> Self {
971        Self {
972            enable_epoch_iota_conservation_check: false,
973            enable_deep_per_tx_iota_conservation_check: false,
974            force_disable_epoch_iota_conservation_check: true,
975            enable_state_consistency_check: false,
976            force_disable_state_consistency_check: true,
977            enable_secondary_index_checks: false,
978        }
979    }
980
981    pub fn force_disable_epoch_iota_conservation_check(&mut self) {
982        self.force_disable_epoch_iota_conservation_check = true;
983    }
984
985    pub fn enable_epoch_iota_conservation_check(&self) -> bool {
986        (self.enable_epoch_iota_conservation_check || cfg!(debug_assertions))
987            && !self.force_disable_epoch_iota_conservation_check
988    }
989
990    pub fn force_disable_state_consistency_check(&mut self) {
991        self.force_disable_state_consistency_check = true;
992    }
993
994    pub fn enable_state_consistency_check(&self) -> bool {
995        (self.enable_state_consistency_check || cfg!(debug_assertions))
996            && !self.force_disable_state_consistency_check
997    }
998
999    pub fn enable_deep_per_tx_iota_conservation_check(&self) -> bool {
1000        self.enable_deep_per_tx_iota_conservation_check || cfg!(debug_assertions)
1001    }
1002
1003    pub fn enable_secondary_index_checks(&self) -> bool {
1004        self.enable_secondary_index_checks
1005    }
1006}
1007
1008fn default_checkpoint_execution_max_concurrency() -> usize {
1009    4
1010}
1011
1012fn default_local_execution_timeout_sec() -> u64 {
1013    30
1014}
1015
1016impl Default for CheckpointExecutorConfig {
1017    fn default() -> Self {
1018        Self {
1019            checkpoint_execution_max_concurrency: default_checkpoint_execution_max_concurrency(),
1020            local_execution_timeout_sec: default_local_execution_timeout_sec(),
1021            data_ingestion_dir: None,
1022        }
1023    }
1024}
1025
1026#[derive(Debug, Clone, Deserialize, Serialize)]
1027#[serde(rename_all = "kebab-case")]
1028pub struct AuthorityStorePruningConfig {
1029    /// number of the latest epoch dbs to retain
1030    #[serde(default = "default_num_latest_epoch_dbs_to_retain")]
1031    pub num_latest_epoch_dbs_to_retain: usize,
1032    /// number of epochs to keep the latest version of objects for.
1033    /// Note that a zero value corresponds to an aggressive pruner.
1034    /// This mode is experimental and needs to be used with caution.
1035    /// Use `u64::MAX` to disable the pruner for the objects.
1036    #[serde(default)]
1037    pub num_epochs_to_retain: u64,
1038    /// enables periodic background compaction for old SST files whose last
1039    /// modified time is older than `periodic_compaction_threshold_days`
1040    /// days. That ensures that all sst files eventually go through the
1041    /// compaction process
1042    #[serde(
1043        default = "default_periodic_compaction_threshold_days",
1044        skip_serializing_if = "Option::is_none"
1045    )]
1046    pub periodic_compaction_threshold_days: Option<usize>,
1047    /// number of epochs to keep the latest version of transactions and effects
1048    /// for
1049    #[serde(skip_serializing_if = "Option::is_none")]
1050    pub num_epochs_to_retain_for_checkpoints: Option<u64>,
1051    /// Enables the compaction filter for pruning the objects table.
1052    /// If disabled, a range deletion approach is used instead.
1053    /// While it is generally safe to switch between the two modes,
1054    /// switching from the compaction filter approach back to range deletion
1055    /// may result in some old versions that will never be pruned.
1056    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1057    pub enable_compaction_filter: bool,
1058    #[serde(skip_serializing_if = "Option::is_none")]
1059    pub num_epochs_to_retain_for_indexes: Option<u64>,
1060}
1061
1062fn default_num_latest_epoch_dbs_to_retain() -> usize {
1063    3
1064}
1065
1066fn default_periodic_compaction_threshold_days() -> Option<usize> {
1067    Some(1)
1068}
1069
1070impl Default for AuthorityStorePruningConfig {
1071    fn default() -> Self {
1072        Self {
1073            num_latest_epoch_dbs_to_retain: default_num_latest_epoch_dbs_to_retain(),
1074            num_epochs_to_retain: 0,
1075            periodic_compaction_threshold_days: None,
1076            num_epochs_to_retain_for_checkpoints: if cfg!(msim) { Some(2) } else { None },
1077            enable_compaction_filter: cfg!(test) || cfg!(msim),
1078            num_epochs_to_retain_for_indexes: None,
1079        }
1080    }
1081}
1082
1083impl AuthorityStorePruningConfig {
1084    pub fn set_num_epochs_to_retain(&mut self, num_epochs_to_retain: u64) {
1085        self.num_epochs_to_retain = num_epochs_to_retain;
1086    }
1087
1088    pub fn set_num_epochs_to_retain_for_checkpoints(&mut self, num_epochs_to_retain: Option<u64>) {
1089        self.num_epochs_to_retain_for_checkpoints = num_epochs_to_retain;
1090    }
1091
1092    pub fn num_epochs_to_retain_for_checkpoints(&self) -> Option<u64> {
1093        self.num_epochs_to_retain_for_checkpoints
1094            // if n less than 2, coerce to 2 and log
1095            .map(|n| {
1096                if n < 2 {
1097                    info!("num_epochs_to_retain_for_checkpoints must be at least 2, rounding up from {}", n);
1098                    2
1099                } else {
1100                    n
1101                }
1102            })
1103    }
1104}
1105
1106#[derive(Debug, Clone, Deserialize, Serialize)]
1107#[serde(rename_all = "kebab-case")]
1108pub struct MetricsConfig {
1109    #[serde(skip_serializing_if = "Option::is_none")]
1110    pub push_interval_seconds: Option<u64>,
1111    #[serde(skip_serializing_if = "Option::is_none")]
1112    pub push_url: Option<String>,
1113    #[serde(skip_serializing_if = "Option::is_none")]
1114    pub groups: Option<MetricGroups>,
1115}
1116
1117fn default_checkpoint_archive_download_concurrency() -> usize {
1118    10
1119}
1120
1121/// Configuration for backfilling checkpoint contents from the
1122/// checkpoint archive when peers no longer serve the required range.
1123#[derive(Debug, Clone, Deserialize, Serialize)]
1124#[serde(rename_all = "kebab-case")]
1125pub struct CheckpointArchiveConfig {
1126    /// URL of the checkpoint archive to backfill from.
1127    pub url: String,
1128    /// Non-zero number of checkpoints to download in parallel.
1129    #[serde(default = "default_checkpoint_archive_download_concurrency")]
1130    pub download_concurrency: usize,
1131}
1132
1133/// Configuration for the per-epoch state-snapshot publisher.
1134///
1135/// **Operator note (V2 snapshot publishing).** A node configured to publish
1136/// V2 snapshots must have a perpetual store containing no pre-V2
1137/// (`StoreObjectV1`) rows. This means a snapshot-publishing node must have
1138/// either synced from genesis under V2 or been restored from a V2 snapshot.
1139/// There is no on-disk backfill: a fresh sync is the only supported path.
1140#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1141#[serde(rename_all = "kebab-case")]
1142pub struct StateSnapshotConfig {
1143    #[serde(skip_serializing_if = "Option::is_none")]
1144    pub object_store_config: Option<ObjectStoreConfig>,
1145    pub concurrency: usize,
1146}
1147
1148#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1149#[serde(rename_all = "kebab-case")]
1150pub struct TransactionKeyValueStoreWriteConfig {
1151    pub aws_access_key_id: String,
1152    pub aws_secret_access_key: String,
1153    pub aws_region: String,
1154    pub table_name: String,
1155    pub bucket_name: String,
1156    pub concurrency: usize,
1157}
1158
1159/// Configuration for the threshold(s) at which we consider the system
1160/// to be overloaded. When one of the threshold is passed, the node may
1161/// stop processing new transactions and/or certificates until the congestion
1162/// resolves.
1163#[derive(Clone, Debug, Deserialize, Serialize)]
1164#[serde(rename_all = "kebab-case")]
1165pub struct AuthorityOverloadConfig {
1166    /// Maximum time a transaction can wait in the transaction manager execution
1167    /// queue before it triggers an overload detection on the object it depends
1168    /// on.
1169    #[serde(default = "default_max_txn_age_in_queue")]
1170    pub max_txn_age_in_queue: Duration,
1171
1172    /// The interval of checking overload signal.
1173    #[serde(default = "default_overload_monitor_interval")]
1174    pub overload_monitor_interval: Duration,
1175
1176    /// The execution queueing latency when entering load shedding mode.
1177    #[serde(default = "default_execution_queue_latency_soft_limit")]
1178    pub execution_queue_latency_soft_limit: Duration,
1179
1180    /// The execution queueing latency when entering aggressive load shedding
1181    /// mode.
1182    #[serde(default = "default_execution_queue_latency_hard_limit")]
1183    pub execution_queue_latency_hard_limit: Duration,
1184
1185    /// The maximum percentage of transactions to shed in load shedding mode.
1186    #[serde(default = "default_max_load_shedding_percentage")]
1187    pub max_load_shedding_percentage: u32,
1188
1189    /// When in aggressive load shedding mode, the minimum percentage of
1190    /// transactions to shed.
1191    #[serde(default = "default_min_load_shedding_percentage_above_hard_limit")]
1192    pub min_load_shedding_percentage_above_hard_limit: u32,
1193
1194    /// If transaction ready rate is below this rate, we consider the validator
1195    /// is well under used, and will not enter load shedding mode.
1196    #[serde(default = "default_safe_transaction_ready_rate")]
1197    pub safe_transaction_ready_rate: u32,
1198
1199    /// When set to true, transaction signing may be rejected when the validator
1200    /// is overloaded.
1201    #[serde(default = "default_check_system_overload_at_signing")]
1202    pub check_system_overload_at_signing: bool,
1203
1204    /// When set to true, transaction execution may be rejected when the
1205    /// validator is overloaded.
1206    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1207    pub check_system_overload_at_execution: bool,
1208
1209    /// Reject a transaction if transaction manager queue length is above this
1210    /// threshold. 100_000 = 10k TPS * 5s resident time in transaction
1211    /// manager (pending + executing) * 2.
1212    #[serde(default = "default_max_transaction_manager_queue_length")]
1213    pub max_transaction_manager_queue_length: usize,
1214
1215    /// Reject a transaction if the number of pending transactions depending on
1216    /// the object is above the threshold.
1217    #[serde(default = "default_max_transaction_manager_per_object_queue_length")]
1218    pub max_transaction_manager_per_object_queue_length: usize,
1219
1220    /// Percentage of `max_transaction_manager_queue_length` at which graduated
1221    /// load shedding begins in the certificate-less (P-COOL) mode. Read
1222    /// via the same-named accessor, which clamps the value to <=100.
1223    #[serde(default = "default_max_transaction_manager_queue_length_soft_limit_pct")]
1224    pub max_transaction_manager_queue_length_soft_limit_pct: u32,
1225}
1226
1227impl AuthorityOverloadConfig {
1228    /// Returns the soft-limit percentage, clamped to <=100 to guard against
1229    /// out-of-range operator-supplied values.
1230    pub fn max_transaction_manager_queue_length_soft_limit_pct(&self) -> u32 {
1231        self.max_transaction_manager_queue_length_soft_limit_pct
1232            .min(100)
1233    }
1234}
1235
1236fn default_max_txn_age_in_queue() -> Duration {
1237    Duration::from_millis(500)
1238}
1239
1240fn default_overload_monitor_interval() -> Duration {
1241    Duration::from_secs(10)
1242}
1243
1244fn default_execution_queue_latency_soft_limit() -> Duration {
1245    Duration::from_secs(1)
1246}
1247
1248fn default_execution_queue_latency_hard_limit() -> Duration {
1249    Duration::from_secs(10)
1250}
1251
1252fn default_max_load_shedding_percentage() -> u32 {
1253    95
1254}
1255
1256fn default_min_load_shedding_percentage_above_hard_limit() -> u32 {
1257    50
1258}
1259
1260fn default_safe_transaction_ready_rate() -> u32 {
1261    100
1262}
1263
1264fn default_check_system_overload_at_signing() -> bool {
1265    true
1266}
1267
1268fn default_max_transaction_manager_queue_length() -> usize {
1269    100_000
1270}
1271
1272fn default_max_transaction_manager_queue_length_soft_limit_pct() -> u32 {
1273    50
1274}
1275
1276fn default_max_transaction_manager_per_object_queue_length() -> usize {
1277    20
1278}
1279
1280impl Default for AuthorityOverloadConfig {
1281    fn default() -> Self {
1282        Self {
1283            max_txn_age_in_queue: default_max_txn_age_in_queue(),
1284            overload_monitor_interval: default_overload_monitor_interval(),
1285            execution_queue_latency_soft_limit: default_execution_queue_latency_soft_limit(),
1286            execution_queue_latency_hard_limit: default_execution_queue_latency_hard_limit(),
1287            max_load_shedding_percentage: default_max_load_shedding_percentage(),
1288            min_load_shedding_percentage_above_hard_limit:
1289                default_min_load_shedding_percentage_above_hard_limit(),
1290            safe_transaction_ready_rate: default_safe_transaction_ready_rate(),
1291            check_system_overload_at_signing: true,
1292            check_system_overload_at_execution: false,
1293            max_transaction_manager_queue_length: default_max_transaction_manager_queue_length(),
1294            max_transaction_manager_queue_length_soft_limit_pct:
1295                default_max_transaction_manager_queue_length_soft_limit_pct(),
1296            max_transaction_manager_per_object_queue_length:
1297                default_max_transaction_manager_per_object_queue_length(),
1298        }
1299    }
1300}
1301
1302fn default_authority_overload_config() -> AuthorityOverloadConfig {
1303    AuthorityOverloadConfig::default()
1304}
1305
1306fn default_traffic_controller_policy_config() -> Option<PolicyConfig> {
1307    Some(PolicyConfig::default_dos_protection_policy())
1308}
1309
1310#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1311pub struct Genesis {
1312    #[serde(flatten)]
1313    location: Option<GenesisLocation>,
1314
1315    #[serde(skip)]
1316    genesis: once_cell::sync::OnceCell<genesis::Genesis>,
1317}
1318
1319impl Genesis {
1320    pub fn new(genesis: genesis::Genesis) -> Self {
1321        Self {
1322            location: Some(GenesisLocation::InPlace {
1323                genesis: Box::new(genesis),
1324            }),
1325            genesis: Default::default(),
1326        }
1327    }
1328
1329    pub fn new_from_file<P: Into<PathBuf>>(path: P) -> Self {
1330        Self {
1331            location: Some(GenesisLocation::File {
1332                genesis_file_location: path.into(),
1333            }),
1334            genesis: Default::default(),
1335        }
1336    }
1337
1338    pub fn new_empty() -> Self {
1339        Self {
1340            location: None,
1341            genesis: Default::default(),
1342        }
1343    }
1344
1345    pub fn genesis(&self) -> Result<&genesis::Genesis> {
1346        match &self.location {
1347            Some(GenesisLocation::InPlace { genesis }) => Ok(genesis),
1348            Some(GenesisLocation::File {
1349                genesis_file_location,
1350            }) => self
1351                .genesis
1352                .get_or_try_init(|| genesis::Genesis::load(genesis_file_location)),
1353            None => anyhow::bail!("no genesis location set"),
1354        }
1355    }
1356}
1357
1358#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1359#[serde(untagged)]
1360enum GenesisLocation {
1361    InPlace {
1362        genesis: Box<genesis::Genesis>,
1363    },
1364    File {
1365        #[serde(rename = "genesis-file-location")]
1366        genesis_file_location: PathBuf,
1367    },
1368}
1369
1370/// Wrapper struct for SimpleKeypair that can be deserialized from a file path.
1371/// Used by network, worker, and account keypair.
1372#[derive(Clone, Debug, Deserialize, Serialize)]
1373pub struct KeyPairWithPath {
1374    #[serde(flatten)]
1375    location: KeyPairLocation,
1376
1377    #[serde(skip)]
1378    keypair: OnceCell<Arc<SimpleKeypair>>,
1379
1380    // The consensus/network stacks borrow their key as `&Ed25519KeyPair`
1381    // (fastcrypto), while the key itself is stored as an SDK `SimpleKeypair`
1382    // above. Converting on each access would return an owned value, which
1383    // can't back the `&`-returning accessors, so the converted key is cached
1384    // here. Never populated for account keys.
1385    #[serde(skip)]
1386    ed25519_keypair: OnceCell<Arc<Ed25519KeyPair>>,
1387}
1388
1389impl PartialEq for KeyPairWithPath {
1390    fn eq(&self, other: &Self) -> bool {
1391        self.location == other.location
1392    }
1393}
1394
1395impl Eq for KeyPairWithPath {}
1396
1397#[derive(Debug, Clone, Deserialize, Serialize)]
1398#[serde(untagged)]
1399enum KeyPairLocation {
1400    InPlace {
1401        #[serde(with = "bech32_formatted_keypair")]
1402        value: Arc<SimpleKeypair>,
1403    },
1404    File {
1405        path: PathBuf,
1406    },
1407}
1408
1409impl PartialEq for KeyPairLocation {
1410    fn eq(&self, other: &Self) -> bool {
1411        match (self, other) {
1412            (Self::InPlace { value: a }, Self::InPlace { value: b }) => {
1413                a.to_bytes() == b.to_bytes()
1414            }
1415            (Self::File { path: a }, Self::File { path: b }) => a == b,
1416            _ => false,
1417        }
1418    }
1419}
1420
1421impl Eq for KeyPairLocation {}
1422
1423impl KeyPairWithPath {
1424    pub fn new(kp: SimpleKeypair) -> Self {
1425        let cell: OnceCell<Arc<SimpleKeypair>> = OnceCell::new();
1426        let arc_kp = Arc::new(kp);
1427        // OK to unwrap panic because authority should not start without all keypairs
1428        // loaded.
1429        cell.set(arc_kp.clone()).expect("failed to set keypair");
1430        Self {
1431            location: KeyPairLocation::InPlace { value: arc_kp },
1432            keypair: cell,
1433            ed25519_keypair: OnceCell::new(),
1434        }
1435    }
1436
1437    pub fn new_from_path(path: PathBuf) -> Self {
1438        let cell: OnceCell<Arc<SimpleKeypair>> = OnceCell::new();
1439        // OK to unwrap panic because authority should not start without all keypairs
1440        // loaded.
1441        cell.set(Arc::new(read_keypair_from_file(&path).unwrap_or_else(
1442            |e| panic!("invalid keypair file at path {path:?}: {e}"),
1443        )))
1444        .expect("failed to set keypair");
1445        Self {
1446            location: KeyPairLocation::File { path },
1447            keypair: cell,
1448            ed25519_keypair: OnceCell::new(),
1449        }
1450    }
1451
1452    pub fn keypair(&self) -> &SimpleKeypair {
1453        self.keypair
1454            .get_or_init(|| match &self.location {
1455                KeyPairLocation::InPlace { value } => value.clone(),
1456                KeyPairLocation::File { path } => {
1457                    // OK to unwrap panic because authority should not start without all keypairs
1458                    // loaded.
1459                    Arc::new(
1460                        read_keypair_from_file(path).unwrap_or_else(|e| {
1461                            panic!("invalid keypair file at path {path:?}: {e}")
1462                        }),
1463                    )
1464                }
1465            })
1466            .as_ref()
1467    }
1468
1469    /// The keypair as a fastcrypto ed25519 keypair, for the network stacks
1470    /// that consume that type directly. Panics if the stored keypair is not
1471    /// ed25519.
1472    pub fn ed25519_keypair(&self) -> &Ed25519KeyPair {
1473        self.ed25519_keypair
1474            .get_or_init(|| {
1475                Arc::new(
1476                    simple_to_network_keypair(self.keypair())
1477                        .expect("only Ed25519 network keys are allowed"),
1478                )
1479            })
1480            .as_ref()
1481    }
1482}
1483
1484/// Wrapper struct for AuthorityKeyPair that can be deserialized from a file
1485/// path.
1486#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
1487pub struct AuthorityKeyPairWithPath {
1488    #[serde(flatten)]
1489    location: AuthorityKeyPairLocation,
1490
1491    #[serde(skip)]
1492    keypair: OnceCell<Arc<AuthorityKeyPair>>,
1493}
1494
1495#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1496#[serde(untagged)]
1497enum AuthorityKeyPairLocation {
1498    InPlace { value: Arc<AuthorityKeyPair> },
1499    File { path: PathBuf },
1500}
1501
1502impl AuthorityKeyPairWithPath {
1503    pub fn new(kp: AuthorityKeyPair) -> Self {
1504        let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1505        let arc_kp = Arc::new(kp);
1506        // OK to unwrap panic because authority should not start without all keypairs
1507        // loaded.
1508        cell.set(arc_kp.clone())
1509            .expect("failed to set authority keypair");
1510        Self {
1511            location: AuthorityKeyPairLocation::InPlace { value: arc_kp },
1512            keypair: cell,
1513        }
1514    }
1515
1516    pub fn new_from_path(path: PathBuf) -> Self {
1517        let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1518        // OK to unwrap panic because authority should not start without all keypairs
1519        // loaded.
1520        cell.set(Arc::new(
1521            read_authority_keypair_from_file(&path)
1522                .unwrap_or_else(|_| panic!("invalid authority keypair file at path {path:?}")),
1523        ))
1524        .expect("failed to set authority keypair");
1525        Self {
1526            location: AuthorityKeyPairLocation::File { path },
1527            keypair: cell,
1528        }
1529    }
1530
1531    pub fn authority_keypair(&self) -> &AuthorityKeyPair {
1532        self.keypair
1533            .get_or_init(|| match &self.location {
1534                AuthorityKeyPairLocation::InPlace { value } => value.clone(),
1535                AuthorityKeyPairLocation::File { path } => {
1536                    // OK to unwrap panic because authority should not start without all keypairs
1537                    // loaded.
1538                    Arc::new(
1539                        read_authority_keypair_from_file(path)
1540                            .unwrap_or_else(|_| panic!("invalid authority keypair file {path:?}")),
1541                    )
1542                }
1543            })
1544            .as_ref()
1545    }
1546}
1547
1548/// Configurations which determine how we dump state debug info.
1549/// Debug info is dumped when a node forks.
1550#[derive(Clone, Debug, Deserialize, Serialize, Default)]
1551#[serde(rename_all = "kebab-case")]
1552pub struct StateDebugDumpConfig {
1553    #[serde(skip_serializing_if = "Option::is_none")]
1554    pub dump_file_directory: Option<PathBuf>,
1555}
1556
1557#[cfg(test)]
1558mod tests {
1559    use std::path::PathBuf;
1560
1561    use fastcrypto::traits::KeyPair;
1562    use iota_keys::keypair_file::{write_authority_keypair_to_file, write_keypair_to_file};
1563    use iota_types::crypto::{
1564        AuthorityKeyPair, NetworkKeyPair, get_key_pair_from_rng, network_to_simple_keypair,
1565    };
1566    use rand::{SeedableRng, rngs::StdRng};
1567
1568    use super::Genesis;
1569    use crate::NodeConfig;
1570
1571    #[test]
1572    fn serialize_genesis_from_file() {
1573        let g = Genesis::new_from_file("path/to/file");
1574
1575        let s = serde_yaml::to_string(&g).unwrap();
1576        assert_eq!("---\ngenesis-file-location: path/to/file\n", s);
1577        let loaded_genesis: Genesis = serde_yaml::from_str(&s).unwrap();
1578        assert_eq!(g, loaded_genesis);
1579    }
1580
1581    #[test]
1582    fn fullnode_template() {
1583        const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1584
1585        let _template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1586    }
1587
1588    #[test]
1589    fn enable_soft_locking_defaults_to_enabled() {
1590        // The template omits `enable-soft-locking`, so this exercises the serde
1591        // default and pins the documented "default: enabled" contract.
1592        const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1593
1594        let config: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1595        assert!(config.enable_soft_locking);
1596    }
1597
1598    #[test]
1599    fn load_key_pairs_to_node_config() {
1600        let authority_key_pair: AuthorityKeyPair =
1601            get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1602        let protocol_key_pair: NetworkKeyPair =
1603            get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1604        let network_key_pair: NetworkKeyPair =
1605            get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1606
1607        write_authority_keypair_to_file(&authority_key_pair, PathBuf::from("authority.key"))
1608            .unwrap();
1609        write_keypair_to_file(
1610            &network_to_simple_keypair(&protocol_key_pair),
1611            PathBuf::from("protocol.key"),
1612        )
1613        .unwrap();
1614        write_keypair_to_file(
1615            &network_to_simple_keypair(&network_key_pair),
1616            PathBuf::from("network.key"),
1617        )
1618        .unwrap();
1619
1620        const TEMPLATE: &str = include_str!("../data/fullnode-template-with-path.yaml");
1621        let template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1622        assert_eq!(
1623            template.authority_key_pair().public(),
1624            authority_key_pair.public()
1625        );
1626        assert_eq!(
1627            template.network_key_pair().public(),
1628            network_key_pair.public()
1629        );
1630        assert_eq!(
1631            template.protocol_key_pair().public(),
1632            protocol_key_pair.public()
1633        );
1634    }
1635}
1636
1637// RunWithRange is used to specify the ending epoch/checkpoint to process.
1638// this is intended for use with disaster recovery debugging and verification
1639// workflows, never in normal operations
1640#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
1641pub enum RunWithRange {
1642    Epoch(EpochId),
1643    Checkpoint(CheckpointSequenceNumber),
1644}
1645
1646impl RunWithRange {
1647    // is epoch_id > RunWithRange::Epoch
1648    pub fn is_epoch_gt(&self, epoch_id: EpochId) -> bool {
1649        matches!(self, RunWithRange::Epoch(e) if epoch_id > *e)
1650    }
1651
1652    pub fn matches_checkpoint(&self, seq_num: CheckpointSequenceNumber) -> bool {
1653        matches!(self, RunWithRange::Checkpoint(seq) if *seq == seq_num)
1654    }
1655
1656    pub fn into_checkpoint_bound(self) -> Option<CheckpointSequenceNumber> {
1657        match self {
1658            RunWithRange::Epoch(_) => None,
1659            RunWithRange::Checkpoint(seq) => Some(seq),
1660        }
1661    }
1662}
1663
1664/// A serde helper module used with #[serde(with = "...")] to change the
1665/// de/serialization format of an `SimpleKeypair` to Bech32 when written to or
1666/// read from a node config.
1667mod bech32_formatted_keypair {
1668    use std::ops::Deref;
1669
1670    use fastcrypto::encoding::{Base64, Encoding};
1671    use iota_sdk_crypto::{ToFromBech32, simple::SimpleKeypair};
1672    use serde::{Deserialize, Deserializer, Serializer};
1673
1674    pub fn serialize<S, T>(kp: &T, serializer: S) -> Result<S::Ok, S::Error>
1675    where
1676        S: Serializer,
1677        T: Deref<Target = SimpleKeypair>,
1678    {
1679        use serde::ser::Error;
1680
1681        // Serialize the keypair to a Bech32 string
1682        let s = kp.to_bech32().map_err(Error::custom)?;
1683
1684        serializer.serialize_str(&s)
1685    }
1686
1687    pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
1688    where
1689        D: Deserializer<'de>,
1690        T: From<SimpleKeypair>,
1691    {
1692        use serde::de::Error;
1693
1694        let s = String::deserialize(deserializer)?;
1695
1696        // Try to deserialize the keypair from a Bech32 formatted string
1697        SimpleKeypair::from_bech32(&s)
1698            .map_err(Error::custom)
1699            .or_else(|_: D::Error| {
1700                // For backwards compatibility try Base64 if Bech32 failed
1701                let bytes = Base64::decode(&s).map_err(Error::custom)?;
1702                SimpleKeypair::from_bytes(&bytes).map_err(Error::custom)
1703            })
1704            .map(Into::into)
1705    }
1706}