Skip to main content

iota_config/
node.rs

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