sui_config/
node.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3use crate::Config;
4use crate::certificate_deny_config::CertificateDenyConfig;
5use crate::genesis;
6use crate::object_storage_config::ObjectStoreConfig;
7use crate::p2p::P2pConfig;
8use crate::transaction_deny_config::TransactionDenyConfig;
9use crate::validator_client_monitor_config::ValidatorClientMonitorConfig;
10use crate::verifier_signing_config::VerifierSigningConfig;
11use anyhow::Result;
12use consensus_config::Parameters as ConsensusParameters;
13use mysten_common::fatal;
14use nonzero_ext::nonzero;
15use once_cell::sync::OnceCell;
16use rand::rngs::OsRng;
17use serde::{Deserialize, Serialize};
18use serde_with::serde_as;
19use std::collections::{BTreeMap, BTreeSet};
20use std::net::SocketAddr;
21use std::num::{NonZeroU32, NonZeroUsize};
22use std::path::{Path, PathBuf};
23use std::sync::Arc;
24use std::time::Duration;
25use sui_keys::keypair_file::{read_authority_keypair_from_file, read_keypair_from_file};
26use sui_types::base_types::{ObjectID, SuiAddress};
27use sui_types::committee::EpochId;
28use sui_types::crypto::AuthorityPublicKeyBytes;
29use sui_types::crypto::KeypairTraits;
30use sui_types::crypto::NetworkKeyPair;
31use sui_types::crypto::SuiKeyPair;
32use sui_types::messages_checkpoint::CheckpointSequenceNumber;
33use sui_types::supported_protocol_versions::{Chain, SupportedProtocolVersions};
34use sui_types::traffic_control::{PolicyConfig, RemoteFirewallConfig};
35
36use sui_types::crypto::{AccountKeyPair, AuthorityKeyPair, get_key_pair_from_rng};
37use sui_types::multiaddr::Multiaddr;
38use tracing::info;
39
40// Default max number of concurrent requests served
41pub const DEFAULT_GRPC_CONCURRENCY_LIMIT: usize = 20000000000;
42
43/// Default gas price of 100 Mist
44pub const DEFAULT_VALIDATOR_GAS_PRICE: u64 = sui_types::transaction::DEFAULT_VALIDATOR_GAS_PRICE;
45
46/// Default commission rate of 2%
47pub const DEFAULT_COMMISSION_RATE: u64 = 200;
48
49/// The type of funds withdraw scheduler to use.
50#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
51pub enum FundsWithdrawSchedulerType {
52    Naive,
53    #[default]
54    Eager,
55}
56
57#[serde_as]
58#[derive(Clone, Debug, Deserialize, Serialize)]
59#[serde(rename_all = "kebab-case")]
60pub struct NodeConfig {
61    #[serde(default = "default_authority_key_pair")]
62    pub protocol_key_pair: AuthorityKeyPairWithPath,
63    #[serde(default = "default_key_pair")]
64    pub worker_key_pair: KeyPairWithPath,
65    #[serde(default = "default_key_pair")]
66    pub account_key_pair: KeyPairWithPath,
67    #[serde(default = "default_key_pair")]
68    pub network_key_pair: KeyPairWithPath,
69
70    pub db_path: PathBuf,
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    #[serde(skip_serializing_if = "Option::is_none")]
77    pub rpc: Option<crate::RpcConfig>,
78
79    #[serde(default = "default_metrics_address")]
80    pub metrics_address: SocketAddr,
81    #[serde(default = "default_admin_interface_port")]
82    pub admin_interface_port: u16,
83
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub consensus_config: Option<ConsensusConfig>,
86
87    #[serde(default = "default_enable_index_processing")]
88    pub enable_index_processing: bool,
89
90    /// When true, post-processing (JSON-RPC indexing and event emission) runs
91    /// synchronously on the execution path instead of being spawned to a
92    /// background thread. This is the legacy behavior and can be used as a
93    /// rollback mechanism or for testing.
94    #[serde(default)]
95    pub sync_post_process_one_tx: bool,
96
97    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
98    pub remove_deprecated_tables: bool,
99
100    #[serde(default)]
101    /// Determines the jsonrpc server type as either:
102    /// - 'websocket' for a websocket based service (deprecated)
103    /// - 'http' for an http based service
104    /// - 'both' for both a websocket and http based service (deprecated)
105    pub jsonrpc_server_type: Option<ServerType>,
106
107    #[serde(default)]
108    pub grpc_load_shed: Option<bool>,
109
110    #[serde(default = "default_concurrency_limit")]
111    pub grpc_concurrency_limit: Option<usize>,
112
113    #[serde(default)]
114    pub p2p_config: P2pConfig,
115
116    pub genesis: Genesis,
117
118    #[serde(default = "default_authority_store_pruning_config")]
119    pub authority_store_pruning_config: AuthorityStorePruningConfig,
120
121    /// Size of the broadcast channel used for notifying other systems of end of epoch.
122    ///
123    /// If unspecified, this will default to `128`.
124    #[serde(default = "default_end_of_epoch_broadcast_channel_capacity")]
125    pub end_of_epoch_broadcast_channel_capacity: usize,
126
127    #[serde(default)]
128    pub checkpoint_executor_config: CheckpointExecutorConfig,
129
130    #[serde(skip_serializing_if = "Option::is_none")]
131    pub metrics: Option<MetricsConfig>,
132
133    /// In a `sui-node` binary, this is set to SupportedProtocolVersions::SYSTEM_DEFAULT
134    /// in sui-node/src/main.rs. It is present in the config so that it can be changed by tests in
135    /// order to test protocol upgrades.
136    #[serde(skip)]
137    pub supported_protocol_versions: Option<SupportedProtocolVersions>,
138
139    #[serde(default)]
140    pub db_checkpoint_config: DBCheckpointConfig,
141
142    #[serde(default)]
143    pub expensive_safety_check_config: ExpensiveSafetyCheckConfig,
144
145    #[serde(skip_serializing_if = "Option::is_none")]
146    pub name_service_package_address: Option<SuiAddress>,
147
148    #[serde(skip_serializing_if = "Option::is_none")]
149    pub name_service_registry_id: Option<ObjectID>,
150
151    #[serde(skip_serializing_if = "Option::is_none")]
152    pub name_service_reverse_registry_id: Option<ObjectID>,
153
154    #[serde(default)]
155    pub transaction_deny_config: TransactionDenyConfig,
156
157    /// Whether dev-inspect transaction execution is disabled on this node.
158    #[serde(default)]
159    pub dev_inspect_disabled: bool,
160
161    #[serde(default)]
162    pub certificate_deny_config: CertificateDenyConfig,
163
164    #[serde(default)]
165    pub state_debug_dump_config: StateDebugDumpConfig,
166
167    #[serde(default)]
168    pub state_archive_read_config: Vec<StateArchiveConfig>,
169
170    #[serde(default)]
171    pub state_snapshot_write_config: StateSnapshotConfig,
172
173    #[serde(default)]
174    pub indexer_max_subscriptions: Option<usize>,
175
176    #[serde(default = "default_transaction_kv_store_config")]
177    pub transaction_kv_store_read_config: TransactionKeyValueStoreReadConfig,
178
179    #[serde(skip_serializing_if = "Option::is_none")]
180    pub transaction_kv_store_write_config: Option<TransactionKeyValueStoreWriteConfig>,
181
182    #[serde(default = "default_jwk_fetch_interval_seconds")]
183    pub jwk_fetch_interval_seconds: u64,
184
185    #[serde(default = "default_zklogin_oauth_providers")]
186    pub zklogin_oauth_providers: BTreeMap<Chain, BTreeSet<String>>,
187
188    #[serde(default = "default_authority_overload_config")]
189    pub authority_overload_config: AuthorityOverloadConfig,
190
191    #[serde(skip_serializing_if = "Option::is_none")]
192    pub run_with_range: Option<RunWithRange>,
193
194    // For killswitch use None
195    #[serde(
196        skip_serializing_if = "Option::is_none",
197        default = "default_traffic_controller_policy_config"
198    )]
199    pub policy_config: Option<PolicyConfig>,
200
201    #[serde(skip_serializing_if = "Option::is_none")]
202    pub firewall_config: Option<RemoteFirewallConfig>,
203
204    #[serde(default)]
205    pub execution_cache: ExecutionCacheConfig,
206
207    // step 1 in removing the old state accumulator
208    #[serde(skip)]
209    #[serde(default = "bool_true")]
210    pub state_accumulator_v2: bool,
211
212    /// The type of funds withdraw scheduler to use.
213    /// Default is Eager. Not exposed to file configuration.
214    #[serde(skip)]
215    #[serde(default)]
216    pub funds_withdraw_scheduler_type: FundsWithdrawSchedulerType,
217
218    #[serde(default = "bool_true")]
219    pub enable_soft_bundle: bool,
220
221    #[serde(default)]
222    pub verifier_signing_config: VerifierSigningConfig,
223
224    /// If a value is set, it determines if writes to DB can stall, which can halt the whole process.
225    /// By default, write stall is enabled on validators but not on fullnodes.
226    #[serde(skip_serializing_if = "Option::is_none")]
227    pub enable_db_write_stall: Option<bool>,
228
229    /// If set, determines whether database writes are synced to disk (fsync).
230    /// Provides stronger durability at the cost of write performance.
231    /// Falls back to SUI_DB_SYNC_TO_DISK env var if not set. Default: disabled.
232    #[serde(skip_serializing_if = "Option::is_none")]
233    pub enable_db_sync_to_disk: Option<bool>,
234
235    #[serde(skip_serializing_if = "Option::is_none")]
236    pub execution_time_observer_config: Option<ExecutionTimeObserverConfig>,
237
238    /// Allow overriding the chain for testing purposes. For instance, it allows you to
239    /// create a test network that believes it is mainnet or testnet. Attempting to
240    /// override this value on production networks will result in an error.
241    #[serde(skip_serializing_if = "Option::is_none")]
242    pub chain_override_for_testing: Option<Chain>,
243
244    /// Configuration for validator client monitoring from the client perspective.
245    /// When enabled, tracks client-observed performance metrics for validators.
246    #[serde(skip_serializing_if = "Option::is_none")]
247    pub validator_client_monitor_config: Option<ValidatorClientMonitorConfig>,
248
249    /// Fork recovery configuration for handling validator equivocation after forks
250    #[serde(skip_serializing_if = "Option::is_none")]
251    pub fork_recovery: Option<ForkRecoveryConfig>,
252
253    /// Configuration for the transaction driver.
254    #[serde(skip_serializing_if = "Option::is_none")]
255    pub transaction_driver_config: Option<TransactionDriverConfig>,
256
257    /// Configuration for congestion tracker binary logging.
258    /// When set, enables per-commit binary logs of congestion tracker state.
259    #[serde(skip_serializing_if = "Option::is_none")]
260    pub congestion_log: Option<CongestionLogConfig>,
261}
262
263#[derive(Clone, Debug, Deserialize, Serialize)]
264#[serde(rename_all = "kebab-case")]
265pub struct TransactionDriverConfig {
266    /// The list of validators that are allowed to submit MFP transactions to (via the transaction driver).
267    /// Each entry is a validator display name.
268    #[serde(default, skip_serializing_if = "Vec::is_empty")]
269    pub allowed_submission_validators: Vec<String>,
270
271    /// The list of validators that are blocked from submitting block transactions to (via the transaction driver).
272    /// Each entry is a validator display name.
273    #[serde(default, skip_serializing_if = "Vec::is_empty")]
274    pub blocked_submission_validators: Vec<String>,
275
276    /// Enable early transaction validation before submission to consensus.
277    /// This checks for non-retriable errors (like old object versions) and rejects
278    /// transactions early to provide fast feedback to clients.
279    /// Note: Currently used in TransactionOrchestrator, but may be moved to TransactionDriver in future.
280    #[serde(default = "bool_true")]
281    pub enable_early_validation: bool,
282}
283
284impl Default for TransactionDriverConfig {
285    fn default() -> Self {
286        Self {
287            allowed_submission_validators: vec![],
288            blocked_submission_validators: vec![],
289            enable_early_validation: true,
290        }
291    }
292}
293
294#[derive(Clone, Debug, Deserialize, Serialize)]
295#[serde(rename_all = "kebab-case")]
296pub struct CongestionLogConfig {
297    pub path: PathBuf,
298    #[serde(default = "default_congestion_log_max_file_size")]
299    pub max_file_size: u64,
300    #[serde(default = "default_congestion_log_max_files")]
301    pub max_files: u32,
302}
303
304fn default_congestion_log_max_file_size() -> u64 {
305    100 * 1024 * 1024 // 100MB
306}
307
308fn default_congestion_log_max_files() -> u32 {
309    10
310}
311
312#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
313#[serde(rename_all = "kebab-case")]
314pub enum ForkCrashBehavior {
315    #[serde(rename = "await-fork-recovery")]
316    #[default]
317    AwaitForkRecovery,
318    /// Return an error instead of blocking forever. This is primarily for testing.
319    #[serde(rename = "return-error")]
320    ReturnError,
321}
322
323#[derive(Clone, Debug, Default, Deserialize, Serialize)]
324#[serde(rename_all = "kebab-case")]
325pub struct ForkRecoveryConfig {
326    /// Map of transaction digest to effects digest overrides
327    /// Used to repoint transactions to correct effects after a fork
328    #[serde(default)]
329    pub transaction_overrides: BTreeMap<String, String>,
330
331    /// Map of checkpoint sequence number to checkpoint digest overrides
332    /// On node start, if we have a locally computed checkpoint with a
333    /// digest mismatch with this table, we will clear any associated local state.
334    #[serde(default)]
335    pub checkpoint_overrides: BTreeMap<u64, String>,
336
337    /// Behavior when a fork is detected after recovery attempts
338    #[serde(default)]
339    pub fork_crash_behavior: ForkCrashBehavior,
340}
341
342#[derive(Clone, Debug, Default, Deserialize, Serialize)]
343#[serde(rename_all = "kebab-case")]
344pub struct ExecutionTimeObserverConfig {
345    /// Size of the channel used for buffering local execution time observations.
346    ///
347    /// If unspecified, this will default to `1_024`.
348    pub observation_channel_capacity: Option<NonZeroUsize>,
349
350    /// Size of the LRU cache used for storing local execution time observations.
351    ///
352    /// If unspecified, this will default to `10_000`.
353    pub observation_cache_size: Option<NonZeroUsize>,
354
355    /// Size of the channel used for buffering object debt updates from consensus handler.
356    ///
357    /// If unspecified, this will default to `128`.
358    pub object_debt_channel_capacity: Option<NonZeroUsize>,
359
360    /// Size of the LRU cache used for tracking object utilization.
361    ///
362    /// If unspecified, this will default to `50_000`.
363    pub object_utilization_cache_size: Option<NonZeroUsize>,
364
365    /// If true, the execution time observer will report per-object utilization metrics
366    /// with full object IDs. When set, the metric can have a high cardinality, so this
367    /// should not be used except in controlled tests where there are a small number of
368    /// objects.
369    ///
370    /// If false, object utilization is reported using hash(object_id) % 32 as the key,
371    /// which still allows observation of utilization when there are small numbers of
372    /// over-utilized objects.
373    ///
374    /// If unspecified, this will default to `false`.
375    pub report_object_utilization_metric_with_full_id: Option<bool>,
376
377    /// Unless target object utilization is exceeded by at least this amount, no observation
378    /// will be shared with consensus.
379    ///
380    /// If unspecified, this will default to `500` milliseconds.
381    pub observation_sharing_object_utilization_threshold: Option<Duration>,
382
383    /// Unless the current local observation differs from the last one we shared by at least this
384    /// percentage, no observation will be shared with consensus.
385    ///
386    /// If unspecified, this will default to `0.1`.
387    pub observation_sharing_diff_threshold: Option<f64>,
388
389    /// Minimum interval between sharing multiple observations of the same key.
390    ///
391    /// If unspecified, this will default to `5` seconds.
392    pub observation_sharing_min_interval: Option<Duration>,
393
394    /// Global per-second rate limit for sharing observations. This is a safety valve and
395    /// should not trigger during normal operation.
396    ///
397    /// If unspecified, this will default to `10` observations per second.
398    pub observation_sharing_rate_limit: Option<NonZeroU32>,
399
400    /// Global burst limit for sharing observations.
401    ///
402    /// If unspecified, this will default to `100` observations.
403    pub observation_sharing_burst_limit: Option<NonZeroU32>,
404
405    /// Whether to use gas price weighting in execution time estimates.
406    /// When enabled, samples with higher gas prices have more influence on the
407    /// execution time estimates, providing protection against volume-based
408    /// manipulation attacks.
409    ///
410    /// If unspecified, this will default to `false`.
411    pub enable_gas_price_weighting: Option<bool>,
412
413    /// Size of the weighted moving average window for execution time observations.
414    /// This determines how many recent observations are kept in the weighted moving average
415    /// calculation for each execution time observation key.
416    /// Note that this is independent of the window size for the simple moving average.
417    ///
418    /// If unspecified, this will default to `20`.
419    pub weighted_moving_average_window_size: Option<usize>,
420
421    /// Whether to inject synthetic execution time for testing in simtest.
422    /// When enabled, synthetic timings will be generated for execution time observations
423    /// to enable deterministic testing of congestion control features.
424    ///
425    /// If unspecified, this will default to `false`.
426    #[cfg(msim)]
427    pub inject_synthetic_execution_time: Option<bool>,
428}
429
430impl ExecutionTimeObserverConfig {
431    pub fn observation_channel_capacity(&self) -> NonZeroUsize {
432        self.observation_channel_capacity
433            .unwrap_or(nonzero!(1_024usize))
434    }
435
436    pub fn observation_cache_size(&self) -> NonZeroUsize {
437        self.observation_cache_size.unwrap_or(nonzero!(10_000usize))
438    }
439
440    pub fn object_debt_channel_capacity(&self) -> NonZeroUsize {
441        self.object_debt_channel_capacity
442            .unwrap_or(nonzero!(128usize))
443    }
444
445    pub fn object_utilization_cache_size(&self) -> NonZeroUsize {
446        self.object_utilization_cache_size
447            .unwrap_or(nonzero!(50_000usize))
448    }
449
450    pub fn report_object_utilization_metric_with_full_id(&self) -> bool {
451        self.report_object_utilization_metric_with_full_id
452            .unwrap_or(false)
453    }
454
455    pub fn observation_sharing_object_utilization_threshold(&self) -> Duration {
456        self.observation_sharing_object_utilization_threshold
457            .unwrap_or(Duration::from_millis(500))
458    }
459
460    pub fn observation_sharing_diff_threshold(&self) -> f64 {
461        self.observation_sharing_diff_threshold.unwrap_or(0.1)
462    }
463
464    pub fn observation_sharing_min_interval(&self) -> Duration {
465        self.observation_sharing_min_interval
466            .unwrap_or(Duration::from_secs(5))
467    }
468
469    pub fn observation_sharing_rate_limit(&self) -> NonZeroU32 {
470        self.observation_sharing_rate_limit
471            .unwrap_or(nonzero!(10u32))
472    }
473
474    pub fn observation_sharing_burst_limit(&self) -> NonZeroU32 {
475        self.observation_sharing_burst_limit
476            .unwrap_or(nonzero!(100u32))
477    }
478
479    pub fn enable_gas_price_weighting(&self) -> bool {
480        self.enable_gas_price_weighting.unwrap_or(false)
481    }
482
483    pub fn weighted_moving_average_window_size(&self) -> usize {
484        self.weighted_moving_average_window_size.unwrap_or(20)
485    }
486
487    #[cfg(msim)]
488    pub fn inject_synthetic_execution_time(&self) -> bool {
489        self.inject_synthetic_execution_time.unwrap_or(false)
490    }
491}
492
493#[allow(clippy::large_enum_variant)]
494#[derive(Clone, Debug, Deserialize, Serialize)]
495#[serde(rename_all = "kebab-case")]
496pub enum ExecutionCacheConfig {
497    PassthroughCache,
498    WritebackCache {
499        /// Maximum number of entries in each cache. (There are several different caches).
500        /// If None, the default of 10000 is used.
501        max_cache_size: Option<u64>,
502
503        package_cache_size: Option<u64>, // defaults to 1000
504
505        object_cache_size: Option<u64>, // defaults to max_cache_size
506        marker_cache_size: Option<u64>, // defaults to object_cache_size
507        object_by_id_cache_size: Option<u64>, // defaults to object_cache_size
508
509        transaction_cache_size: Option<u64>, // defaults to max_cache_size
510        executed_effect_cache_size: Option<u64>, // defaults to transaction_cache_size
511        effect_cache_size: Option<u64>,      // defaults to executed_effect_cache_size
512
513        events_cache_size: Option<u64>, // defaults to transaction_cache_size
514
515        transaction_objects_cache_size: Option<u64>, // defaults to 1000
516
517        /// Number of uncommitted transactions at which to pause consensus handler.
518        backpressure_threshold: Option<u64>,
519
520        /// Number of uncommitted transactions at which to refuse new transaction
521        /// submissions. Defaults to backpressure_threshold if unset.
522        backpressure_threshold_for_rpc: Option<u64>,
523    },
524}
525
526impl Default for ExecutionCacheConfig {
527    fn default() -> Self {
528        ExecutionCacheConfig::WritebackCache {
529            max_cache_size: None,
530            backpressure_threshold: None,
531            backpressure_threshold_for_rpc: None,
532            package_cache_size: None,
533            object_cache_size: None,
534            marker_cache_size: None,
535            object_by_id_cache_size: None,
536            transaction_cache_size: None,
537            executed_effect_cache_size: None,
538            effect_cache_size: None,
539            events_cache_size: None,
540            transaction_objects_cache_size: None,
541        }
542    }
543}
544
545impl ExecutionCacheConfig {
546    pub fn max_cache_size(&self) -> u64 {
547        std::env::var("SUI_MAX_CACHE_SIZE")
548            .ok()
549            .and_then(|s| s.parse().ok())
550            .unwrap_or_else(|| match self {
551                ExecutionCacheConfig::PassthroughCache => fatal!("invalid cache config"),
552                ExecutionCacheConfig::WritebackCache { max_cache_size, .. } => {
553                    max_cache_size.unwrap_or(100000)
554                }
555            })
556    }
557
558    pub fn package_cache_size(&self) -> u64 {
559        std::env::var("SUI_PACKAGE_CACHE_SIZE")
560            .ok()
561            .and_then(|s| s.parse().ok())
562            .unwrap_or_else(|| match self {
563                ExecutionCacheConfig::PassthroughCache => fatal!("invalid cache config"),
564                ExecutionCacheConfig::WritebackCache {
565                    package_cache_size, ..
566                } => package_cache_size.unwrap_or(1000),
567            })
568    }
569
570    pub fn object_cache_size(&self) -> u64 {
571        std::env::var("SUI_OBJECT_CACHE_SIZE")
572            .ok()
573            .and_then(|s| s.parse().ok())
574            .unwrap_or_else(|| match self {
575                ExecutionCacheConfig::PassthroughCache => fatal!("invalid cache config"),
576                ExecutionCacheConfig::WritebackCache {
577                    object_cache_size, ..
578                } => object_cache_size.unwrap_or(self.max_cache_size()),
579            })
580    }
581
582    pub fn marker_cache_size(&self) -> u64 {
583        std::env::var("SUI_MARKER_CACHE_SIZE")
584            .ok()
585            .and_then(|s| s.parse().ok())
586            .unwrap_or_else(|| match self {
587                ExecutionCacheConfig::PassthroughCache => fatal!("invalid cache config"),
588                ExecutionCacheConfig::WritebackCache {
589                    marker_cache_size, ..
590                } => marker_cache_size.unwrap_or(self.object_cache_size()),
591            })
592    }
593
594    pub fn object_by_id_cache_size(&self) -> u64 {
595        std::env::var("SUI_OBJECT_BY_ID_CACHE_SIZE")
596            .ok()
597            .and_then(|s| s.parse().ok())
598            .unwrap_or_else(|| match self {
599                ExecutionCacheConfig::PassthroughCache => fatal!("invalid cache config"),
600                ExecutionCacheConfig::WritebackCache {
601                    object_by_id_cache_size,
602                    ..
603                } => object_by_id_cache_size.unwrap_or(self.object_cache_size()),
604            })
605    }
606
607    pub fn transaction_cache_size(&self) -> u64 {
608        std::env::var("SUI_TRANSACTION_CACHE_SIZE")
609            .ok()
610            .and_then(|s| s.parse().ok())
611            .unwrap_or_else(|| match self {
612                ExecutionCacheConfig::PassthroughCache => fatal!("invalid cache config"),
613                ExecutionCacheConfig::WritebackCache {
614                    transaction_cache_size,
615                    ..
616                } => transaction_cache_size.unwrap_or(self.max_cache_size()),
617            })
618    }
619
620    pub fn executed_effect_cache_size(&self) -> u64 {
621        std::env::var("SUI_EXECUTED_EFFECT_CACHE_SIZE")
622            .ok()
623            .and_then(|s| s.parse().ok())
624            .unwrap_or_else(|| match self {
625                ExecutionCacheConfig::PassthroughCache => fatal!("invalid cache config"),
626                ExecutionCacheConfig::WritebackCache {
627                    executed_effect_cache_size,
628                    ..
629                } => executed_effect_cache_size.unwrap_or(self.transaction_cache_size()),
630            })
631    }
632
633    pub fn effect_cache_size(&self) -> u64 {
634        std::env::var("SUI_EFFECT_CACHE_SIZE")
635            .ok()
636            .and_then(|s| s.parse().ok())
637            .unwrap_or_else(|| match self {
638                ExecutionCacheConfig::PassthroughCache => fatal!("invalid cache config"),
639                ExecutionCacheConfig::WritebackCache {
640                    effect_cache_size, ..
641                } => effect_cache_size.unwrap_or(self.executed_effect_cache_size()),
642            })
643    }
644
645    pub fn events_cache_size(&self) -> u64 {
646        std::env::var("SUI_EVENTS_CACHE_SIZE")
647            .ok()
648            .and_then(|s| s.parse().ok())
649            .unwrap_or_else(|| match self {
650                ExecutionCacheConfig::PassthroughCache => fatal!("invalid cache config"),
651                ExecutionCacheConfig::WritebackCache {
652                    events_cache_size, ..
653                } => events_cache_size.unwrap_or(self.transaction_cache_size()),
654            })
655    }
656
657    pub fn transaction_objects_cache_size(&self) -> u64 {
658        std::env::var("SUI_TRANSACTION_OBJECTS_CACHE_SIZE")
659            .ok()
660            .and_then(|s| s.parse().ok())
661            .unwrap_or_else(|| match self {
662                ExecutionCacheConfig::PassthroughCache => fatal!("invalid cache config"),
663                ExecutionCacheConfig::WritebackCache {
664                    transaction_objects_cache_size,
665                    ..
666                } => transaction_objects_cache_size.unwrap_or(1000),
667            })
668    }
669
670    pub fn backpressure_threshold(&self) -> u64 {
671        std::env::var("SUI_BACKPRESSURE_THRESHOLD")
672            .ok()
673            .and_then(|s| s.parse().ok())
674            .unwrap_or_else(|| match self {
675                ExecutionCacheConfig::PassthroughCache => fatal!("invalid cache config"),
676                ExecutionCacheConfig::WritebackCache {
677                    backpressure_threshold,
678                    ..
679                } => backpressure_threshold.unwrap_or(100_000),
680            })
681    }
682
683    pub fn backpressure_threshold_for_rpc(&self) -> u64 {
684        std::env::var("SUI_BACKPRESSURE_THRESHOLD_FOR_RPC")
685            .ok()
686            .and_then(|s| s.parse().ok())
687            .unwrap_or_else(|| match self {
688                ExecutionCacheConfig::PassthroughCache => fatal!("invalid cache config"),
689                ExecutionCacheConfig::WritebackCache {
690                    backpressure_threshold_for_rpc,
691                    ..
692                } => backpressure_threshold_for_rpc.unwrap_or(self.backpressure_threshold()),
693            })
694    }
695}
696
697#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
698#[serde(rename_all = "lowercase")]
699pub enum ServerType {
700    WebSocket,
701    Http,
702    Both,
703}
704
705#[derive(Clone, Debug, Deserialize, Serialize)]
706#[serde(rename_all = "kebab-case")]
707pub struct TransactionKeyValueStoreReadConfig {
708    #[serde(default = "default_base_url")]
709    pub base_url: String,
710
711    #[serde(default = "default_cache_size")]
712    pub cache_size: u64,
713}
714
715impl Default for TransactionKeyValueStoreReadConfig {
716    fn default() -> Self {
717        Self {
718            base_url: default_base_url(),
719            cache_size: default_cache_size(),
720        }
721    }
722}
723
724fn default_base_url() -> String {
725    "https://transactions.sui.io/".to_string()
726}
727
728fn default_cache_size() -> u64 {
729    100_000
730}
731
732fn default_jwk_fetch_interval_seconds() -> u64 {
733    3600
734}
735
736pub fn default_zklogin_oauth_providers() -> BTreeMap<Chain, BTreeSet<String>> {
737    let mut map = BTreeMap::new();
738
739    // providers that are available on devnet only.
740    let experimental_providers = BTreeSet::from([
741        "Google".to_string(),
742        "Facebook".to_string(),
743        "Twitch".to_string(),
744        "Kakao".to_string(),
745        "Apple".to_string(),
746        "Slack".to_string(),
747        "TestIssuer".to_string(),
748        "Microsoft".to_string(),
749        "KarrierOne".to_string(),
750        "Credenza3".to_string(),
751        "Playtron".to_string(),
752        "Threedos".to_string(),
753        "Onefc".to_string(),
754        "FanTV".to_string(),
755        "Arden".to_string(), // Arden partner
756        "AwsTenant-region:eu-west-3-tenant_id:eu-west-3_gGVCx53Es".to_string(), // Trace, external partner
757        "EveFrontier".to_string(),
758        "TestEveFrontier".to_string(),
759        "AwsTenant-region:ap-southeast-1-tenant_id:ap-southeast-1_2QQPyQXDz".to_string(), // Decot, external partner
760        "AwsTenant-region:eu-north-1-tenant_id:eu-north-1_rz7IVMOR5".to_string(), // test Gamma Prime, external partner
761        "AwsTenant-region:eu-north-1-tenant_id:eu-north-1_K3XgRburu".to_string(), // Gamma Prime, external partner
762    ]);
763
764    // providers that are available for mainnet and testnet.
765    let providers = BTreeSet::from([
766        "Google".to_string(),
767        "Facebook".to_string(),
768        "Twitch".to_string(),
769        "Apple".to_string(),
770        "KarrierOne".to_string(),
771        "Credenza3".to_string(),
772        "Playtron".to_string(),
773        "Onefc".to_string(),
774        "Threedos".to_string(),
775        "AwsTenant-region:eu-west-3-tenant_id:eu-west-3_gGVCx53Es".to_string(), // Trace, external partner
776        "Arden".to_string(),
777        "FanTV".to_string(),
778        "EveFrontier".to_string(),
779        "TestEveFrontier".to_string(),
780        "AwsTenant-region:ap-southeast-1-tenant_id:ap-southeast-1_2QQPyQXDz".to_string(), // Decot, external partner
781    ]);
782    map.insert(Chain::Mainnet, providers.clone());
783    map.insert(Chain::Testnet, providers);
784    map.insert(Chain::Unknown, experimental_providers);
785    map
786}
787
788fn default_transaction_kv_store_config() -> TransactionKeyValueStoreReadConfig {
789    TransactionKeyValueStoreReadConfig::default()
790}
791
792fn default_authority_store_pruning_config() -> AuthorityStorePruningConfig {
793    AuthorityStorePruningConfig::default()
794}
795
796pub fn default_enable_index_processing() -> bool {
797    true
798}
799
800fn default_grpc_address() -> Multiaddr {
801    "/ip4/0.0.0.0/tcp/8080".parse().unwrap()
802}
803fn default_authority_key_pair() -> AuthorityKeyPairWithPath {
804    AuthorityKeyPairWithPath::new(get_key_pair_from_rng::<AuthorityKeyPair, _>(&mut OsRng).1)
805}
806
807fn default_key_pair() -> KeyPairWithPath {
808    KeyPairWithPath::new(
809        get_key_pair_from_rng::<AccountKeyPair, _>(&mut OsRng)
810            .1
811            .into(),
812    )
813}
814
815fn default_metrics_address() -> SocketAddr {
816    use std::net::{IpAddr, Ipv4Addr};
817    SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9184)
818}
819
820pub fn default_admin_interface_port() -> u16 {
821    1337
822}
823
824pub fn default_json_rpc_address() -> SocketAddr {
825    use std::net::{IpAddr, Ipv4Addr};
826    SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9000)
827}
828
829pub fn default_concurrency_limit() -> Option<usize> {
830    Some(DEFAULT_GRPC_CONCURRENCY_LIMIT)
831}
832
833pub fn default_end_of_epoch_broadcast_channel_capacity() -> usize {
834    128
835}
836
837pub fn bool_true() -> bool {
838    true
839}
840
841fn is_true(value: &bool) -> bool {
842    *value
843}
844
845impl Config for NodeConfig {}
846
847impl NodeConfig {
848    pub fn protocol_key_pair(&self) -> &AuthorityKeyPair {
849        self.protocol_key_pair.authority_keypair()
850    }
851
852    pub fn worker_key_pair(&self) -> &NetworkKeyPair {
853        match self.worker_key_pair.keypair() {
854            SuiKeyPair::Ed25519(kp) => kp,
855            other => panic!(
856                "Invalid keypair type: {:?}, only Ed25519 is allowed for worker key",
857                other
858            ),
859        }
860    }
861
862    pub fn network_key_pair(&self) -> &NetworkKeyPair {
863        match self.network_key_pair.keypair() {
864            SuiKeyPair::Ed25519(kp) => kp,
865            other => panic!(
866                "Invalid keypair type: {:?}, only Ed25519 is allowed for network key",
867                other
868            ),
869        }
870    }
871
872    pub fn protocol_public_key(&self) -> AuthorityPublicKeyBytes {
873        self.protocol_key_pair().public().into()
874    }
875
876    pub fn db_path(&self) -> PathBuf {
877        self.db_path.join("live")
878    }
879
880    pub fn db_checkpoint_path(&self) -> PathBuf {
881        self.db_path.join("db_checkpoints")
882    }
883
884    pub fn archive_path(&self) -> PathBuf {
885        self.db_path.join("archive")
886    }
887
888    pub fn snapshot_path(&self) -> PathBuf {
889        self.db_path.join("snapshot")
890    }
891
892    pub fn network_address(&self) -> &Multiaddr {
893        &self.network_address
894    }
895
896    pub fn consensus_config(&self) -> Option<&ConsensusConfig> {
897        self.consensus_config.as_ref()
898    }
899
900    pub fn genesis(&self) -> Result<&genesis::Genesis> {
901        self.genesis.genesis()
902    }
903
904    pub fn sui_address(&self) -> SuiAddress {
905        (&self.account_key_pair.keypair().public()).into()
906    }
907
908    pub fn archive_reader_config(&self) -> Option<ArchiveReaderConfig> {
909        self.state_archive_read_config
910            .first()
911            .map(|config| ArchiveReaderConfig {
912                ingestion_url: config.ingestion_url.clone(),
913                remote_store_options: config.remote_store_options.clone(),
914                download_concurrency: NonZeroUsize::new(config.concurrency)
915                    .unwrap_or(NonZeroUsize::new(5).unwrap()),
916                remote_store_config: ObjectStoreConfig::default(),
917            })
918    }
919
920    pub fn jsonrpc_server_type(&self) -> ServerType {
921        self.jsonrpc_server_type.unwrap_or(ServerType::Http)
922    }
923
924    pub fn rpc(&self) -> Option<&crate::RpcConfig> {
925        self.rpc.as_ref()
926    }
927}
928
929#[derive(Debug, Clone, Deserialize, Serialize)]
930pub enum ConsensusProtocol {
931    #[serde(rename = "narwhal")]
932    Narwhal,
933    #[serde(rename = "mysticeti")]
934    Mysticeti,
935}
936
937#[derive(Debug, Clone, Deserialize, Serialize)]
938#[serde(rename_all = "kebab-case")]
939pub struct ConsensusConfig {
940    // Base consensus DB path for all epochs.
941    pub db_path: PathBuf,
942
943    // The number of epochs for which to retain the consensus DBs. Setting it to 0 will make a consensus DB getting
944    // dropped as soon as system is switched to a new epoch.
945    pub db_retention_epochs: Option<u64>,
946
947    // Pruner will run on every epoch change but it will also check periodically on every `db_pruner_period_secs`
948    // seconds to see if there are any epoch DBs to remove.
949    pub db_pruner_period_secs: Option<u64>,
950
951    /// Maximum number of pending transactions to submit to consensus, including those
952    /// in submission wait.
953    /// Default to 20_000 inflight limit, assuming 20_000 txn tps * 1 sec consensus latency.
954    pub max_pending_transactions: Option<usize>,
955
956    /// When defined caps the calculated submission position to the max_submit_position. Even if the
957    /// is elected to submit from a higher position than this, it will "reset" to the max_submit_position.
958    pub max_submit_position: Option<usize>,
959
960    /// The submit delay step to consensus defined in milliseconds. When provided it will
961    /// override the current back off logic otherwise the default backoff logic will be applied based
962    /// on consensus latency estimates.
963    pub submit_delay_step_override_millis: Option<u64>,
964
965    pub parameters: Option<ConsensusParameters>,
966
967    /// Override for the consensus network listen address.
968    /// When set, Mysticeti binds to this address instead of deriving from the committee.
969    /// Address override is advertised via the discovery protocol.
970    #[serde(skip_serializing_if = "Option::is_none")]
971    pub listen_address: Option<Multiaddr>,
972
973    /// External consensus address that should be advertised via the discovery protocol,
974    /// if it is different from `listen_address` above.
975    ///
976    /// When neither this nor `listen_address` is set, peers use the on-chain committee address.
977    #[serde(skip_serializing_if = "Option::is_none")]
978    pub external_address: Option<Multiaddr>,
979}
980
981impl ConsensusConfig {
982    pub fn db_path(&self) -> &Path {
983        &self.db_path
984    }
985
986    pub fn max_pending_transactions(&self) -> usize {
987        self.max_pending_transactions.unwrap_or(20_000)
988    }
989
990    pub fn submit_delay_step_override(&self) -> Option<Duration> {
991        self.submit_delay_step_override_millis
992            .map(Duration::from_millis)
993    }
994
995    pub fn db_retention_epochs(&self) -> u64 {
996        self.db_retention_epochs.unwrap_or(0)
997    }
998
999    pub fn db_pruner_period(&self) -> Duration {
1000        // Default to 1 hour
1001        self.db_pruner_period_secs
1002            .map(Duration::from_secs)
1003            .unwrap_or(Duration::from_secs(3_600))
1004    }
1005}
1006
1007#[derive(Clone, Debug, Deserialize, Serialize)]
1008#[serde(rename_all = "kebab-case")]
1009pub struct CheckpointExecutorConfig {
1010    /// Upper bound on the number of checkpoints that can be concurrently executed
1011    ///
1012    /// If unspecified, this will default to `200`
1013    #[serde(default = "default_checkpoint_execution_max_concurrency")]
1014    pub checkpoint_execution_max_concurrency: usize,
1015
1016    /// Number of seconds to wait for effects of a batch of transactions
1017    /// before logging a warning. Note that we will continue to retry
1018    /// indefinitely
1019    ///
1020    /// If unspecified, this will default to `10`.
1021    #[serde(default = "default_local_execution_timeout_sec")]
1022    pub local_execution_timeout_sec: u64,
1023
1024    /// Optional directory used for data ingestion pipeline
1025    /// When specified, each executed checkpoint will be saved in a local directory for post processing
1026    #[serde(default, skip_serializing_if = "Option::is_none")]
1027    pub data_ingestion_dir: Option<PathBuf>,
1028}
1029
1030#[derive(Clone, Debug, Default, Deserialize, Serialize)]
1031#[serde(rename_all = "kebab-case")]
1032pub struct ExpensiveSafetyCheckConfig {
1033    /// If enabled, at epoch boundary, we will check that the storage
1034    /// fund balance is always identical to the sum of the storage
1035    /// rebate of all live objects, and that the total SUI in the network remains
1036    /// the same.
1037    #[serde(default)]
1038    enable_epoch_sui_conservation_check: bool,
1039
1040    /// If enabled, we will check that the total SUI in all input objects of a tx
1041    /// (both the Move part and the storage rebate) matches the total SUI in all
1042    /// output objects of the tx + gas fees
1043    #[serde(default)]
1044    enable_deep_per_tx_sui_conservation_check: bool,
1045
1046    /// Disable epoch SUI conservation check even when we are running in debug mode.
1047    #[serde(default)]
1048    force_disable_epoch_sui_conservation_check: bool,
1049
1050    /// If enabled, at epoch boundary, we will check that the accumulated
1051    /// live object state matches the end of epoch root state digest.
1052    #[serde(default)]
1053    enable_state_consistency_check: bool,
1054
1055    /// Disable state consistency check even when we are running in debug mode.
1056    #[serde(default)]
1057    force_disable_state_consistency_check: bool,
1058
1059    #[serde(default)]
1060    enable_secondary_index_checks: bool,
1061    // TODO: Add more expensive checks here
1062}
1063
1064impl ExpensiveSafetyCheckConfig {
1065    pub fn new_enable_all() -> Self {
1066        Self {
1067            enable_epoch_sui_conservation_check: true,
1068            enable_deep_per_tx_sui_conservation_check: true,
1069            force_disable_epoch_sui_conservation_check: false,
1070            enable_state_consistency_check: true,
1071            force_disable_state_consistency_check: false,
1072            enable_secondary_index_checks: false, // Disable by default for now
1073        }
1074    }
1075
1076    pub fn new_enable_all_with_secondary_index_checks() -> Self {
1077        Self {
1078            enable_secondary_index_checks: true,
1079            ..Self::new_enable_all()
1080        }
1081    }
1082
1083    pub fn new_disable_all() -> Self {
1084        Self {
1085            enable_epoch_sui_conservation_check: false,
1086            enable_deep_per_tx_sui_conservation_check: false,
1087            force_disable_epoch_sui_conservation_check: true,
1088            enable_state_consistency_check: false,
1089            force_disable_state_consistency_check: true,
1090            enable_secondary_index_checks: false,
1091        }
1092    }
1093
1094    pub fn force_disable_epoch_sui_conservation_check(&mut self) {
1095        self.force_disable_epoch_sui_conservation_check = true;
1096    }
1097
1098    pub fn enable_epoch_sui_conservation_check(&self) -> bool {
1099        (self.enable_epoch_sui_conservation_check || cfg!(debug_assertions))
1100            && !self.force_disable_epoch_sui_conservation_check
1101    }
1102
1103    pub fn force_disable_state_consistency_check(&mut self) {
1104        self.force_disable_state_consistency_check = true;
1105    }
1106
1107    pub fn enable_state_consistency_check(&self) -> bool {
1108        (self.enable_state_consistency_check || cfg!(debug_assertions))
1109            && !self.force_disable_state_consistency_check
1110    }
1111
1112    pub fn enable_deep_per_tx_sui_conservation_check(&self) -> bool {
1113        self.enable_deep_per_tx_sui_conservation_check || cfg!(debug_assertions)
1114    }
1115
1116    pub fn enable_secondary_index_checks(&self) -> bool {
1117        self.enable_secondary_index_checks
1118    }
1119}
1120
1121fn default_checkpoint_execution_max_concurrency() -> usize {
1122    4
1123}
1124
1125fn default_local_execution_timeout_sec() -> u64 {
1126    30
1127}
1128
1129impl Default for CheckpointExecutorConfig {
1130    fn default() -> Self {
1131        Self {
1132            checkpoint_execution_max_concurrency: default_checkpoint_execution_max_concurrency(),
1133            local_execution_timeout_sec: default_local_execution_timeout_sec(),
1134            data_ingestion_dir: None,
1135        }
1136    }
1137}
1138
1139#[derive(Debug, Clone, Deserialize, Serialize)]
1140#[serde(rename_all = "kebab-case")]
1141pub struct AuthorityStorePruningConfig {
1142    /// number of the latest epoch dbs to retain
1143    #[serde(default = "default_num_latest_epoch_dbs_to_retain")]
1144    pub num_latest_epoch_dbs_to_retain: usize,
1145    /// time interval used by the pruner to determine whether there are any epoch DBs to remove
1146    #[serde(default = "default_epoch_db_pruning_period_secs")]
1147    pub epoch_db_pruning_period_secs: u64,
1148    /// number of epochs to keep the latest version of objects for.
1149    /// Note that a zero value corresponds to an aggressive pruner.
1150    /// This mode is experimental and needs to be used with caution.
1151    /// Use `u64::MAX` to disable the pruner for the objects.
1152    #[serde(default)]
1153    pub num_epochs_to_retain: u64,
1154    /// pruner's runtime interval used for aggressive mode
1155    #[serde(skip_serializing_if = "Option::is_none")]
1156    pub pruning_run_delay_seconds: Option<u64>,
1157    /// maximum number of checkpoints in the pruning batch. Can be adjusted to increase performance
1158    #[serde(default = "default_max_checkpoints_in_batch")]
1159    pub max_checkpoints_in_batch: usize,
1160    /// maximum number of transaction in the pruning batch
1161    #[serde(default = "default_max_transactions_in_batch")]
1162    pub max_transactions_in_batch: usize,
1163    /// enables periodic background compaction for old SST files whose last modified time is
1164    /// older than `periodic_compaction_threshold_days` days.
1165    /// That ensures that all sst files eventually go through the compaction process
1166    #[serde(
1167        default = "default_periodic_compaction_threshold_days",
1168        skip_serializing_if = "Option::is_none"
1169    )]
1170    pub periodic_compaction_threshold_days: Option<usize>,
1171    /// number of epochs to keep the latest version of transactions and effects for
1172    #[serde(skip_serializing_if = "Option::is_none")]
1173    pub num_epochs_to_retain_for_checkpoints: Option<u64>,
1174    /// disables object tombstone pruning. We don't serialize it if it is the default value, false.
1175    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1176    pub killswitch_tombstone_pruning: bool,
1177    #[serde(default = "default_smoothing", skip_serializing_if = "is_true")]
1178    pub smooth: bool,
1179    #[serde(skip_serializing_if = "Option::is_none")]
1180    pub num_epochs_to_retain_for_indexes: Option<u64>,
1181}
1182
1183fn default_num_latest_epoch_dbs_to_retain() -> usize {
1184    3
1185}
1186
1187fn default_epoch_db_pruning_period_secs() -> u64 {
1188    3600
1189}
1190
1191fn default_max_transactions_in_batch() -> usize {
1192    1000
1193}
1194
1195fn default_max_checkpoints_in_batch() -> usize {
1196    10
1197}
1198
1199fn default_smoothing() -> bool {
1200    cfg!(not(test))
1201}
1202
1203fn default_periodic_compaction_threshold_days() -> Option<usize> {
1204    Some(1)
1205}
1206
1207impl Default for AuthorityStorePruningConfig {
1208    fn default() -> Self {
1209        Self {
1210            num_latest_epoch_dbs_to_retain: default_num_latest_epoch_dbs_to_retain(),
1211            epoch_db_pruning_period_secs: default_epoch_db_pruning_period_secs(),
1212            num_epochs_to_retain: 0,
1213            pruning_run_delay_seconds: if cfg!(msim) { Some(2) } else { None },
1214            max_checkpoints_in_batch: default_max_checkpoints_in_batch(),
1215            max_transactions_in_batch: default_max_transactions_in_batch(),
1216            periodic_compaction_threshold_days: None,
1217            num_epochs_to_retain_for_checkpoints: if cfg!(msim) { Some(2) } else { None },
1218            killswitch_tombstone_pruning: false,
1219            smooth: true,
1220            num_epochs_to_retain_for_indexes: None,
1221        }
1222    }
1223}
1224
1225impl AuthorityStorePruningConfig {
1226    pub fn set_num_epochs_to_retain(&mut self, num_epochs_to_retain: u64) {
1227        self.num_epochs_to_retain = num_epochs_to_retain;
1228    }
1229
1230    pub fn set_num_epochs_to_retain_for_checkpoints(&mut self, num_epochs_to_retain: Option<u64>) {
1231        self.num_epochs_to_retain_for_checkpoints = num_epochs_to_retain;
1232    }
1233
1234    pub fn num_epochs_to_retain_for_checkpoints(&self) -> Option<u64> {
1235        self.num_epochs_to_retain_for_checkpoints
1236            // if n less than 2, coerce to 2 and log
1237            .map(|n| {
1238                if n < 2 {
1239                    info!("num_epochs_to_retain_for_checkpoints must be at least 2, rounding up from {}", n);
1240                    2
1241                } else {
1242                    n
1243                }
1244            })
1245    }
1246
1247    pub fn set_killswitch_tombstone_pruning(&mut self, killswitch_tombstone_pruning: bool) {
1248        self.killswitch_tombstone_pruning = killswitch_tombstone_pruning;
1249    }
1250}
1251
1252#[derive(Debug, Clone, Deserialize, Serialize)]
1253#[serde(rename_all = "kebab-case")]
1254pub struct MetricsConfig {
1255    #[serde(skip_serializing_if = "Option::is_none")]
1256    pub push_interval_seconds: Option<u64>,
1257    #[serde(skip_serializing_if = "Option::is_none")]
1258    pub push_url: Option<String>,
1259}
1260
1261#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1262#[serde(rename_all = "kebab-case")]
1263pub struct DBCheckpointConfig {
1264    #[serde(default)]
1265    pub perform_db_checkpoints_at_epoch_end: bool,
1266    #[serde(skip_serializing_if = "Option::is_none")]
1267    pub checkpoint_path: Option<PathBuf>,
1268    #[serde(skip_serializing_if = "Option::is_none")]
1269    pub object_store_config: Option<ObjectStoreConfig>,
1270    #[serde(skip_serializing_if = "Option::is_none")]
1271    pub perform_index_db_checkpoints_at_epoch_end: Option<bool>,
1272    #[serde(skip_serializing_if = "Option::is_none")]
1273    pub prune_and_compact_before_upload: Option<bool>,
1274}
1275
1276#[derive(Debug, Clone)]
1277pub struct ArchiveReaderConfig {
1278    pub remote_store_config: ObjectStoreConfig,
1279    pub download_concurrency: NonZeroUsize,
1280    pub ingestion_url: Option<String>,
1281    pub remote_store_options: Vec<(String, String)>,
1282}
1283
1284#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1285#[serde(rename_all = "kebab-case")]
1286pub struct StateArchiveConfig {
1287    #[serde(skip_serializing_if = "Option::is_none")]
1288    pub object_store_config: Option<ObjectStoreConfig>,
1289    pub concurrency: usize,
1290    #[serde(skip_serializing_if = "Option::is_none")]
1291    pub ingestion_url: Option<String>,
1292    #[serde(
1293        skip_serializing_if = "Vec::is_empty",
1294        default,
1295        deserialize_with = "deserialize_remote_store_options"
1296    )]
1297    pub remote_store_options: Vec<(String, String)>,
1298}
1299
1300#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1301#[serde(rename_all = "kebab-case")]
1302pub struct StateSnapshotConfig {
1303    #[serde(skip_serializing_if = "Option::is_none")]
1304    pub object_store_config: Option<ObjectStoreConfig>,
1305    pub concurrency: usize,
1306    /// Archive snapshots every N epochs. If set to 0, archival is disabled.
1307    /// Archived snapshots are copied to `archive/epoch_<N>/` in the same bucket
1308    /// and are intended to be kept indefinitely.
1309    #[serde(default)]
1310    pub archive_interval_epochs: u64,
1311}
1312
1313#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1314#[serde(rename_all = "kebab-case")]
1315pub struct TransactionKeyValueStoreWriteConfig {
1316    pub aws_access_key_id: String,
1317    pub aws_secret_access_key: String,
1318    pub aws_region: String,
1319    pub table_name: String,
1320    pub bucket_name: String,
1321    pub concurrency: usize,
1322}
1323
1324/// Configuration for the threshold(s) at which we consider the system
1325/// to be overloaded. When one of the threshold is passed, the node may
1326/// stop processing new transactions and/or certificates until the congestion
1327/// resolves.
1328#[derive(Clone, Debug, Deserialize, Serialize)]
1329#[serde(rename_all = "kebab-case")]
1330pub struct AuthorityOverloadConfig {
1331    #[serde(default = "default_max_txn_age_in_queue")]
1332    pub max_txn_age_in_queue: Duration,
1333
1334    // The interval of checking overload signal.
1335    #[serde(default = "default_overload_monitor_interval")]
1336    pub overload_monitor_interval: Duration,
1337
1338    // The execution queueing latency when entering load shedding mode.
1339    #[serde(default = "default_execution_queue_latency_soft_limit")]
1340    pub execution_queue_latency_soft_limit: Duration,
1341
1342    // The execution queueing latency when entering aggressive load shedding mode.
1343    #[serde(default = "default_execution_queue_latency_hard_limit")]
1344    pub execution_queue_latency_hard_limit: Duration,
1345
1346    // The maximum percentage of transactions to shed in load shedding mode.
1347    #[serde(default = "default_max_load_shedding_percentage")]
1348    pub max_load_shedding_percentage: u32,
1349
1350    // When in aggressive load shedding mode, the minimum percentage of
1351    // transactions to shed.
1352    #[serde(default = "default_min_load_shedding_percentage_above_hard_limit")]
1353    pub min_load_shedding_percentage_above_hard_limit: u32,
1354
1355    // If transaction ready rate is below this rate, we consider the validator
1356    // is well under used, and will not enter load shedding mode.
1357    #[serde(default = "default_safe_transaction_ready_rate")]
1358    pub safe_transaction_ready_rate: u32,
1359
1360    // When set to true, transaction signing may be rejected when the validator
1361    // is overloaded.
1362    #[serde(default = "default_check_system_overload_at_signing")]
1363    pub check_system_overload_at_signing: bool,
1364
1365    // When set to true, transaction execution may be rejected when the validator
1366    // is overloaded.
1367    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1368    pub check_system_overload_at_execution: bool,
1369
1370    // Reject a transaction if transaction manager queue length is above this threshold.
1371    // 100_000 = 10k TPS * 5s resident time in transaction manager (pending + executing) * 2.
1372    #[serde(default = "default_max_transaction_manager_queue_length")]
1373    pub max_transaction_manager_queue_length: usize,
1374
1375    // Reject a transaction if the number of pending transactions depending on the object
1376    // is above the threshold.
1377    #[serde(default = "default_max_transaction_manager_per_object_queue_length")]
1378    pub max_transaction_manager_per_object_queue_length: usize,
1379}
1380
1381fn default_max_txn_age_in_queue() -> Duration {
1382    Duration::from_millis(1000)
1383}
1384
1385fn default_overload_monitor_interval() -> Duration {
1386    Duration::from_secs(10)
1387}
1388
1389fn default_execution_queue_latency_soft_limit() -> Duration {
1390    Duration::from_secs(1)
1391}
1392
1393fn default_execution_queue_latency_hard_limit() -> Duration {
1394    Duration::from_secs(10)
1395}
1396
1397fn default_max_load_shedding_percentage() -> u32 {
1398    95
1399}
1400
1401fn default_min_load_shedding_percentage_above_hard_limit() -> u32 {
1402    50
1403}
1404
1405fn default_safe_transaction_ready_rate() -> u32 {
1406    100
1407}
1408
1409fn default_check_system_overload_at_signing() -> bool {
1410    true
1411}
1412
1413fn default_max_transaction_manager_queue_length() -> usize {
1414    100_000
1415}
1416
1417fn default_max_transaction_manager_per_object_queue_length() -> usize {
1418    2000
1419}
1420
1421impl Default for AuthorityOverloadConfig {
1422    fn default() -> Self {
1423        Self {
1424            max_txn_age_in_queue: default_max_txn_age_in_queue(),
1425            overload_monitor_interval: default_overload_monitor_interval(),
1426            execution_queue_latency_soft_limit: default_execution_queue_latency_soft_limit(),
1427            execution_queue_latency_hard_limit: default_execution_queue_latency_hard_limit(),
1428            max_load_shedding_percentage: default_max_load_shedding_percentage(),
1429            min_load_shedding_percentage_above_hard_limit:
1430                default_min_load_shedding_percentage_above_hard_limit(),
1431            safe_transaction_ready_rate: default_safe_transaction_ready_rate(),
1432            check_system_overload_at_signing: true,
1433            check_system_overload_at_execution: false,
1434            max_transaction_manager_queue_length: default_max_transaction_manager_queue_length(),
1435            max_transaction_manager_per_object_queue_length:
1436                default_max_transaction_manager_per_object_queue_length(),
1437        }
1438    }
1439}
1440
1441fn default_authority_overload_config() -> AuthorityOverloadConfig {
1442    AuthorityOverloadConfig::default()
1443}
1444
1445fn default_traffic_controller_policy_config() -> Option<PolicyConfig> {
1446    Some(PolicyConfig::default_dos_protection_policy())
1447}
1448
1449#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1450pub struct Genesis {
1451    #[serde(flatten)]
1452    location: GenesisLocation,
1453
1454    #[serde(skip)]
1455    genesis: once_cell::sync::OnceCell<genesis::Genesis>,
1456}
1457
1458impl Genesis {
1459    pub fn new(genesis: genesis::Genesis) -> Self {
1460        Self {
1461            location: GenesisLocation::InPlace { genesis },
1462            genesis: Default::default(),
1463        }
1464    }
1465
1466    pub fn new_from_file<P: Into<PathBuf>>(path: P) -> Self {
1467        Self {
1468            location: GenesisLocation::File {
1469                genesis_file_location: path.into(),
1470            },
1471            genesis: Default::default(),
1472        }
1473    }
1474
1475    pub fn genesis(&self) -> Result<&genesis::Genesis> {
1476        match &self.location {
1477            GenesisLocation::InPlace { genesis } => Ok(genesis),
1478            GenesisLocation::File {
1479                genesis_file_location,
1480            } => self
1481                .genesis
1482                .get_or_try_init(|| genesis::Genesis::load(genesis_file_location)),
1483        }
1484    }
1485}
1486
1487#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1488#[serde(untagged)]
1489#[allow(clippy::large_enum_variant)]
1490enum GenesisLocation {
1491    InPlace {
1492        genesis: genesis::Genesis,
1493    },
1494    File {
1495        #[serde(rename = "genesis-file-location")]
1496        genesis_file_location: PathBuf,
1497    },
1498}
1499
1500/// Wrapper struct for SuiKeyPair that can be deserialized from a file path. Used by network, worker, and account keypair.
1501#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
1502pub struct KeyPairWithPath {
1503    #[serde(flatten)]
1504    location: KeyPairLocation,
1505
1506    #[serde(skip)]
1507    keypair: OnceCell<Arc<SuiKeyPair>>,
1508}
1509
1510#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1511#[serde_as]
1512#[serde(untagged)]
1513enum KeyPairLocation {
1514    InPlace {
1515        #[serde_as(as = "Arc<KeyPairBase64>")]
1516        value: Arc<SuiKeyPair>,
1517    },
1518    File {
1519        #[serde(rename = "path")]
1520        path: PathBuf,
1521    },
1522}
1523
1524impl KeyPairWithPath {
1525    pub fn new(kp: SuiKeyPair) -> Self {
1526        let cell: OnceCell<Arc<SuiKeyPair>> = OnceCell::new();
1527        let arc_kp = Arc::new(kp);
1528        // OK to unwrap panic because authority should not start without all keypairs loaded.
1529        cell.set(arc_kp.clone()).expect("Failed to set keypair");
1530        Self {
1531            location: KeyPairLocation::InPlace { value: arc_kp },
1532            keypair: cell,
1533        }
1534    }
1535
1536    pub fn new_from_path(path: PathBuf) -> Self {
1537        let cell: OnceCell<Arc<SuiKeyPair>> = OnceCell::new();
1538        // OK to unwrap panic because authority should not start without all keypairs loaded.
1539        cell.set(Arc::new(read_keypair_from_file(&path).unwrap_or_else(
1540            |e| panic!("Invalid keypair file at path {:?}: {e}", &path),
1541        )))
1542        .expect("Failed to set keypair");
1543        Self {
1544            location: KeyPairLocation::File { path },
1545            keypair: cell,
1546        }
1547    }
1548
1549    pub fn keypair(&self) -> &SuiKeyPair {
1550        self.keypair
1551            .get_or_init(|| match &self.location {
1552                KeyPairLocation::InPlace { value } => value.clone(),
1553                KeyPairLocation::File { path } => {
1554                    // OK to unwrap panic because authority should not start without all keypairs loaded.
1555                    Arc::new(
1556                        read_keypair_from_file(path).unwrap_or_else(|e| {
1557                            panic!("Invalid keypair file at path {:?}: {e}", path)
1558                        }),
1559                    )
1560                }
1561            })
1562            .as_ref()
1563    }
1564}
1565
1566/// Wrapper struct for AuthorityKeyPair that can be deserialized from a file path.
1567#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
1568pub struct AuthorityKeyPairWithPath {
1569    #[serde(flatten)]
1570    location: AuthorityKeyPairLocation,
1571
1572    #[serde(skip)]
1573    keypair: OnceCell<Arc<AuthorityKeyPair>>,
1574}
1575
1576#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1577#[serde_as]
1578#[serde(untagged)]
1579enum AuthorityKeyPairLocation {
1580    InPlace { value: Arc<AuthorityKeyPair> },
1581    File { path: PathBuf },
1582}
1583
1584impl AuthorityKeyPairWithPath {
1585    pub fn new(kp: AuthorityKeyPair) -> Self {
1586        let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1587        let arc_kp = Arc::new(kp);
1588        // OK to unwrap panic because authority should not start without all keypairs loaded.
1589        cell.set(arc_kp.clone())
1590            .expect("Failed to set authority keypair");
1591        Self {
1592            location: AuthorityKeyPairLocation::InPlace { value: arc_kp },
1593            keypair: cell,
1594        }
1595    }
1596
1597    pub fn new_from_path(path: PathBuf) -> Self {
1598        let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1599        // OK to unwrap panic because authority should not start without all keypairs loaded.
1600        cell.set(Arc::new(
1601            read_authority_keypair_from_file(&path)
1602                .unwrap_or_else(|_| panic!("Invalid authority keypair file at path {:?}", &path)),
1603        ))
1604        .expect("Failed to set authority keypair");
1605        Self {
1606            location: AuthorityKeyPairLocation::File { path },
1607            keypair: cell,
1608        }
1609    }
1610
1611    pub fn authority_keypair(&self) -> &AuthorityKeyPair {
1612        self.keypair
1613            .get_or_init(|| match &self.location {
1614                AuthorityKeyPairLocation::InPlace { value } => value.clone(),
1615                AuthorityKeyPairLocation::File { path } => {
1616                    // OK to unwrap panic because authority should not start without all keypairs loaded.
1617                    Arc::new(
1618                        read_authority_keypair_from_file(path).unwrap_or_else(|_| {
1619                            panic!("Invalid authority keypair file {:?}", &path)
1620                        }),
1621                    )
1622                }
1623            })
1624            .as_ref()
1625    }
1626}
1627
1628/// Configurations which determine how we dump state debug info.
1629/// Debug info is dumped when a node forks.
1630#[derive(Clone, Debug, Deserialize, Serialize, Default)]
1631#[serde(rename_all = "kebab-case")]
1632pub struct StateDebugDumpConfig {
1633    #[serde(skip_serializing_if = "Option::is_none")]
1634    pub dump_file_directory: Option<PathBuf>,
1635}
1636
1637fn read_credential_from_path_or_literal(value: &str) -> Result<String, std::io::Error> {
1638    let path = Path::new(value);
1639    if path.exists() && path.is_file() {
1640        std::fs::read_to_string(path).map(|content| content.trim().to_string())
1641    } else {
1642        Ok(value.to_string())
1643    }
1644}
1645
1646// Custom deserializer for remote store options that supports file paths or literal values
1647fn deserialize_remote_store_options<'de, D>(
1648    deserializer: D,
1649) -> Result<Vec<(String, String)>, D::Error>
1650where
1651    D: serde::Deserializer<'de>,
1652{
1653    use serde::de::Error;
1654
1655    let raw_options: Vec<(String, String)> = Vec::deserialize(deserializer)?;
1656    let mut processed_options = Vec::new();
1657
1658    for (key, value) in raw_options {
1659        // GCS service_account keys expect a file path, not the file content
1660        // All other keys (AWS credentials, service_account_key) should read file content
1661        let is_service_account_path = matches!(
1662            key.as_str(),
1663            "google_service_account"
1664                | "service_account"
1665                | "google_service_account_path"
1666                | "service_account_path"
1667        );
1668
1669        let processed_value = if is_service_account_path {
1670            value
1671        } else {
1672            match read_credential_from_path_or_literal(&value) {
1673                Ok(processed) => processed,
1674                Err(e) => {
1675                    return Err(D::Error::custom(format!(
1676                        "Failed to read credential for key '{}': {}",
1677                        key, e
1678                    )));
1679                }
1680            }
1681        };
1682
1683        processed_options.push((key, processed_value));
1684    }
1685
1686    Ok(processed_options)
1687}
1688
1689#[cfg(test)]
1690mod tests {
1691    use std::path::PathBuf;
1692
1693    use fastcrypto::traits::KeyPair;
1694    use rand::{SeedableRng, rngs::StdRng};
1695    use sui_keys::keypair_file::{write_authority_keypair_to_file, write_keypair_to_file};
1696    use sui_types::crypto::{AuthorityKeyPair, NetworkKeyPair, SuiKeyPair, get_key_pair_from_rng};
1697
1698    use super::{Genesis, StateArchiveConfig};
1699    use crate::NodeConfig;
1700
1701    #[test]
1702    fn serialize_genesis_from_file() {
1703        let g = Genesis::new_from_file("path/to/file");
1704
1705        let s = serde_yaml::to_string(&g).unwrap();
1706        assert_eq!("---\ngenesis-file-location: path/to/file\n", s);
1707        let loaded_genesis: Genesis = serde_yaml::from_str(&s).unwrap();
1708        assert_eq!(g, loaded_genesis);
1709    }
1710
1711    #[test]
1712    fn fullnode_template() {
1713        const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1714
1715        let _template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1716    }
1717
1718    /// Tests that a legacy validator config (captured on 12/06/2024) can be parsed.
1719    #[test]
1720    fn legacy_validator_config() {
1721        const FILE: &str = include_str!("../data/sui-node-legacy.yaml");
1722
1723        let _template: NodeConfig = serde_yaml::from_str(FILE).unwrap();
1724    }
1725
1726    #[test]
1727    fn load_key_pairs_to_node_config() {
1728        let protocol_key_pair: AuthorityKeyPair =
1729            get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1730        let worker_key_pair: NetworkKeyPair =
1731            get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1732        let network_key_pair: NetworkKeyPair =
1733            get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1734
1735        write_authority_keypair_to_file(&protocol_key_pair, PathBuf::from("protocol.key")).unwrap();
1736        write_keypair_to_file(
1737            &SuiKeyPair::Ed25519(worker_key_pair.copy()),
1738            PathBuf::from("worker.key"),
1739        )
1740        .unwrap();
1741        write_keypair_to_file(
1742            &SuiKeyPair::Ed25519(network_key_pair.copy()),
1743            PathBuf::from("network.key"),
1744        )
1745        .unwrap();
1746
1747        const TEMPLATE: &str = include_str!("../data/fullnode-template-with-path.yaml");
1748        let template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1749        assert_eq!(
1750            template.protocol_key_pair().public(),
1751            protocol_key_pair.public()
1752        );
1753        assert_eq!(
1754            template.network_key_pair().public(),
1755            network_key_pair.public()
1756        );
1757        assert_eq!(
1758            template.worker_key_pair().public(),
1759            worker_key_pair.public()
1760        );
1761    }
1762
1763    #[test]
1764    fn test_remote_store_options_file_path_support() {
1765        // Create temporary credential files
1766        let temp_dir = std::env::temp_dir();
1767        let access_key_file = temp_dir.join("test_access_key");
1768        let secret_key_file = temp_dir.join("test_secret_key");
1769
1770        std::fs::write(&access_key_file, "test_access_key_value").unwrap();
1771        std::fs::write(&secret_key_file, "test_secret_key_value\n").unwrap();
1772
1773        let yaml_config = format!(
1774            r#"
1775object-store-config: null
1776concurrency: 5
1777ingestion-url: "https://example.com"
1778remote-store-options:
1779  - ["aws_access_key_id", "{}"]
1780  - ["aws_secret_access_key", "{}"]
1781  - ["literal_key", "literal_value"]
1782"#,
1783            access_key_file.to_string_lossy(),
1784            secret_key_file.to_string_lossy()
1785        );
1786
1787        let config: StateArchiveConfig = serde_yaml::from_str(&yaml_config).unwrap();
1788
1789        // Verify that file paths were resolved and literal values preserved
1790        assert_eq!(config.remote_store_options.len(), 3);
1791
1792        let access_key_option = config
1793            .remote_store_options
1794            .iter()
1795            .find(|(key, _)| key == "aws_access_key_id")
1796            .unwrap();
1797        assert_eq!(access_key_option.1, "test_access_key_value");
1798
1799        let secret_key_option = config
1800            .remote_store_options
1801            .iter()
1802            .find(|(key, _)| key == "aws_secret_access_key")
1803            .unwrap();
1804        assert_eq!(secret_key_option.1, "test_secret_key_value");
1805
1806        let literal_option = config
1807            .remote_store_options
1808            .iter()
1809            .find(|(key, _)| key == "literal_key")
1810            .unwrap();
1811        assert_eq!(literal_option.1, "literal_value");
1812
1813        // Clean up
1814        std::fs::remove_file(&access_key_file).ok();
1815        std::fs::remove_file(&secret_key_file).ok();
1816    }
1817
1818    #[test]
1819    fn test_remote_store_options_literal_values_only() {
1820        let yaml_config = r#"
1821object-store-config: null
1822concurrency: 5
1823ingestion-url: "https://example.com"
1824remote-store-options:
1825  - ["aws_access_key_id", "literal_access_key"]
1826  - ["aws_secret_access_key", "literal_secret_key"]
1827"#;
1828
1829        let config: StateArchiveConfig = serde_yaml::from_str(yaml_config).unwrap();
1830
1831        assert_eq!(config.remote_store_options.len(), 2);
1832        assert_eq!(config.remote_store_options[0].1, "literal_access_key");
1833        assert_eq!(config.remote_store_options[1].1, "literal_secret_key");
1834    }
1835
1836    #[test]
1837    fn test_remote_store_options_gcs_service_account_path_preserved() {
1838        let temp_dir = std::env::temp_dir();
1839        let service_account_file = temp_dir.join("test_service_account.json");
1840        let aws_key_file = temp_dir.join("test_aws_key");
1841
1842        std::fs::write(&service_account_file, r#"{"type": "service_account"}"#).unwrap();
1843        std::fs::write(&aws_key_file, "aws_key_value").unwrap();
1844
1845        let yaml_config = format!(
1846            r#"
1847object-store-config: null
1848concurrency: 5
1849ingestion-url: "gs://my-bucket"
1850remote-store-options:
1851  - ["service_account", "{}"]
1852  - ["google_service_account_path", "{}"]
1853  - ["aws_access_key_id", "{}"]
1854"#,
1855            service_account_file.to_string_lossy(),
1856            service_account_file.to_string_lossy(),
1857            aws_key_file.to_string_lossy()
1858        );
1859
1860        let config: StateArchiveConfig = serde_yaml::from_str(&yaml_config).unwrap();
1861
1862        assert_eq!(config.remote_store_options.len(), 3);
1863
1864        // service_account should preserve the file path, not read the content
1865        let service_account_option = config
1866            .remote_store_options
1867            .iter()
1868            .find(|(key, _)| key == "service_account")
1869            .unwrap();
1870        assert_eq!(
1871            service_account_option.1,
1872            service_account_file.to_string_lossy()
1873        );
1874
1875        // google_service_account_path should also preserve the file path
1876        let gcs_path_option = config
1877            .remote_store_options
1878            .iter()
1879            .find(|(key, _)| key == "google_service_account_path")
1880            .unwrap();
1881        assert_eq!(gcs_path_option.1, service_account_file.to_string_lossy());
1882
1883        // AWS key should read the file content
1884        let aws_option = config
1885            .remote_store_options
1886            .iter()
1887            .find(|(key, _)| key == "aws_access_key_id")
1888            .unwrap();
1889        assert_eq!(aws_option.1, "aws_key_value");
1890
1891        // Clean up
1892        std::fs::remove_file(&service_account_file).ok();
1893        std::fs::remove_file(&aws_key_file).ok();
1894    }
1895}
1896
1897// RunWithRange is used to specify the ending epoch/checkpoint to process.
1898// this is intended for use with disaster recovery debugging and verification workflows, never in normal operations
1899#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
1900pub enum RunWithRange {
1901    Epoch(EpochId),
1902    Checkpoint(CheckpointSequenceNumber),
1903}
1904
1905impl RunWithRange {
1906    // is epoch_id > RunWithRange::Epoch
1907    pub fn is_epoch_gt(&self, epoch_id: EpochId) -> bool {
1908        matches!(self, RunWithRange::Epoch(e) if epoch_id > *e)
1909    }
1910
1911    pub fn matches_checkpoint(&self, seq_num: CheckpointSequenceNumber) -> bool {
1912        matches!(self, RunWithRange::Checkpoint(seq) if *seq == seq_num)
1913    }
1914
1915    pub fn into_checkpoint_bound(self) -> Option<CheckpointSequenceNumber> {
1916        match self {
1917            RunWithRange::Epoch(_) => None,
1918            RunWithRange::Checkpoint(seq) => Some(seq),
1919        }
1920    }
1921}