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