1use 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
40pub const DEFAULT_GRPC_CONCURRENCY_LIMIT: usize = 20000000000;
42
43pub const DEFAULT_VALIDATOR_GAS_PRICE: u64 = sui_types::transaction::DEFAULT_VALIDATOR_GAS_PRICE;
45
46pub const DEFAULT_COMMISSION_RATE: u64 = 200;
48
49#[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 #[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 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 #[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 #[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 #[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 #[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 #[serde(skip)]
209 #[serde(default = "bool_true")]
210 pub state_accumulator_v2: bool,
211
212 #[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 #[serde(skip_serializing_if = "Option::is_none")]
227 pub enable_db_write_stall: Option<bool>,
228
229 #[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 #[serde(skip_serializing_if = "Option::is_none")]
242 pub chain_override_for_testing: Option<Chain>,
243
244 #[serde(skip_serializing_if = "Option::is_none")]
247 pub validator_client_monitor_config: Option<ValidatorClientMonitorConfig>,
248
249 #[serde(skip_serializing_if = "Option::is_none")]
251 pub fork_recovery: Option<ForkRecoveryConfig>,
252
253 #[serde(skip_serializing_if = "Option::is_none")]
255 pub transaction_driver_config: Option<TransactionDriverConfig>,
256
257 #[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 #[serde(default, skip_serializing_if = "Vec::is_empty")]
269 pub allowed_submission_validators: Vec<String>,
270
271 #[serde(default, skip_serializing_if = "Vec::is_empty")]
274 pub blocked_submission_validators: Vec<String>,
275
276 #[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 }
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 #[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 #[serde(default)]
329 pub transaction_overrides: BTreeMap<String, String>,
330
331 #[serde(default)]
335 pub checkpoint_overrides: BTreeMap<u64, String>,
336
337 #[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 pub observation_channel_capacity: Option<NonZeroUsize>,
349
350 pub observation_cache_size: Option<NonZeroUsize>,
354
355 pub object_debt_channel_capacity: Option<NonZeroUsize>,
359
360 pub object_utilization_cache_size: Option<NonZeroUsize>,
364
365 pub report_object_utilization_metric_with_full_id: Option<bool>,
376
377 pub observation_sharing_object_utilization_threshold: Option<Duration>,
382
383 pub observation_sharing_diff_threshold: Option<f64>,
388
389 pub observation_sharing_min_interval: Option<Duration>,
393
394 pub observation_sharing_rate_limit: Option<NonZeroU32>,
399
400 pub observation_sharing_burst_limit: Option<NonZeroU32>,
404
405 pub enable_gas_price_weighting: Option<bool>,
412
413 pub weighted_moving_average_window_size: Option<usize>,
420
421 #[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 max_cache_size: Option<u64>,
502
503 package_cache_size: Option<u64>, object_cache_size: Option<u64>, marker_cache_size: Option<u64>, object_by_id_cache_size: Option<u64>, transaction_cache_size: Option<u64>, executed_effect_cache_size: Option<u64>, effect_cache_size: Option<u64>, events_cache_size: Option<u64>, transaction_objects_cache_size: Option<u64>, backpressure_threshold: Option<u64>,
519
520 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 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(), "AwsTenant-region:eu-west-3-tenant_id:eu-west-3_gGVCx53Es".to_string(), "EveFrontier".to_string(),
758 "TestEveFrontier".to_string(),
759 "AwsTenant-region:ap-southeast-1-tenant_id:ap-southeast-1_2QQPyQXDz".to_string(), "AwsTenant-region:eu-north-1-tenant_id:eu-north-1_rz7IVMOR5".to_string(), "AwsTenant-region:eu-north-1-tenant_id:eu-north-1_K3XgRburu".to_string(), ]);
763
764 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(), "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(), ]);
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 pub db_path: PathBuf,
942
943 pub db_retention_epochs: Option<u64>,
946
947 pub db_pruner_period_secs: Option<u64>,
950
951 pub max_pending_transactions: Option<usize>,
955
956 pub max_submit_position: Option<usize>,
959
960 pub submit_delay_step_override_millis: Option<u64>,
964
965 pub parameters: Option<ConsensusParameters>,
966
967 #[serde(skip_serializing_if = "Option::is_none")]
971 pub listen_address: Option<Multiaddr>,
972
973 #[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 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 #[serde(default = "default_checkpoint_execution_max_concurrency")]
1014 pub checkpoint_execution_max_concurrency: usize,
1015
1016 #[serde(default = "default_local_execution_timeout_sec")]
1022 pub local_execution_timeout_sec: u64,
1023
1024 #[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 #[serde(default)]
1038 enable_epoch_sui_conservation_check: bool,
1039
1040 #[serde(default)]
1044 enable_deep_per_tx_sui_conservation_check: bool,
1045
1046 #[serde(default)]
1048 force_disable_epoch_sui_conservation_check: bool,
1049
1050 #[serde(default)]
1053 enable_state_consistency_check: bool,
1054
1055 #[serde(default)]
1057 force_disable_state_consistency_check: bool,
1058
1059 #[serde(default)]
1060 enable_secondary_index_checks: bool,
1061 }
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, }
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 #[serde(default = "default_num_latest_epoch_dbs_to_retain")]
1144 pub num_latest_epoch_dbs_to_retain: usize,
1145 #[serde(default = "default_epoch_db_pruning_period_secs")]
1147 pub epoch_db_pruning_period_secs: u64,
1148 #[serde(default)]
1153 pub num_epochs_to_retain: u64,
1154 #[serde(skip_serializing_if = "Option::is_none")]
1156 pub pruning_run_delay_seconds: Option<u64>,
1157 #[serde(default = "default_max_checkpoints_in_batch")]
1159 pub max_checkpoints_in_batch: usize,
1160 #[serde(default = "default_max_transactions_in_batch")]
1162 pub max_transactions_in_batch: usize,
1163 #[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 #[serde(skip_serializing_if = "Option::is_none")]
1173 pub num_epochs_to_retain_for_checkpoints: Option<u64>,
1174 #[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 .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 #[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#[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 #[serde(default = "default_overload_monitor_interval")]
1336 pub overload_monitor_interval: Duration,
1337
1338 #[serde(default = "default_execution_queue_latency_soft_limit")]
1340 pub execution_queue_latency_soft_limit: Duration,
1341
1342 #[serde(default = "default_execution_queue_latency_hard_limit")]
1344 pub execution_queue_latency_hard_limit: Duration,
1345
1346 #[serde(default = "default_max_load_shedding_percentage")]
1348 pub max_load_shedding_percentage: u32,
1349
1350 #[serde(default = "default_min_load_shedding_percentage_above_hard_limit")]
1353 pub min_load_shedding_percentage_above_hard_limit: u32,
1354
1355 #[serde(default = "default_safe_transaction_ready_rate")]
1358 pub safe_transaction_ready_rate: u32,
1359
1360 #[serde(default = "default_check_system_overload_at_signing")]
1363 pub check_system_overload_at_signing: bool,
1364
1365 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1368 pub check_system_overload_at_execution: bool,
1369
1370 #[serde(default = "default_max_transaction_manager_queue_length")]
1373 pub max_transaction_manager_queue_length: usize,
1374
1375 #[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#[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 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 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 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#[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 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 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 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#[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
1646fn 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 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 #[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 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 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 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 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 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 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 std::fs::remove_file(&service_account_file).ok();
1893 std::fs::remove_file(&aws_key_file).ok();
1894 }
1895}
1896
1897#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
1900pub enum RunWithRange {
1901 Epoch(EpochId),
1902 Checkpoint(CheckpointSequenceNumber),
1903}
1904
1905impl RunWithRange {
1906 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}