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_multiaddr::Multiaddr;
18use iota_names::config::IotaNamesConfig;
19use iota_sdk_crypto::simple::SimpleKeypair;
20use iota_sdk_types::Address;
21use iota_types::{
22    committee::EpochId,
23    crypto::{
24        AccountKeyPair, AuthorityKeyPair, AuthorityPublicKeyBytes, KeypairTraits, NetworkKeyPair,
25        get_key_pair_from_rng, simple_to_network_keypair,
26    },
27    messages_checkpoint::CheckpointSequenceNumber,
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() -> NonZeroUsize {
1114    NonZeroUsize::new(10).unwrap()
1115}
1116
1117fn default_checkpoint_archive_verify_concurrency() -> NonZeroUsize {
1118    std::thread::available_parallelism().unwrap_or(NonZeroUsize::new(4).unwrap())
1119}
1120
1121fn default_checkpoint_archive_max_checkpoints_ahead_of_execution() -> NonZeroUsize {
1122    NonZeroUsize::new(100_000).unwrap()
1123}
1124
1125/// Configuration for backfilling checkpoint contents from the
1126/// checkpoint archive when peers no longer serve the required range.
1127#[derive(Debug, Clone, Deserialize, Serialize)]
1128#[serde(rename_all = "kebab-case")]
1129pub struct CheckpointArchiveConfig {
1130    /// URL of the checkpoint archive to backfill from.
1131    pub url: String,
1132    /// Non-zero number of checkpoints to download in parallel.
1133    #[serde(default = "default_checkpoint_archive_download_concurrency")]
1134    pub download_concurrency: NonZeroUsize,
1135    /// Non-zero number of downloaded checkpoints to verify in parallel.
1136    /// Defaults to the number of CPU cores.
1137    #[serde(default = "default_checkpoint_archive_verify_concurrency")]
1138    pub verify_concurrency: NonZeroUsize,
1139    /// Pause downloading from the archive while the synced watermark is this
1140    /// many checkpoints ahead of the executed watermark, and resume once
1141    /// execution catches up. Bounds the disk space held by checkpoints that
1142    /// are synced but not yet executed, since only executed checkpoints can
1143    /// be pruned.
1144    #[serde(default = "default_checkpoint_archive_max_checkpoints_ahead_of_execution")]
1145    pub max_checkpoints_ahead_of_execution: NonZeroUsize,
1146}
1147
1148/// Configuration for the per-epoch state-snapshot publisher.
1149///
1150/// **Operator note (V2 snapshot publishing).** A node configured to publish
1151/// V2 snapshots must have a perpetual store containing no pre-V2
1152/// (`StoreObjectV1`) rows. This means a snapshot-publishing node must have
1153/// either synced from genesis under V2 or been restored from a V2 snapshot.
1154/// There is no on-disk backfill: a fresh sync is the only supported path.
1155#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1156#[serde(rename_all = "kebab-case")]
1157pub struct StateSnapshotConfig {
1158    #[serde(skip_serializing_if = "Option::is_none")]
1159    pub object_store_config: Option<ObjectStoreConfig>,
1160    pub concurrency: usize,
1161}
1162
1163#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1164#[serde(rename_all = "kebab-case")]
1165pub struct TransactionKeyValueStoreWriteConfig {
1166    pub aws_access_key_id: String,
1167    pub aws_secret_access_key: String,
1168    pub aws_region: String,
1169    pub table_name: String,
1170    pub bucket_name: String,
1171    pub concurrency: usize,
1172}
1173
1174/// Configuration for the threshold(s) at which we consider the system
1175/// to be overloaded. When one of the threshold is passed, the node may
1176/// stop processing new transactions and/or certificates until the congestion
1177/// resolves.
1178#[derive(Clone, Debug, Deserialize, Serialize)]
1179#[serde(rename_all = "kebab-case")]
1180pub struct AuthorityOverloadConfig {
1181    /// Maximum time a transaction can wait in the transaction manager execution
1182    /// queue before it triggers an overload detection on the object it depends
1183    /// on.
1184    #[serde(default = "default_max_txn_age_in_queue")]
1185    pub max_txn_age_in_queue: Duration,
1186
1187    /// The interval of checking overload signal.
1188    #[serde(default = "default_overload_monitor_interval")]
1189    pub overload_monitor_interval: Duration,
1190
1191    /// The execution queueing latency when entering load shedding mode.
1192    #[serde(default = "default_execution_queue_latency_soft_limit")]
1193    pub execution_queue_latency_soft_limit: Duration,
1194
1195    /// The execution queueing latency when entering aggressive load shedding
1196    /// mode.
1197    #[serde(default = "default_execution_queue_latency_hard_limit")]
1198    pub execution_queue_latency_hard_limit: Duration,
1199
1200    /// The maximum percentage of transactions to shed in load shedding mode.
1201    #[serde(default = "default_max_load_shedding_percentage")]
1202    pub max_load_shedding_percentage: u32,
1203
1204    /// When in aggressive load shedding mode, the minimum percentage of
1205    /// transactions to shed.
1206    #[serde(default = "default_min_load_shedding_percentage_above_hard_limit")]
1207    pub min_load_shedding_percentage_above_hard_limit: u32,
1208
1209    /// If transaction ready rate is below this rate, we consider the validator
1210    /// is well under used, and will not enter load shedding mode.
1211    #[serde(default = "default_safe_transaction_ready_rate")]
1212    pub safe_transaction_ready_rate: u32,
1213
1214    /// When set to true, transaction signing may be rejected when the validator
1215    /// is overloaded.
1216    #[serde(default = "default_check_system_overload_at_signing")]
1217    pub check_system_overload_at_signing: bool,
1218
1219    /// When set to true, transaction execution may be rejected when the
1220    /// validator is overloaded.
1221    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1222    pub check_system_overload_at_execution: bool,
1223
1224    /// Reject a transaction if transaction manager queue length is above this
1225    /// threshold. 100_000 = 10k TPS * 5s resident time in transaction
1226    /// manager (pending + executing) * 2.
1227    #[serde(default = "default_max_transaction_manager_queue_length")]
1228    pub max_transaction_manager_queue_length: usize,
1229
1230    /// Reject a transaction if the number of pending transactions depending on
1231    /// the object is above the threshold.
1232    #[serde(default = "default_max_transaction_manager_per_object_queue_length")]
1233    pub max_transaction_manager_per_object_queue_length: usize,
1234
1235    /// Percentage of `max_transaction_manager_queue_length` at which graduated
1236    /// load shedding begins in the certificate-less (P-COOL) mode. Read
1237    /// via the same-named accessor, which clamps the value to <=100.
1238    #[serde(default = "default_max_transaction_manager_queue_length_soft_limit_pct")]
1239    pub max_transaction_manager_queue_length_soft_limit_pct: u32,
1240}
1241
1242impl AuthorityOverloadConfig {
1243    /// Returns the soft-limit percentage, clamped to <=100 to guard against
1244    /// out-of-range operator-supplied values.
1245    pub fn max_transaction_manager_queue_length_soft_limit_pct(&self) -> u32 {
1246        self.max_transaction_manager_queue_length_soft_limit_pct
1247            .min(100)
1248    }
1249}
1250
1251fn default_max_txn_age_in_queue() -> Duration {
1252    Duration::from_millis(500)
1253}
1254
1255fn default_overload_monitor_interval() -> Duration {
1256    Duration::from_secs(10)
1257}
1258
1259fn default_execution_queue_latency_soft_limit() -> Duration {
1260    Duration::from_secs(1)
1261}
1262
1263fn default_execution_queue_latency_hard_limit() -> Duration {
1264    Duration::from_secs(10)
1265}
1266
1267fn default_max_load_shedding_percentage() -> u32 {
1268    95
1269}
1270
1271fn default_min_load_shedding_percentage_above_hard_limit() -> u32 {
1272    50
1273}
1274
1275fn default_safe_transaction_ready_rate() -> u32 {
1276    100
1277}
1278
1279fn default_check_system_overload_at_signing() -> bool {
1280    true
1281}
1282
1283fn default_max_transaction_manager_queue_length() -> usize {
1284    100_000
1285}
1286
1287fn default_max_transaction_manager_queue_length_soft_limit_pct() -> u32 {
1288    50
1289}
1290
1291fn default_max_transaction_manager_per_object_queue_length() -> usize {
1292    20
1293}
1294
1295impl Default for AuthorityOverloadConfig {
1296    fn default() -> Self {
1297        Self {
1298            max_txn_age_in_queue: default_max_txn_age_in_queue(),
1299            overload_monitor_interval: default_overload_monitor_interval(),
1300            execution_queue_latency_soft_limit: default_execution_queue_latency_soft_limit(),
1301            execution_queue_latency_hard_limit: default_execution_queue_latency_hard_limit(),
1302            max_load_shedding_percentage: default_max_load_shedding_percentage(),
1303            min_load_shedding_percentage_above_hard_limit:
1304                default_min_load_shedding_percentage_above_hard_limit(),
1305            safe_transaction_ready_rate: default_safe_transaction_ready_rate(),
1306            check_system_overload_at_signing: true,
1307            check_system_overload_at_execution: false,
1308            max_transaction_manager_queue_length: default_max_transaction_manager_queue_length(),
1309            max_transaction_manager_queue_length_soft_limit_pct:
1310                default_max_transaction_manager_queue_length_soft_limit_pct(),
1311            max_transaction_manager_per_object_queue_length:
1312                default_max_transaction_manager_per_object_queue_length(),
1313        }
1314    }
1315}
1316
1317fn default_authority_overload_config() -> AuthorityOverloadConfig {
1318    AuthorityOverloadConfig::default()
1319}
1320
1321fn default_traffic_controller_policy_config() -> Option<PolicyConfig> {
1322    Some(PolicyConfig::default_dos_protection_policy())
1323}
1324
1325#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1326pub struct Genesis {
1327    #[serde(flatten)]
1328    location: Option<GenesisLocation>,
1329
1330    #[serde(skip)]
1331    genesis: once_cell::sync::OnceCell<genesis::Genesis>,
1332}
1333
1334impl Genesis {
1335    pub fn new(genesis: genesis::Genesis) -> Self {
1336        Self {
1337            location: Some(GenesisLocation::InPlace {
1338                genesis: Box::new(genesis),
1339            }),
1340            genesis: Default::default(),
1341        }
1342    }
1343
1344    pub fn new_from_file<P: Into<PathBuf>>(path: P) -> Self {
1345        Self {
1346            location: Some(GenesisLocation::File {
1347                genesis_file_location: path.into(),
1348            }),
1349            genesis: Default::default(),
1350        }
1351    }
1352
1353    pub fn new_empty() -> Self {
1354        Self {
1355            location: None,
1356            genesis: Default::default(),
1357        }
1358    }
1359
1360    pub fn genesis(&self) -> Result<&genesis::Genesis> {
1361        match &self.location {
1362            Some(GenesisLocation::InPlace { genesis }) => Ok(genesis),
1363            Some(GenesisLocation::File {
1364                genesis_file_location,
1365            }) => self
1366                .genesis
1367                .get_or_try_init(|| genesis::Genesis::load(genesis_file_location)),
1368            None => anyhow::bail!("no genesis location set"),
1369        }
1370    }
1371}
1372
1373#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1374#[serde(untagged)]
1375enum GenesisLocation {
1376    InPlace {
1377        genesis: Box<genesis::Genesis>,
1378    },
1379    File {
1380        #[serde(rename = "genesis-file-location")]
1381        genesis_file_location: PathBuf,
1382    },
1383}
1384
1385/// Wrapper struct for SimpleKeypair that can be deserialized from a file path.
1386/// Used by network, worker, and account keypair.
1387#[derive(Clone, Debug, Deserialize, Serialize)]
1388pub struct KeyPairWithPath {
1389    #[serde(flatten)]
1390    location: KeyPairLocation,
1391
1392    #[serde(skip)]
1393    keypair: OnceCell<Arc<SimpleKeypair>>,
1394
1395    // The consensus/network stacks borrow their key as `&Ed25519KeyPair`
1396    // (fastcrypto), while the key itself is stored as an SDK `SimpleKeypair`
1397    // above. Converting on each access would return an owned value, which
1398    // can't back the `&`-returning accessors, so the converted key is cached
1399    // here. Never populated for account keys.
1400    #[serde(skip)]
1401    ed25519_keypair: OnceCell<Arc<Ed25519KeyPair>>,
1402}
1403
1404impl PartialEq for KeyPairWithPath {
1405    fn eq(&self, other: &Self) -> bool {
1406        self.location == other.location
1407    }
1408}
1409
1410impl Eq for KeyPairWithPath {}
1411
1412#[derive(Debug, Clone, Deserialize, Serialize)]
1413#[serde(untagged)]
1414enum KeyPairLocation {
1415    InPlace {
1416        #[serde(with = "bech32_formatted_keypair")]
1417        value: Arc<SimpleKeypair>,
1418    },
1419    File {
1420        path: PathBuf,
1421    },
1422}
1423
1424impl PartialEq for KeyPairLocation {
1425    fn eq(&self, other: &Self) -> bool {
1426        match (self, other) {
1427            (Self::InPlace { value: a }, Self::InPlace { value: b }) => {
1428                a.to_bytes() == b.to_bytes()
1429            }
1430            (Self::File { path: a }, Self::File { path: b }) => a == b,
1431            _ => false,
1432        }
1433    }
1434}
1435
1436impl Eq for KeyPairLocation {}
1437
1438impl KeyPairWithPath {
1439    pub fn new(kp: SimpleKeypair) -> Self {
1440        let cell: OnceCell<Arc<SimpleKeypair>> = OnceCell::new();
1441        let arc_kp = Arc::new(kp);
1442        // OK to unwrap panic because authority should not start without all keypairs
1443        // loaded.
1444        cell.set(arc_kp.clone()).expect("failed to set keypair");
1445        Self {
1446            location: KeyPairLocation::InPlace { value: arc_kp },
1447            keypair: cell,
1448            ed25519_keypair: OnceCell::new(),
1449        }
1450    }
1451
1452    pub fn new_from_path(path: PathBuf) -> Self {
1453        let cell: OnceCell<Arc<SimpleKeypair>> = OnceCell::new();
1454        // OK to unwrap panic because authority should not start without all keypairs
1455        // loaded.
1456        cell.set(Arc::new(read_keypair_from_file(&path).unwrap_or_else(
1457            |e| panic!("invalid keypair file at path {path:?}: {e}"),
1458        )))
1459        .expect("failed to set keypair");
1460        Self {
1461            location: KeyPairLocation::File { path },
1462            keypair: cell,
1463            ed25519_keypair: OnceCell::new(),
1464        }
1465    }
1466
1467    pub fn keypair(&self) -> &SimpleKeypair {
1468        self.keypair
1469            .get_or_init(|| match &self.location {
1470                KeyPairLocation::InPlace { value } => value.clone(),
1471                KeyPairLocation::File { path } => {
1472                    // OK to unwrap panic because authority should not start without all keypairs
1473                    // loaded.
1474                    Arc::new(
1475                        read_keypair_from_file(path).unwrap_or_else(|e| {
1476                            panic!("invalid keypair file at path {path:?}: {e}")
1477                        }),
1478                    )
1479                }
1480            })
1481            .as_ref()
1482    }
1483
1484    /// The keypair as a fastcrypto ed25519 keypair, for the network stacks
1485    /// that consume that type directly. Panics if the stored keypair is not
1486    /// ed25519.
1487    pub fn ed25519_keypair(&self) -> &Ed25519KeyPair {
1488        self.ed25519_keypair
1489            .get_or_init(|| {
1490                Arc::new(
1491                    simple_to_network_keypair(self.keypair())
1492                        .expect("only Ed25519 network keys are allowed"),
1493                )
1494            })
1495            .as_ref()
1496    }
1497}
1498
1499/// Wrapper struct for AuthorityKeyPair that can be deserialized from a file
1500/// path.
1501#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
1502pub struct AuthorityKeyPairWithPath {
1503    #[serde(flatten)]
1504    location: AuthorityKeyPairLocation,
1505
1506    #[serde(skip)]
1507    keypair: OnceCell<Arc<AuthorityKeyPair>>,
1508}
1509
1510#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1511#[serde(untagged)]
1512enum AuthorityKeyPairLocation {
1513    InPlace { value: Arc<AuthorityKeyPair> },
1514    File { path: PathBuf },
1515}
1516
1517impl AuthorityKeyPairWithPath {
1518    pub fn new(kp: AuthorityKeyPair) -> Self {
1519        let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1520        let arc_kp = Arc::new(kp);
1521        // OK to unwrap panic because authority should not start without all keypairs
1522        // loaded.
1523        cell.set(arc_kp.clone())
1524            .expect("failed to set authority keypair");
1525        Self {
1526            location: AuthorityKeyPairLocation::InPlace { value: arc_kp },
1527            keypair: cell,
1528        }
1529    }
1530
1531    pub fn new_from_path(path: PathBuf) -> Self {
1532        let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1533        // OK to unwrap panic because authority should not start without all keypairs
1534        // loaded.
1535        cell.set(Arc::new(
1536            read_authority_keypair_from_file(&path)
1537                .unwrap_or_else(|_| panic!("invalid authority keypair file at path {path:?}")),
1538        ))
1539        .expect("failed to set authority keypair");
1540        Self {
1541            location: AuthorityKeyPairLocation::File { path },
1542            keypair: cell,
1543        }
1544    }
1545
1546    pub fn authority_keypair(&self) -> &AuthorityKeyPair {
1547        self.keypair
1548            .get_or_init(|| match &self.location {
1549                AuthorityKeyPairLocation::InPlace { value } => value.clone(),
1550                AuthorityKeyPairLocation::File { path } => {
1551                    // OK to unwrap panic because authority should not start without all keypairs
1552                    // loaded.
1553                    Arc::new(
1554                        read_authority_keypair_from_file(path)
1555                            .unwrap_or_else(|_| panic!("invalid authority keypair file {path:?}")),
1556                    )
1557                }
1558            })
1559            .as_ref()
1560    }
1561}
1562
1563/// Configurations which determine how we dump state debug info.
1564/// Debug info is dumped when a node forks.
1565#[derive(Clone, Debug, Deserialize, Serialize, Default)]
1566#[serde(rename_all = "kebab-case")]
1567pub struct StateDebugDumpConfig {
1568    #[serde(skip_serializing_if = "Option::is_none")]
1569    pub dump_file_directory: Option<PathBuf>,
1570}
1571
1572#[cfg(test)]
1573mod tests {
1574    use std::path::PathBuf;
1575
1576    use fastcrypto::traits::KeyPair;
1577    use iota_keys::keypair_file::{write_authority_keypair_to_file, write_keypair_to_file};
1578    use iota_types::crypto::{
1579        AuthorityKeyPair, NetworkKeyPair, get_key_pair_from_rng, network_to_simple_keypair,
1580    };
1581    use rand::{SeedableRng, rngs::StdRng};
1582
1583    use super::Genesis;
1584    use crate::NodeConfig;
1585
1586    #[test]
1587    fn serialize_genesis_from_file() {
1588        let g = Genesis::new_from_file("path/to/file");
1589
1590        let s = serde_yaml::to_string(&g).unwrap();
1591        assert_eq!("---\ngenesis-file-location: path/to/file\n", s);
1592        let loaded_genesis: Genesis = serde_yaml::from_str(&s).unwrap();
1593        assert_eq!(g, loaded_genesis);
1594    }
1595
1596    #[test]
1597    fn fullnode_template() {
1598        const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1599
1600        let _template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1601    }
1602
1603    #[test]
1604    fn enable_soft_locking_defaults_to_enabled() {
1605        // The template omits `enable-soft-locking`, so this exercises the serde
1606        // default and pins the documented "default: enabled" contract.
1607        const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1608
1609        let config: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1610        assert!(config.enable_soft_locking);
1611    }
1612
1613    #[test]
1614    fn load_key_pairs_to_node_config() {
1615        let authority_key_pair: AuthorityKeyPair =
1616            get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1617        let protocol_key_pair: NetworkKeyPair =
1618            get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1619        let network_key_pair: NetworkKeyPair =
1620            get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1621
1622        write_authority_keypair_to_file(&authority_key_pair, PathBuf::from("authority.key"))
1623            .unwrap();
1624        write_keypair_to_file(
1625            &network_to_simple_keypair(&protocol_key_pair),
1626            PathBuf::from("protocol.key"),
1627        )
1628        .unwrap();
1629        write_keypair_to_file(
1630            &network_to_simple_keypair(&network_key_pair),
1631            PathBuf::from("network.key"),
1632        )
1633        .unwrap();
1634
1635        const TEMPLATE: &str = include_str!("../data/fullnode-template-with-path.yaml");
1636        let template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1637        assert_eq!(
1638            template.authority_key_pair().public(),
1639            authority_key_pair.public()
1640        );
1641        assert_eq!(
1642            template.network_key_pair().public(),
1643            network_key_pair.public()
1644        );
1645        assert_eq!(
1646            template.protocol_key_pair().public(),
1647            protocol_key_pair.public()
1648        );
1649    }
1650}
1651
1652// RunWithRange is used to specify the ending epoch/checkpoint to process.
1653// this is intended for use with disaster recovery debugging and verification
1654// workflows, never in normal operations
1655#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
1656pub enum RunWithRange {
1657    Epoch(EpochId),
1658    Checkpoint(CheckpointSequenceNumber),
1659}
1660
1661impl RunWithRange {
1662    // is epoch_id > RunWithRange::Epoch
1663    pub fn is_epoch_gt(&self, epoch_id: EpochId) -> bool {
1664        matches!(self, RunWithRange::Epoch(e) if epoch_id > *e)
1665    }
1666
1667    pub fn matches_checkpoint(&self, seq_num: CheckpointSequenceNumber) -> bool {
1668        matches!(self, RunWithRange::Checkpoint(seq) if *seq == seq_num)
1669    }
1670
1671    pub fn into_checkpoint_bound(self) -> Option<CheckpointSequenceNumber> {
1672        match self {
1673            RunWithRange::Epoch(_) => None,
1674            RunWithRange::Checkpoint(seq) => Some(seq),
1675        }
1676    }
1677}
1678
1679/// A serde helper module used with #[serde(with = "...")] to change the
1680/// de/serialization format of an `SimpleKeypair` to Bech32 when written to or
1681/// read from a node config.
1682mod bech32_formatted_keypair {
1683    use std::ops::Deref;
1684
1685    use fastcrypto::encoding::{Base64, Encoding};
1686    use iota_sdk_crypto::{ToFromBech32, simple::SimpleKeypair};
1687    use serde::{Deserialize, Deserializer, Serializer};
1688
1689    pub fn serialize<S, T>(kp: &T, serializer: S) -> Result<S::Ok, S::Error>
1690    where
1691        S: Serializer,
1692        T: Deref<Target = SimpleKeypair>,
1693    {
1694        use serde::ser::Error;
1695
1696        // Serialize the keypair to a Bech32 string
1697        let s = kp.to_bech32().map_err(Error::custom)?;
1698
1699        serializer.serialize_str(&s)
1700    }
1701
1702    pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
1703    where
1704        D: Deserializer<'de>,
1705        T: From<SimpleKeypair>,
1706    {
1707        use serde::de::Error;
1708
1709        let s = String::deserialize(deserializer)?;
1710
1711        // Try to deserialize the keypair from a Bech32 formatted string
1712        SimpleKeypair::from_bech32(&s)
1713            .map_err(Error::custom)
1714            .or_else(|_: D::Error| {
1715                // For backwards compatibility try Base64 if Bech32 failed
1716                let bytes = Base64::decode(&s).map_err(Error::custom)?;
1717                SimpleKeypair::from_bytes(&bytes).map_err(Error::custom)
1718            })
1719            .map(Into::into)
1720    }
1721}