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