Skip to main content

iota_config/
node.rs

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