Skip to main content

iota_config/
node.rs

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