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