1use std::{
6 net::{IpAddr, Ipv4Addr, SocketAddr},
7 num::NonZeroUsize,
8 path::{Path, PathBuf},
9 sync::Arc,
10 time::Duration,
11};
12
13use anyhow::Result;
14use fastcrypto::ed25519::Ed25519KeyPair;
15use iota_keys::keypair_file::{read_authority_keypair_from_file, read_keypair_from_file};
16use iota_metrics::MetricGroups;
17use iota_multiaddr::Multiaddr;
18use iota_names::config::IotaNamesConfig;
19use iota_sdk_crypto::simple::SimpleKeypair;
20use iota_sdk_types::Address;
21use iota_types::{
22 committee::EpochId,
23 crypto::{
24 AccountPrivateKey, AuthorityKeyPair, AuthorityPublicKeyBytes, KeypairTraits,
25 NetworkKeyPair, get_key_pair_from_rng, simple_to_network_keypair,
26 },
27 messages_checkpoint::CheckpointSequenceNumber,
28 supported_protocol_versions::{Chain, SupportedProtocolVersions},
29 traffic_control::{PolicyConfig, RemoteFirewallConfig},
30};
31use once_cell::sync::OnceCell;
32use rand::rngs::OsRng;
33use serde::{Deserialize, Serialize};
34use starfish_config::Parameters as StarfishParameters;
35use tracing::info;
36
37use crate::{
38 Config, certificate_deny_config::CertificateDenyConfig, genesis,
39 migration_tx_data::MigrationTxData, object_storage_config::ObjectStoreConfig, p2p::P2pConfig,
40 transaction_deny_config::TransactionDenyConfig, verifier_signing_config::VerifierSigningConfig,
41};
42
43pub const DEFAULT_VALIDATOR_GAS_PRICE: u64 = iota_types::transaction::DEFAULT_VALIDATOR_GAS_PRICE;
45
46pub const DEFAULT_COMMISSION_RATE: u64 = 200;
48
49pub const DEFAULT_FULL_CHECKPOINT_CONTENTS_CACHE_SIZE_MB: usize = 1024;
51
52#[derive(Clone, Debug, Deserialize, Serialize)]
53#[serde(rename_all = "kebab-case")]
54pub struct NodeConfig {
55 #[serde(default = "default_authority_key_pair")]
58 pub authority_key_pair: AuthorityKeyPairWithPath,
59 #[serde(default = "default_key_pair")]
62 pub protocol_key_pair: KeyPairWithPath,
63 #[serde(default = "default_key_pair")]
64 pub account_key_pair: KeyPairWithPath,
65 #[serde(default = "default_key_pair")]
68 pub network_key_pair: KeyPairWithPath,
69 pub db_path: PathBuf,
70
71 #[serde(default = "default_grpc_address")]
75 pub network_address: Multiaddr,
76 #[serde(default = "default_json_rpc_address")]
77 pub json_rpc_address: SocketAddr,
78
79 #[serde(default = "default_metrics_address")]
81 pub metrics_address: SocketAddr,
82
83 #[serde(default = "default_admin_interface_address")]
87 pub admin_interface_address: SocketAddr,
88
89 #[serde(skip_serializing_if = "Option::is_none")]
91 pub consensus_config: Option<ConsensusConfig>,
92
93 #[serde(default = "default_enable_index_processing")]
98 pub enable_index_processing: bool,
99
100 #[serde(default)]
102 pub jsonrpc_server_type: Option<ServerType>,
107
108 #[serde(default)]
112 pub grpc_load_shed: Option<bool>,
113
114 #[serde(default = "default_grpc_concurrency_limit_per_core")]
131 pub grpc_concurrency_limit_per_core: NonZeroUsize,
132
133 #[serde(default)]
135 pub p2p_config: P2pConfig,
136
137 pub genesis: Genesis,
141
142 pub migration_tx_data_path: Option<PathBuf>,
144
145 #[serde(default = "default_authority_store_pruning_config")]
148 pub authority_store_pruning_config: AuthorityStorePruningConfig,
149
150 #[serde(default = "default_end_of_epoch_broadcast_channel_capacity")]
155 pub end_of_epoch_broadcast_channel_capacity: usize,
156
157 #[serde(default)]
161 pub checkpoint_executor_config: CheckpointExecutorConfig,
162
163 #[serde(skip_serializing_if = "Option::is_none")]
164 pub metrics: Option<MetricsConfig>,
165
166 #[serde(skip)]
171 pub supported_protocol_versions: Option<SupportedProtocolVersions>,
172
173 #[serde(default)]
175 pub expensive_safety_check_config: ExpensiveSafetyCheckConfig,
176
177 #[serde(default)]
181 pub transaction_deny_config: TransactionDenyConfig,
182
183 #[serde(default)]
189 pub certificate_deny_config: CertificateDenyConfig,
190
191 #[serde(default)]
194 pub state_debug_dump_config: StateDebugDumpConfig,
195
196 #[serde(default)]
197 pub checkpoint_archive_config: Option<CheckpointArchiveConfig>,
198
199 #[serde(default)]
201 pub state_snapshot_write_config: StateSnapshotConfig,
202
203 #[serde(default)]
204 pub indexer_max_subscriptions: Option<usize>,
205
206 #[serde(default = "default_transaction_kv_store_config")]
207 pub transaction_kv_store_read_config: TransactionKeyValueStoreReadConfig,
208
209 #[serde(skip_serializing_if = "Option::is_none")]
211 pub transaction_kv_store_write_config: Option<TransactionKeyValueStoreWriteConfig>,
212
213 #[serde(default = "default_authority_overload_config")]
216 pub authority_overload_config: AuthorityOverloadConfig,
217
218 #[serde(skip_serializing_if = "Option::is_none")]
222 pub run_with_range: Option<RunWithRange>,
223
224 #[serde(
231 skip_serializing_if = "is_default_traffic_controller_policy_config",
232 default = "default_traffic_controller_policy_config"
233 )]
234 pub policy_config: Option<PolicyConfig>,
235
236 #[serde(skip_serializing_if = "Option::is_none")]
237 pub firewall_config: Option<RemoteFirewallConfig>,
238
239 #[serde(default)]
240 pub execution_cache_config: ExecutionCacheConfig,
241
242 #[serde(default = "default_full_checkpoint_contents_cache_size_mb")]
253 pub full_checkpoint_contents_cache_size_mb: usize,
254
255 #[serde(default = "bool_true")]
256 pub enable_validator_tx_finalizer: bool,
257
258 #[serde(default = "bool_true")]
264 pub enable_soft_locking: bool,
265
266 #[serde(default)]
267 pub verifier_signing_config: VerifierSigningConfig,
268
269 #[serde(skip_serializing_if = "Option::is_none")]
273 pub enable_db_write_stall: Option<bool>,
274
275 #[serde(default, skip_serializing_if = "Option::is_none")]
276 pub iota_names_config: Option<IotaNamesConfig>,
277
278 #[serde(default)]
280 pub enable_grpc_api: bool,
281 #[serde(
287 default = "default_grpc_api_config",
288 skip_serializing_if = "is_default_grpc_api_config"
289 )]
290 pub grpc_api_config: Option<GrpcApiConfig>,
291
292 #[serde(skip_serializing_if = "Option::is_none")]
297 pub chain_override_for_testing: Option<Chain>,
298
299 #[serde(default, skip_serializing_if = "Option::is_none")]
302 pub validator_client_monitor_config:
303 Option<crate::validator_client_monitor_config::ValidatorClientMonitorConfig>,
304}
305
306#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
307#[serde(rename_all = "kebab-case")]
308pub struct TlsConfig {
309 cert: String,
311 key: String,
313}
314
315impl TlsConfig {
316 pub fn cert(&self) -> &str {
317 &self.cert
318 }
319
320 pub fn key(&self) -> &str {
321 &self.key
322 }
323}
324
325#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
327#[serde(rename_all = "kebab-case")]
328pub struct GrpcApiConfig {
329 #[serde(default = "default_grpc_api_address")]
331 pub address: SocketAddr,
332
333 #[serde(skip_serializing_if = "Option::is_none")]
337 pub tls: Option<TlsConfig>,
338
339 #[serde(default = "default_grpc_api_max_message_size_bytes")]
341 pub max_message_size_bytes: u32,
342
343 #[serde(default = "default_grpc_api_broadcast_buffer_size")]
345 pub broadcast_buffer_size: u32,
346
347 #[serde(default = "default_grpc_api_max_concurrent_stream_subscribers")]
353 pub max_concurrent_stream_subscribers: u32,
354
355 #[serde(default = "default_grpc_api_max_json_move_value_size")]
358 pub max_json_move_value_size: usize,
359
360 #[serde(default = "default_grpc_api_max_execute_transaction_batch_size")]
363 pub max_execute_transaction_batch_size: u32,
364
365 #[serde(default = "default_grpc_api_max_simulate_transaction_batch_size")]
368 pub max_simulate_transaction_batch_size: u32,
369
370 #[serde(default = "default_grpc_api_max_get_objects_batch_size")]
372 pub max_get_objects_batch_size: u32,
373
374 #[serde(default = "default_grpc_api_max_get_transactions_batch_size")]
377 pub max_get_transactions_batch_size: u32,
378
379 #[serde(default = "default_grpc_api_max_view_function_call_batch_size")]
382 pub max_view_function_call_batch_size: u32,
383
384 #[serde(default = "default_grpc_api_max_checkpoint_inclusion_timeout_ms")]
388 pub max_checkpoint_inclusion_timeout_ms: u64,
389}
390
391fn default_grpc_api_address() -> SocketAddr {
392 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 50051)
393}
394
395fn default_grpc_api_broadcast_buffer_size() -> u32 {
396 100
397}
398
399fn default_grpc_api_max_concurrent_stream_subscribers() -> u32 {
400 1024
401}
402
403fn default_grpc_api_max_message_size_bytes() -> u32 {
404 128 * 1024 * 1024 }
406
407fn default_grpc_api_max_json_move_value_size() -> usize {
408 1024 * 1024 }
410
411fn default_grpc_api_max_execute_transaction_batch_size() -> u32 {
412 20
413}
414
415fn default_grpc_api_max_simulate_transaction_batch_size() -> u32 {
416 20
417}
418
419fn default_grpc_api_max_get_objects_batch_size() -> u32 {
420 1000
421}
422
423fn default_grpc_api_max_get_transactions_batch_size() -> u32 {
424 1000
425}
426
427fn default_grpc_api_max_view_function_call_batch_size() -> u32 {
428 20
429}
430
431fn default_grpc_api_max_checkpoint_inclusion_timeout_ms() -> u64 {
432 60_000 }
434
435impl Default for GrpcApiConfig {
436 fn default() -> Self {
437 Self {
438 address: default_grpc_api_address(),
439 tls: None,
440 max_message_size_bytes: default_grpc_api_max_message_size_bytes(),
441 broadcast_buffer_size: default_grpc_api_broadcast_buffer_size(),
442 max_concurrent_stream_subscribers: default_grpc_api_max_concurrent_stream_subscribers(),
443 max_json_move_value_size: default_grpc_api_max_json_move_value_size(),
444 max_execute_transaction_batch_size: default_grpc_api_max_execute_transaction_batch_size(
445 ),
446 max_simulate_transaction_batch_size:
447 default_grpc_api_max_simulate_transaction_batch_size(),
448 max_get_objects_batch_size: default_grpc_api_max_get_objects_batch_size(),
449 max_get_transactions_batch_size: default_grpc_api_max_get_transactions_batch_size(),
450 max_view_function_call_batch_size: default_grpc_api_max_view_function_call_batch_size(),
451 max_checkpoint_inclusion_timeout_ms:
452 default_grpc_api_max_checkpoint_inclusion_timeout_ms(),
453 }
454 }
455}
456
457impl GrpcApiConfig {
458 const GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE: u32 = 4 * 1024 * 1024; const GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES: u32 =
462 Self::GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE;
463
464 pub fn tls_config(&self) -> Option<&TlsConfig> {
465 self.tls.as_ref()
466 }
467
468 pub fn max_message_size_bytes(&self) -> u32 {
469 self.max_message_size_bytes
471 .max(Self::GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES)
472 }
473
474 pub fn max_message_size_client_bytes(&self, client_max_message_size_bytes: Option<u32>) -> u32 {
478 client_max_message_size_bytes
479 .unwrap_or(Self::GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE)
482 .clamp(
484 Self::GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES,
485 self.max_message_size_bytes(),
486 )
487 }
488}
489
490#[derive(Clone, Debug, Default, Deserialize, Serialize)]
491#[serde(rename_all = "kebab-case")]
492pub struct ExecutionCacheConfig {
493 #[serde(default)]
494 pub writeback_cache: WritebackCacheConfig,
495}
496
497#[derive(Clone, Debug, Default, Deserialize, Serialize)]
498#[serde(rename_all = "kebab-case")]
499pub struct WritebackCacheConfig {
500 #[serde(default, skip_serializing_if = "Option::is_none")]
503 pub max_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
506 pub package_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
509 pub object_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
511 pub marker_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
513 pub object_by_id_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
516 pub transaction_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
518 pub executed_effect_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
520 pub effect_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
523 pub events_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
526 pub transaction_objects_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
531 pub backpressure_threshold: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
537 pub backpressure_threshold_for_rpc: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
547 pub backpressure_soft_limit_pct: Option<u32>,
548}
549
550impl WritebackCacheConfig {
551 pub fn max_cache_size(&self) -> u64 {
552 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_MAX")
553 .ok()
554 .and_then(|s| s.parse().ok())
555 .or(self.max_cache_size)
556 .unwrap_or(100000)
557 }
558
559 pub fn package_cache_size(&self) -> u64 {
560 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_PACKAGE")
561 .ok()
562 .and_then(|s| s.parse().ok())
563 .or(self.package_cache_size)
564 .unwrap_or(1000)
565 }
566
567 pub fn object_cache_size(&self) -> u64 {
568 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_OBJECT")
569 .ok()
570 .and_then(|s| s.parse().ok())
571 .or(self.object_cache_size)
572 .unwrap_or_else(|| self.max_cache_size())
573 }
574
575 pub fn marker_cache_size(&self) -> u64 {
576 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_MARKER")
577 .ok()
578 .and_then(|s| s.parse().ok())
579 .or(self.marker_cache_size)
580 .unwrap_or_else(|| self.object_cache_size())
581 }
582
583 pub fn object_by_id_cache_size(&self) -> u64 {
584 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_OBJECT_BY_ID")
585 .ok()
586 .and_then(|s| s.parse().ok())
587 .or(self.object_by_id_cache_size)
588 .unwrap_or_else(|| self.object_cache_size())
589 }
590
591 pub fn transaction_cache_size(&self) -> u64 {
592 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_TRANSACTION")
593 .ok()
594 .and_then(|s| s.parse().ok())
595 .or(self.transaction_cache_size)
596 .unwrap_or_else(|| self.max_cache_size())
597 }
598
599 pub fn executed_effect_cache_size(&self) -> u64 {
600 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EXECUTED_EFFECT")
601 .ok()
602 .and_then(|s| s.parse().ok())
603 .or(self.executed_effect_cache_size)
604 .unwrap_or_else(|| self.transaction_cache_size())
605 }
606
607 pub fn effect_cache_size(&self) -> u64 {
608 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EFFECT")
609 .ok()
610 .and_then(|s| s.parse().ok())
611 .or(self.effect_cache_size)
612 .unwrap_or_else(|| self.executed_effect_cache_size())
613 }
614
615 pub fn events_cache_size(&self) -> u64 {
616 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EVENTS")
617 .ok()
618 .and_then(|s| s.parse().ok())
619 .or(self.events_cache_size)
620 .unwrap_or_else(|| self.transaction_cache_size())
621 }
622
623 pub fn transaction_objects_cache_size(&self) -> u64 {
624 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_TRANSACTION_OBJECTS")
625 .ok()
626 .and_then(|s| s.parse().ok())
627 .or(self.transaction_objects_cache_size)
628 .unwrap_or(1000)
629 }
630
631 pub fn backpressure_threshold(&self) -> u64 {
632 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_THRESHOLD")
633 .ok()
634 .and_then(|s| s.parse().ok())
635 .or(self.backpressure_threshold)
636 .unwrap_or(100_000)
637 }
638
639 pub fn backpressure_threshold_for_rpc(&self) -> u64 {
640 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_THRESHOLD_FOR_RPC")
641 .ok()
642 .and_then(|s| s.parse().ok())
643 .or(self.backpressure_threshold_for_rpc)
644 .unwrap_or(self.backpressure_threshold())
645 }
646
647 pub fn backpressure_soft_limit_pct(&self) -> u32 {
648 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_SOFT_LIMIT_PCT")
649 .ok()
650 .and_then(|s| s.parse().ok())
651 .or(self.backpressure_soft_limit_pct)
652 .unwrap_or(50)
653 .min(100)
654 }
655}
656
657#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
658#[serde(rename_all = "lowercase")]
659pub enum ServerType {
660 WebSocket,
661 Http,
662 Both,
663}
664
665#[derive(Clone, Debug, Deserialize, Serialize)]
666#[serde(rename_all = "kebab-case")]
667pub struct TransactionKeyValueStoreReadConfig {
668 #[serde(default = "default_base_url")]
669 pub base_url: String,
670
671 #[serde(default = "default_cache_size")]
672 pub cache_size: u64,
673}
674
675impl Default for TransactionKeyValueStoreReadConfig {
676 fn default() -> Self {
677 Self {
678 base_url: default_base_url(),
679 cache_size: default_cache_size(),
680 }
681 }
682}
683
684fn default_base_url() -> String {
685 "".to_string()
686}
687
688fn default_cache_size() -> u64 {
689 100_000
690}
691
692fn default_transaction_kv_store_config() -> TransactionKeyValueStoreReadConfig {
693 TransactionKeyValueStoreReadConfig::default()
694}
695
696fn default_authority_store_pruning_config() -> AuthorityStorePruningConfig {
697 AuthorityStorePruningConfig::default()
698}
699
700pub fn default_enable_index_processing() -> bool {
701 true
702}
703
704fn default_grpc_address() -> Multiaddr {
705 "/ip4/0.0.0.0/tcp/8080".parse().unwrap()
706}
707fn default_authority_key_pair() -> AuthorityKeyPairWithPath {
708 AuthorityKeyPairWithPath::new(get_key_pair_from_rng::<AuthorityKeyPair, _>(&mut OsRng).1)
709}
710
711fn default_key_pair() -> KeyPairWithPath {
712 KeyPairWithPath::new(AccountPrivateKey::random().into())
713}
714
715fn default_metrics_address() -> SocketAddr {
716 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9184)
717}
718
719pub fn default_admin_interface_address() -> SocketAddr {
720 SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 1337)
721}
722
723pub fn default_json_rpc_address() -> SocketAddr {
724 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9000)
725}
726
727pub fn default_grpc_api_config() -> Option<GrpcApiConfig> {
728 Some(GrpcApiConfig::default())
729}
730
731fn is_default_grpc_api_config(grpc_api_config: &Option<GrpcApiConfig>) -> bool {
732 serializes_like(grpc_api_config, &default_grpc_api_config())
733}
734
735fn serializes_like<T: Serialize>(value: &T, default: &T) -> bool {
741 match (serde_yaml::to_string(value), serde_yaml::to_string(default)) {
742 (Ok(value), Ok(default)) => value == default,
743 _ => false,
744 }
745}
746
747pub fn default_grpc_concurrency_limit_per_core() -> NonZeroUsize {
748 NonZeroUsize::new(1000).unwrap()
749}
750
751pub fn default_end_of_epoch_broadcast_channel_capacity() -> usize {
752 128
753}
754
755pub fn default_full_checkpoint_contents_cache_size_mb() -> usize {
756 DEFAULT_FULL_CHECKPOINT_CONTENTS_CACHE_SIZE_MB
757}
758
759pub fn bool_true() -> bool {
760 true
761}
762
763impl Config for NodeConfig {}
764
765impl NodeConfig {
766 pub fn authority_key_pair(&self) -> &AuthorityKeyPair {
767 self.authority_key_pair.authority_keypair()
768 }
769
770 pub fn protocol_key_pair(&self) -> &NetworkKeyPair {
771 self.protocol_key_pair.ed25519_keypair()
772 }
773
774 pub fn network_key_pair(&self) -> &NetworkKeyPair {
775 self.network_key_pair.ed25519_keypair()
776 }
777
778 pub fn authority_public_key(&self) -> AuthorityPublicKeyBytes {
779 self.authority_key_pair().public().into()
780 }
781
782 pub fn db_path(&self) -> PathBuf {
783 self.db_path.join("live")
784 }
785
786 pub fn db_checkpoint_path(&self) -> PathBuf {
787 self.db_path.join("db_checkpoints")
788 }
789
790 pub fn snapshot_path(&self) -> PathBuf {
791 self.db_path.join("snapshot")
792 }
793
794 pub fn network_address(&self) -> &Multiaddr {
795 &self.network_address
796 }
797
798 pub fn consensus_config(&self) -> Option<&ConsensusConfig> {
799 self.consensus_config.as_ref()
800 }
801
802 pub fn genesis(&self) -> Result<&genesis::Genesis> {
803 self.genesis.genesis()
804 }
805
806 pub fn load_migration_tx_data(&self) -> Result<MigrationTxData> {
807 let Some(location) = &self.migration_tx_data_path else {
808 anyhow::bail!("no file location set");
809 };
810
811 let migration_tx_data = MigrationTxData::load(location)?;
813
814 migration_tx_data.validate_from_genesis(self.genesis.genesis()?)?;
816 Ok(migration_tx_data)
817 }
818
819 pub fn iota_address(&self) -> Address {
820 self.account_key_pair
821 .keypair()
822 .public_key()
823 .derive_address()
824 }
825
826 pub fn checkpoint_archive_config(&self) -> Option<&CheckpointArchiveConfig> {
827 self.checkpoint_archive_config.as_ref()
828 }
829
830 pub fn jsonrpc_server_type(&self) -> ServerType {
831 self.jsonrpc_server_type.unwrap_or(ServerType::Http)
832 }
833
834 pub fn is_validator(&self) -> bool {
837 self.consensus_config.is_some()
838 }
839
840 pub fn validate(&self) -> Result<()> {
844 if self.is_validator() {
847 if self.enable_grpc_api {
848 anyhow::bail!(
849 "`enable-grpc-api` is set, but validators do not expose the gRPC API; turn \
850 it off, or move the API to a fullnode"
851 );
852 }
853 if self
854 .state_snapshot_write_config
855 .object_store_config
856 .is_some()
857 {
858 anyhow::bail!(
859 "`state-snapshot-write-config.object-store-config` is set, but snapshot \
860 upload is only supported on fullnodes; remove the setting or move the \
861 upload to a fullnode"
862 );
863 }
864 }
865 if self.enable_grpc_api && self.grpc_api_config.is_none() {
869 anyhow::bail!(
870 "`enable-grpc-api` is set but `grpc-api-config` is `null`; give it a value, \
871 remove the key to take the default config, or turn off `enable-grpc-api`"
872 );
873 }
874 if self
876 .state_snapshot_write_config
877 .object_store_config
878 .as_ref()
879 .is_some_and(|store| store.object_store.is_none())
880 {
881 anyhow::bail!(
882 "`state-snapshot-write-config.object-store-config` has no `object-store`; \
883 snapshot upload needs a storage backend"
884 );
885 }
886 if self.firewall_config.is_some() && self.policy_config.is_none() {
891 anyhow::bail!(
892 "`firewall-config` is set but `policy-config` is `null`; the firewall is driven \
893 by the traffic controller, which does not run without a policy; remove \
894 `firewall-config` or set a `policy-config`"
895 );
896 }
897 Ok(())
898 }
899}
900
901#[derive(Debug, Clone, Deserialize, Serialize)]
902#[serde(rename_all = "kebab-case")]
903pub struct ConsensusConfig {
904 pub db_path: PathBuf,
906
907 pub db_retention_epochs: Option<u64>,
911
912 pub db_pruner_period_secs: Option<u64>,
916
917 pub max_pending_transactions: Option<usize>,
928
929 pub max_submit_position: Option<usize>,
935
936 pub submit_delay_step_override_millis: Option<u64>,
942
943 #[serde(skip_serializing_if = "Option::is_none", alias = "starfish_parameters")]
945 pub parameters: Option<StarfishParameters>,
946
947 #[serde(skip_serializing_if = "Option::is_none")]
953 pub graduated_load_shedding_soft_limit_pct: Option<u32>,
954}
955
956impl ConsensusConfig {
957 pub fn db_path(&self) -> &Path {
958 &self.db_path
959 }
960
961 pub fn max_pending_transactions(&self) -> usize {
965 self.max_pending_transactions.unwrap_or(20_000)
966 }
967
968 pub fn graduated_load_shedding_soft_limit_pct(&self) -> u32 {
973 self.graduated_load_shedding_soft_limit_pct
974 .unwrap_or(50)
975 .min(100)
976 }
977
978 pub fn submit_delay_step_override(&self) -> Option<Duration> {
979 self.submit_delay_step_override_millis
980 .map(Duration::from_millis)
981 }
982
983 pub fn db_retention_epochs(&self) -> u64 {
984 self.db_retention_epochs.unwrap_or(0)
985 }
986
987 pub fn db_pruner_period(&self) -> Duration {
988 self.db_pruner_period_secs
990 .map(Duration::from_secs)
991 .unwrap_or(Duration::from_secs(3_600))
992 }
993}
994
995#[derive(Clone, Debug, Deserialize, Serialize)]
996#[serde(rename_all = "kebab-case")]
997pub struct CheckpointExecutorConfig {
998 #[serde(default = "default_checkpoint_execution_max_concurrency")]
1003 pub checkpoint_execution_max_concurrency: usize,
1004
1005 #[serde(default = "default_local_execution_timeout_sec")]
1011 pub local_execution_timeout_sec: u64,
1012
1013 #[serde(default, skip_serializing_if = "Option::is_none")]
1018 pub data_ingestion_dir: Option<PathBuf>,
1019}
1020
1021#[derive(Clone, Debug, Default, Deserialize, Serialize)]
1022#[serde(rename_all = "kebab-case")]
1023pub struct ExpensiveSafetyCheckConfig {
1024 #[serde(default)]
1029 enable_epoch_iota_conservation_check: bool,
1030
1031 #[serde(default)]
1035 enable_deep_per_tx_iota_conservation_check: bool,
1036
1037 #[serde(default)]
1040 force_disable_epoch_iota_conservation_check: bool,
1041
1042 #[serde(default)]
1045 enable_state_consistency_check: bool,
1046
1047 #[serde(default)]
1049 force_disable_state_consistency_check: bool,
1050
1051 #[serde(default)]
1052 enable_secondary_index_checks: bool,
1053 }
1055
1056impl ExpensiveSafetyCheckConfig {
1057 pub fn new_enable_all() -> Self {
1058 Self {
1059 enable_epoch_iota_conservation_check: true,
1060 enable_deep_per_tx_iota_conservation_check: true,
1061 force_disable_epoch_iota_conservation_check: false,
1062 enable_state_consistency_check: true,
1063 force_disable_state_consistency_check: false,
1064 enable_secondary_index_checks: false, }
1066 }
1067
1068 pub fn new_disable_all() -> Self {
1069 Self {
1070 enable_epoch_iota_conservation_check: false,
1071 enable_deep_per_tx_iota_conservation_check: false,
1072 force_disable_epoch_iota_conservation_check: true,
1073 enable_state_consistency_check: false,
1074 force_disable_state_consistency_check: true,
1075 enable_secondary_index_checks: false,
1076 }
1077 }
1078
1079 pub fn force_disable_epoch_iota_conservation_check(&mut self) {
1080 self.force_disable_epoch_iota_conservation_check = true;
1081 }
1082
1083 pub fn enable_epoch_iota_conservation_check(&self) -> bool {
1084 (self.enable_epoch_iota_conservation_check || cfg!(debug_assertions))
1085 && !self.force_disable_epoch_iota_conservation_check
1086 }
1087
1088 pub fn force_disable_state_consistency_check(&mut self) {
1089 self.force_disable_state_consistency_check = true;
1090 }
1091
1092 pub fn enable_state_consistency_check(&self) -> bool {
1093 (self.enable_state_consistency_check || cfg!(debug_assertions))
1094 && !self.force_disable_state_consistency_check
1095 }
1096
1097 pub fn enable_deep_per_tx_iota_conservation_check(&self) -> bool {
1098 self.enable_deep_per_tx_iota_conservation_check || cfg!(debug_assertions)
1099 }
1100
1101 pub fn enable_secondary_index_checks(&self) -> bool {
1102 self.enable_secondary_index_checks
1103 }
1104}
1105
1106fn default_checkpoint_execution_max_concurrency() -> usize {
1107 4
1108}
1109
1110fn default_local_execution_timeout_sec() -> u64 {
1111 30
1112}
1113
1114impl Default for CheckpointExecutorConfig {
1115 fn default() -> Self {
1116 Self {
1117 checkpoint_execution_max_concurrency: default_checkpoint_execution_max_concurrency(),
1118 local_execution_timeout_sec: default_local_execution_timeout_sec(),
1119 data_ingestion_dir: None,
1120 }
1121 }
1122}
1123
1124#[derive(Debug, Clone, Deserialize, Serialize)]
1125#[serde(rename_all = "kebab-case")]
1126pub struct AuthorityStorePruningConfig {
1127 #[serde(default = "default_num_latest_epoch_dbs_to_retain")]
1129 pub num_latest_epoch_dbs_to_retain: usize,
1130 #[serde(default)]
1135 pub num_epochs_to_retain: u64,
1136 #[serde(
1145 default = "default_periodic_compaction_threshold_days",
1146 skip_serializing_if = "is_default_periodic_compaction_threshold_days"
1147 )]
1148 pub periodic_compaction_threshold_days: Option<usize>,
1149 #[serde(skip_serializing_if = "Option::is_none")]
1152 pub num_epochs_to_retain_for_checkpoints: Option<u64>,
1153 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1159 pub enable_compaction_filter: bool,
1160 #[serde(skip_serializing_if = "Option::is_none")]
1161 pub num_epochs_to_retain_for_indexes: Option<u64>,
1162}
1163
1164fn default_num_latest_epoch_dbs_to_retain() -> usize {
1165 3
1166}
1167
1168fn default_periodic_compaction_threshold_days() -> Option<usize> {
1169 Some(1)
1170}
1171
1172fn is_default_periodic_compaction_threshold_days(days: &Option<usize>) -> bool {
1173 *days == default_periodic_compaction_threshold_days()
1174}
1175
1176impl Default for AuthorityStorePruningConfig {
1177 fn default() -> Self {
1178 Self {
1179 num_latest_epoch_dbs_to_retain: default_num_latest_epoch_dbs_to_retain(),
1180 num_epochs_to_retain: 0,
1181 periodic_compaction_threshold_days: default_periodic_compaction_threshold_days(),
1182 num_epochs_to_retain_for_checkpoints: if cfg!(msim) { Some(2) } else { None },
1183 enable_compaction_filter: cfg!(test) || cfg!(msim),
1184 num_epochs_to_retain_for_indexes: None,
1185 }
1186 }
1187}
1188
1189impl AuthorityStorePruningConfig {
1190 pub fn set_num_epochs_to_retain(&mut self, num_epochs_to_retain: u64) {
1191 self.num_epochs_to_retain = num_epochs_to_retain;
1192 }
1193
1194 pub fn set_num_epochs_to_retain_for_checkpoints(&mut self, num_epochs_to_retain: Option<u64>) {
1195 self.num_epochs_to_retain_for_checkpoints = num_epochs_to_retain;
1196 }
1197
1198 pub fn num_epochs_to_retain_for_checkpoints(&self) -> Option<u64> {
1199 self.num_epochs_to_retain_for_checkpoints
1200 .map(|n| {
1202 if n < 2 {
1203 info!("num_epochs_to_retain_for_checkpoints must be at least 2, rounding up from {}", n);
1204 2
1205 } else {
1206 n
1207 }
1208 })
1209 }
1210}
1211
1212#[derive(Debug, Clone, Deserialize, Serialize)]
1213#[serde(rename_all = "kebab-case")]
1214pub struct MetricsConfig {
1215 #[serde(skip_serializing_if = "Option::is_none")]
1216 pub push_interval_seconds: Option<u64>,
1217 #[serde(skip_serializing_if = "Option::is_none")]
1218 pub push_url: Option<String>,
1219 #[serde(skip_serializing_if = "Option::is_none")]
1220 pub groups: Option<MetricGroups>,
1221}
1222
1223fn default_checkpoint_archive_download_concurrency() -> NonZeroUsize {
1224 NonZeroUsize::new(10).unwrap()
1225}
1226
1227fn default_checkpoint_archive_verify_concurrency() -> NonZeroUsize {
1228 std::thread::available_parallelism().unwrap_or(NonZeroUsize::new(4).unwrap())
1229}
1230
1231#[derive(Debug, Clone, Deserialize, Serialize)]
1234#[serde(rename_all = "kebab-case")]
1235pub struct CheckpointArchiveConfig {
1236 pub url: String,
1238 #[serde(default = "default_checkpoint_archive_download_concurrency")]
1240 pub download_concurrency: NonZeroUsize,
1241 #[serde(default = "default_checkpoint_archive_verify_concurrency")]
1244 pub verify_concurrency: NonZeroUsize,
1245}
1246
1247#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1255#[serde(rename_all = "kebab-case")]
1256pub struct StateSnapshotConfig {
1257 #[serde(skip_serializing_if = "Option::is_none")]
1258 pub object_store_config: Option<ObjectStoreConfig>,
1259 pub concurrency: usize,
1260}
1261
1262#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1263#[serde(rename_all = "kebab-case")]
1264pub struct TransactionKeyValueStoreWriteConfig {
1265 pub aws_access_key_id: String,
1266 pub aws_secret_access_key: String,
1267 pub aws_region: String,
1268 pub table_name: String,
1269 pub bucket_name: String,
1270 pub concurrency: usize,
1271}
1272
1273#[derive(Clone, Debug, Deserialize, Serialize)]
1278#[serde(rename_all = "kebab-case")]
1279pub struct AuthorityOverloadConfig {
1280 #[serde(default = "default_max_txn_age_in_queue")]
1284 pub max_txn_age_in_queue: Duration,
1285
1286 #[serde(default = "default_overload_monitor_interval")]
1288 pub overload_monitor_interval: Duration,
1289
1290 #[serde(default = "default_execution_queue_latency_soft_limit")]
1292 pub execution_queue_latency_soft_limit: Duration,
1293
1294 #[serde(default = "default_execution_queue_latency_hard_limit")]
1297 pub execution_queue_latency_hard_limit: Duration,
1298
1299 #[serde(default = "default_max_load_shedding_percentage")]
1301 pub max_load_shedding_percentage: u32,
1302
1303 #[serde(default = "default_min_load_shedding_percentage_above_hard_limit")]
1306 pub min_load_shedding_percentage_above_hard_limit: u32,
1307
1308 #[serde(default = "default_safe_transaction_ready_rate")]
1311 pub safe_transaction_ready_rate: u32,
1312
1313 #[serde(default = "default_check_system_overload_at_signing")]
1316 pub check_system_overload_at_signing: bool,
1317
1318 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1321 pub check_system_overload_at_execution: bool,
1322
1323 #[serde(default = "default_max_transaction_manager_queue_length")]
1327 pub max_transaction_manager_queue_length: usize,
1328
1329 #[serde(default = "default_max_transaction_manager_per_object_queue_length")]
1332 pub max_transaction_manager_per_object_queue_length: usize,
1333
1334 #[serde(default = "default_max_transaction_manager_queue_length_soft_limit_pct")]
1338 pub max_transaction_manager_queue_length_soft_limit_pct: u32,
1339}
1340
1341impl AuthorityOverloadConfig {
1342 pub fn max_transaction_manager_queue_length_soft_limit_pct(&self) -> u32 {
1345 self.max_transaction_manager_queue_length_soft_limit_pct
1346 .min(100)
1347 }
1348}
1349
1350fn default_max_txn_age_in_queue() -> Duration {
1351 Duration::from_millis(500)
1352}
1353
1354fn default_overload_monitor_interval() -> Duration {
1355 Duration::from_secs(10)
1356}
1357
1358fn default_execution_queue_latency_soft_limit() -> Duration {
1359 Duration::from_secs(1)
1360}
1361
1362fn default_execution_queue_latency_hard_limit() -> Duration {
1363 Duration::from_secs(10)
1364}
1365
1366fn default_max_load_shedding_percentage() -> u32 {
1367 95
1368}
1369
1370fn default_min_load_shedding_percentage_above_hard_limit() -> u32 {
1371 50
1372}
1373
1374fn default_safe_transaction_ready_rate() -> u32 {
1375 100
1376}
1377
1378fn default_check_system_overload_at_signing() -> bool {
1379 true
1380}
1381
1382fn default_max_transaction_manager_queue_length() -> usize {
1383 100_000
1384}
1385
1386fn default_max_transaction_manager_queue_length_soft_limit_pct() -> u32 {
1387 50
1388}
1389
1390fn default_max_transaction_manager_per_object_queue_length() -> usize {
1391 20
1392}
1393
1394impl Default for AuthorityOverloadConfig {
1395 fn default() -> Self {
1396 Self {
1397 max_txn_age_in_queue: default_max_txn_age_in_queue(),
1398 overload_monitor_interval: default_overload_monitor_interval(),
1399 execution_queue_latency_soft_limit: default_execution_queue_latency_soft_limit(),
1400 execution_queue_latency_hard_limit: default_execution_queue_latency_hard_limit(),
1401 max_load_shedding_percentage: default_max_load_shedding_percentage(),
1402 min_load_shedding_percentage_above_hard_limit:
1403 default_min_load_shedding_percentage_above_hard_limit(),
1404 safe_transaction_ready_rate: default_safe_transaction_ready_rate(),
1405 check_system_overload_at_signing: true,
1406 check_system_overload_at_execution: false,
1407 max_transaction_manager_queue_length: default_max_transaction_manager_queue_length(),
1408 max_transaction_manager_queue_length_soft_limit_pct:
1409 default_max_transaction_manager_queue_length_soft_limit_pct(),
1410 max_transaction_manager_per_object_queue_length:
1411 default_max_transaction_manager_per_object_queue_length(),
1412 }
1413 }
1414}
1415
1416fn default_authority_overload_config() -> AuthorityOverloadConfig {
1417 AuthorityOverloadConfig::default()
1418}
1419
1420fn default_traffic_controller_policy_config() -> Option<PolicyConfig> {
1421 Some(PolicyConfig::default_dos_protection_policy())
1422}
1423
1424fn is_default_traffic_controller_policy_config(policy_config: &Option<PolicyConfig>) -> bool {
1425 serializes_like(policy_config, &default_traffic_controller_policy_config())
1426}
1427
1428#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1429pub struct Genesis {
1430 #[serde(flatten)]
1431 location: Option<GenesisLocation>,
1432
1433 #[serde(skip)]
1434 genesis: once_cell::sync::OnceCell<genesis::Genesis>,
1435}
1436
1437impl Genesis {
1438 pub fn new(genesis: genesis::Genesis) -> Self {
1439 Self {
1440 location: Some(GenesisLocation::InPlace {
1441 genesis: Box::new(genesis),
1442 }),
1443 genesis: Default::default(),
1444 }
1445 }
1446
1447 pub fn new_from_file<P: Into<PathBuf>>(path: P) -> Self {
1448 Self {
1449 location: Some(GenesisLocation::File {
1450 genesis_file_location: path.into(),
1451 }),
1452 genesis: Default::default(),
1453 }
1454 }
1455
1456 pub fn new_empty() -> Self {
1457 Self {
1458 location: None,
1459 genesis: Default::default(),
1460 }
1461 }
1462
1463 pub fn genesis(&self) -> Result<&genesis::Genesis> {
1464 match &self.location {
1465 Some(GenesisLocation::InPlace { genesis }) => Ok(genesis),
1466 Some(GenesisLocation::File {
1467 genesis_file_location,
1468 }) => self
1469 .genesis
1470 .get_or_try_init(|| genesis::Genesis::load(genesis_file_location)),
1471 None => anyhow::bail!("no genesis location set"),
1472 }
1473 }
1474}
1475
1476#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1477#[serde(untagged)]
1478enum GenesisLocation {
1479 InPlace {
1480 genesis: Box<genesis::Genesis>,
1481 },
1482 File {
1483 #[serde(rename = "genesis-file-location")]
1484 genesis_file_location: PathBuf,
1485 },
1486}
1487
1488#[derive(Clone, Debug, Deserialize, Serialize)]
1491pub struct KeyPairWithPath {
1492 #[serde(flatten)]
1493 location: KeyPairLocation,
1494
1495 #[serde(skip)]
1496 keypair: OnceCell<Arc<SimpleKeypair>>,
1497
1498 #[serde(skip)]
1504 ed25519_keypair: OnceCell<Arc<Ed25519KeyPair>>,
1505}
1506
1507impl PartialEq for KeyPairWithPath {
1508 fn eq(&self, other: &Self) -> bool {
1509 self.location == other.location
1510 }
1511}
1512
1513impl Eq for KeyPairWithPath {}
1514
1515#[derive(Debug, Clone, Deserialize, Serialize)]
1516#[serde(untagged)]
1517enum KeyPairLocation {
1518 InPlace {
1519 #[serde(with = "bech32_formatted_keypair")]
1520 value: Arc<SimpleKeypair>,
1521 },
1522 File {
1523 path: PathBuf,
1524 },
1525}
1526
1527impl PartialEq for KeyPairLocation {
1528 fn eq(&self, other: &Self) -> bool {
1529 match (self, other) {
1530 (Self::InPlace { value: a }, Self::InPlace { value: b }) => {
1531 a.to_bytes() == b.to_bytes()
1532 }
1533 (Self::File { path: a }, Self::File { path: b }) => a == b,
1534 _ => false,
1535 }
1536 }
1537}
1538
1539impl Eq for KeyPairLocation {}
1540
1541impl KeyPairWithPath {
1542 pub fn new(kp: SimpleKeypair) -> Self {
1543 let cell: OnceCell<Arc<SimpleKeypair>> = OnceCell::new();
1544 let arc_kp = Arc::new(kp);
1545 cell.set(arc_kp.clone()).expect("failed to set keypair");
1548 Self {
1549 location: KeyPairLocation::InPlace { value: arc_kp },
1550 keypair: cell,
1551 ed25519_keypair: OnceCell::new(),
1552 }
1553 }
1554
1555 pub fn new_from_path(path: PathBuf) -> Self {
1556 let cell: OnceCell<Arc<SimpleKeypair>> = OnceCell::new();
1557 cell.set(Arc::new(read_keypair_from_file(&path).unwrap_or_else(
1560 |e| panic!("invalid keypair file at path {path:?}: {e}"),
1561 )))
1562 .expect("failed to set keypair");
1563 Self {
1564 location: KeyPairLocation::File { path },
1565 keypair: cell,
1566 ed25519_keypair: OnceCell::new(),
1567 }
1568 }
1569
1570 pub fn keypair(&self) -> &SimpleKeypair {
1571 self.keypair
1572 .get_or_init(|| match &self.location {
1573 KeyPairLocation::InPlace { value } => value.clone(),
1574 KeyPairLocation::File { path } => {
1575 Arc::new(
1578 read_keypair_from_file(path).unwrap_or_else(|e| {
1579 panic!("invalid keypair file at path {path:?}: {e}")
1580 }),
1581 )
1582 }
1583 })
1584 .as_ref()
1585 }
1586
1587 pub fn ed25519_keypair(&self) -> &Ed25519KeyPair {
1591 self.ed25519_keypair
1592 .get_or_init(|| {
1593 Arc::new(
1594 simple_to_network_keypair(self.keypair())
1595 .expect("only Ed25519 network keys are allowed"),
1596 )
1597 })
1598 .as_ref()
1599 }
1600}
1601
1602#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
1605pub struct AuthorityKeyPairWithPath {
1606 #[serde(flatten)]
1607 location: AuthorityKeyPairLocation,
1608
1609 #[serde(skip)]
1610 keypair: OnceCell<Arc<AuthorityKeyPair>>,
1611}
1612
1613#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1614#[serde(untagged)]
1615enum AuthorityKeyPairLocation {
1616 InPlace { value: Arc<AuthorityKeyPair> },
1617 File { path: PathBuf },
1618}
1619
1620impl AuthorityKeyPairWithPath {
1621 pub fn new(kp: AuthorityKeyPair) -> Self {
1622 let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1623 let arc_kp = Arc::new(kp);
1624 cell.set(arc_kp.clone())
1627 .expect("failed to set authority keypair");
1628 Self {
1629 location: AuthorityKeyPairLocation::InPlace { value: arc_kp },
1630 keypair: cell,
1631 }
1632 }
1633
1634 pub fn new_from_path(path: PathBuf) -> Self {
1635 let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1636 cell.set(Arc::new(
1639 read_authority_keypair_from_file(&path)
1640 .unwrap_or_else(|_| panic!("invalid authority keypair file at path {path:?}")),
1641 ))
1642 .expect("failed to set authority keypair");
1643 Self {
1644 location: AuthorityKeyPairLocation::File { path },
1645 keypair: cell,
1646 }
1647 }
1648
1649 pub fn authority_keypair(&self) -> &AuthorityKeyPair {
1650 self.keypair
1651 .get_or_init(|| match &self.location {
1652 AuthorityKeyPairLocation::InPlace { value } => value.clone(),
1653 AuthorityKeyPairLocation::File { path } => {
1654 Arc::new(
1657 read_authority_keypair_from_file(path)
1658 .unwrap_or_else(|_| panic!("invalid authority keypair file {path:?}")),
1659 )
1660 }
1661 })
1662 .as_ref()
1663 }
1664}
1665
1666#[derive(Clone, Debug, Deserialize, Serialize, Default)]
1669#[serde(rename_all = "kebab-case")]
1670pub struct StateDebugDumpConfig {
1671 #[serde(skip_serializing_if = "Option::is_none")]
1672 pub dump_file_directory: Option<PathBuf>,
1673}
1674
1675#[cfg(test)]
1676mod tests {
1677 use std::path::PathBuf;
1678
1679 use fastcrypto::traits::KeyPair;
1680 use iota_keys::keypair_file::{write_authority_keypair_to_file, write_keypair_to_file};
1681 use iota_types::{
1682 crypto::{
1683 AuthorityKeyPair, NetworkKeyPair, get_key_pair_from_rng, network_to_simple_keypair,
1684 },
1685 traffic_control::{PolicyConfig, RemoteFirewallConfig},
1686 };
1687 use rand::{SeedableRng, rngs::StdRng};
1688 use serde::Serialize;
1689 use serde_yaml::Value;
1690
1691 use super::{
1692 Genesis, GrpcApiConfig, ObjectStoreConfig, default_grpc_api_config,
1693 default_periodic_compaction_threshold_days, default_traffic_controller_policy_config,
1694 };
1695 use crate::{NodeConfig, object_storage_config::ObjectStoreType};
1696
1697 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1698
1699 const POLICY_CONFIG: &[&str] = &["policy-config"];
1700 const GRPC_API_CONFIG: &[&str] = &["grpc-api-config"];
1701 const COMPACTION_THRESHOLD: &[&str] = &[
1702 "authority-store-pruning-config",
1703 "periodic-compaction-threshold-days",
1704 ];
1705
1706 fn template_config() -> NodeConfig {
1707 serde_yaml::from_str(TEMPLATE).unwrap()
1708 }
1709
1710 fn consensus_config() -> super::ConsensusConfig {
1711 serde_yaml::from_str("db-path: /opt/iota/consensus-db").unwrap()
1712 }
1713
1714 fn object_store_config() -> ObjectStoreConfig {
1715 ObjectStoreConfig {
1716 object_store: Some(ObjectStoreType::File),
1717 directory: Some(PathBuf::from("/opt/iota/snapshots")),
1718 ..Default::default()
1719 }
1720 }
1721
1722 fn round_trip(config: &NodeConfig) -> NodeConfig {
1723 serde_yaml::from_str(&serde_yaml::to_string(config).unwrap()).unwrap()
1724 }
1725
1726 fn as_yaml<T: Serialize>(value: &T) -> String {
1727 serde_yaml::to_string(value).unwrap()
1728 }
1729
1730 fn written_at(value: &Value, path: &[&str]) -> Option<Value> {
1733 let (last, parents) = path.split_last().unwrap();
1734 let mut current = value;
1735 for name in parents {
1736 current = current
1737 .as_mapping()
1738 .unwrap()
1739 .get(&Value::String((*name).to_owned()))
1740 .unwrap();
1741 }
1742 current
1743 .as_mapping()
1744 .unwrap()
1745 .get(&Value::String((*last).to_owned()))
1746 .cloned()
1747 }
1748
1749 #[test]
1750 fn serialize_genesis_from_file() {
1751 let g = Genesis::new_from_file("path/to/file");
1752
1753 let s = serde_yaml::to_string(&g).unwrap();
1754 assert_eq!("---\ngenesis-file-location: path/to/file\n", s);
1755 let loaded_genesis: Genesis = serde_yaml::from_str(&s).unwrap();
1756 assert_eq!(g, loaded_genesis);
1757 }
1758
1759 #[test]
1760 fn fullnode_template() {
1761 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1762
1763 let _template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1764 }
1765
1766 #[test]
1767 fn validate_requires_a_grpc_config_when_the_api_is_enabled() {
1768 let mut config = template_config();
1771 config.grpc_api_config = None;
1772 config.validate().unwrap();
1773
1774 config.enable_grpc_api = true;
1775 let err = config.validate().unwrap_err().to_string();
1776 assert!(err.contains("`grpc-api-config` is `null`"), "{err}");
1777
1778 config.grpc_api_config = Some(GrpcApiConfig::default());
1779 config.validate().unwrap();
1780
1781 config.grpc_api_config = None;
1784 config.consensus_config = Some(consensus_config());
1785 let err = config.validate().unwrap_err().to_string();
1786 assert!(err.contains("validators do not expose"), "{err}");
1787 }
1788
1789 #[test]
1790 fn validate_rejects_the_grpc_api_on_a_validator() {
1791 let mut config = template_config();
1792 config.consensus_config = Some(consensus_config());
1793 config.validate().unwrap();
1794
1795 config.enable_grpc_api = true;
1796 let err = config.validate().unwrap_err().to_string();
1797 assert!(err.contains("validators do not expose"), "{err}");
1798
1799 config.consensus_config = None;
1801 config.validate().unwrap();
1802 }
1803
1804 #[test]
1805 fn validate_rejects_snapshot_upload_on_a_validator() {
1806 let mut config = template_config();
1807 config.state_snapshot_write_config.object_store_config = Some(object_store_config());
1808 config.validate().unwrap();
1809
1810 config.consensus_config = Some(consensus_config());
1811 let err = config.validate().unwrap_err().to_string();
1812 assert!(err.contains("snapshot upload"), "{err}");
1813 }
1814
1815 #[test]
1816 fn validate_rejects_a_snapshot_store_without_a_backend() {
1817 let mut config = template_config();
1818 config.state_snapshot_write_config.object_store_config = Some(ObjectStoreConfig::default());
1819
1820 let err = config.validate().unwrap_err().to_string();
1821 assert!(err.contains("storage backend"), "{err}");
1822 }
1823
1824 #[test]
1825 fn validate_rejects_a_firewall_without_a_policy() {
1826 let mut config = template_config();
1827 config.firewall_config = Some(RemoteFirewallConfig {
1828 remote_fw_url: "http://localhost:65000".to_owned(),
1829 destination_port: 8080,
1830 delegate_spam_blocking: false,
1831 delegate_error_blocking: false,
1832 drain_path: PathBuf::from("/tmp/drain"),
1833 drain_timeout_secs: 300,
1834 });
1835
1836 config.validate().unwrap();
1839
1840 config.policy_config = None;
1843 let err = config.validate().unwrap_err().to_string();
1844 assert!(err.contains("`firewall-config` is set"), "{err}");
1845 }
1846
1847 #[test]
1848 fn enable_soft_locking_defaults_to_enabled() {
1849 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1852
1853 let config: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1854 assert!(config.enable_soft_locking);
1855 }
1856
1857 #[test]
1858 fn load_key_pairs_to_node_config() {
1859 let authority_key_pair: AuthorityKeyPair =
1860 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1861 let protocol_key_pair: NetworkKeyPair =
1862 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1863 let network_key_pair: NetworkKeyPair =
1864 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1865
1866 write_authority_keypair_to_file(&authority_key_pair, PathBuf::from("authority.key"))
1867 .unwrap();
1868 write_keypair_to_file(
1869 &network_to_simple_keypair(&protocol_key_pair),
1870 PathBuf::from("protocol.key"),
1871 )
1872 .unwrap();
1873 write_keypair_to_file(
1874 &network_to_simple_keypair(&network_key_pair),
1875 PathBuf::from("network.key"),
1876 )
1877 .unwrap();
1878
1879 const TEMPLATE: &str = include_str!("../data/fullnode-template-with-path.yaml");
1880 let template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1881 assert_eq!(
1882 template.authority_key_pair().public(),
1883 authority_key_pair.public()
1884 );
1885 assert_eq!(
1886 template.network_key_pair().public(),
1887 network_key_pair.public()
1888 );
1889 assert_eq!(
1890 template.protocol_key_pair().public(),
1891 protocol_key_pair.public()
1892 );
1893 }
1894
1895 #[test]
1896 fn a_policy_config_survives_a_round_trip_in_all_three_states() {
1897 let mut config = template_config();
1898
1899 config.policy_config = None;
1900 assert!(round_trip(&config).policy_config.is_none());
1901
1902 config.policy_config = default_traffic_controller_policy_config();
1903 assert_eq!(
1904 as_yaml(&round_trip(&config).policy_config),
1905 as_yaml(&default_traffic_controller_policy_config())
1906 );
1907
1908 let configured = PolicyConfig {
1909 dry_run: !PolicyConfig::default_dos_protection_policy().dry_run,
1910 ..PolicyConfig::default_dos_protection_policy()
1911 };
1912 config.policy_config = Some(configured.clone());
1913 assert_eq!(
1914 as_yaml(&round_trip(&config).policy_config),
1915 as_yaml(&Some(configured))
1916 );
1917 }
1918
1919 #[test]
1920 fn a_grpc_api_config_survives_a_round_trip_in_all_three_states() {
1921 let mut config = template_config();
1922
1923 config.grpc_api_config = None;
1924 assert!(round_trip(&config).grpc_api_config.is_none());
1925
1926 config.grpc_api_config = default_grpc_api_config();
1927 assert_eq!(
1928 as_yaml(&round_trip(&config).grpc_api_config),
1929 as_yaml(&default_grpc_api_config())
1930 );
1931
1932 let configured = GrpcApiConfig {
1933 max_message_size_bytes: 1234,
1934 ..GrpcApiConfig::default()
1935 };
1936 config.grpc_api_config = Some(configured.clone());
1937 assert_eq!(
1938 as_yaml(&round_trip(&config).grpc_api_config),
1939 as_yaml(&Some(configured))
1940 );
1941 }
1942
1943 #[test]
1944 fn the_default_pruning_config_agrees_with_the_serde_default() {
1945 assert_eq!(
1946 super::AuthorityStorePruningConfig::default().periodic_compaction_threshold_days,
1947 default_periodic_compaction_threshold_days()
1948 );
1949 }
1950
1951 #[test]
1952 fn a_compaction_threshold_survives_a_round_trip_in_all_three_states() {
1953 let mut config = template_config();
1954
1955 for state in [None, default_periodic_compaction_threshold_days(), Some(7)] {
1956 config
1957 .authority_store_pruning_config
1958 .periodic_compaction_threshold_days = state;
1959 assert_eq!(
1960 round_trip(&config)
1961 .authority_store_pruning_config
1962 .periodic_compaction_threshold_days,
1963 state
1964 );
1965 }
1966 }
1967
1968 #[test]
1969 fn a_default_value_is_omitted_and_a_disabled_one_is_written_as_null() {
1970 let mut config = template_config();
1971 config.policy_config = default_traffic_controller_policy_config();
1972 config.grpc_api_config = default_grpc_api_config();
1973 config
1974 .authority_store_pruning_config
1975 .periodic_compaction_threshold_days = default_periodic_compaction_threshold_days();
1976
1977 let written = serde_yaml::to_value(&config).unwrap();
1978 assert_eq!(written_at(&written, POLICY_CONFIG), None);
1979 assert_eq!(written_at(&written, GRPC_API_CONFIG), None);
1980 assert_eq!(written_at(&written, COMPACTION_THRESHOLD), None);
1981
1982 config.policy_config = None;
1983 config.grpc_api_config = None;
1984 config
1985 .authority_store_pruning_config
1986 .periodic_compaction_threshold_days = None;
1987
1988 let written = serde_yaml::to_value(&config).unwrap();
1989 assert_eq!(written_at(&written, POLICY_CONFIG), Some(Value::Null));
1990 assert_eq!(written_at(&written, GRPC_API_CONFIG), Some(Value::Null));
1991 assert_eq!(
1992 written_at(&written, COMPACTION_THRESHOLD),
1993 Some(Value::Null)
1994 );
1995 }
1996}
1997
1998#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
2002pub enum RunWithRange {
2003 Epoch(EpochId),
2004 Checkpoint(CheckpointSequenceNumber),
2005}
2006
2007impl RunWithRange {
2008 pub fn is_epoch_gt(&self, epoch_id: EpochId) -> bool {
2010 matches!(self, RunWithRange::Epoch(e) if epoch_id > *e)
2011 }
2012
2013 pub fn matches_checkpoint(&self, seq_num: CheckpointSequenceNumber) -> bool {
2014 matches!(self, RunWithRange::Checkpoint(seq) if *seq == seq_num)
2015 }
2016
2017 pub fn into_checkpoint_bound(self) -> Option<CheckpointSequenceNumber> {
2018 match self {
2019 RunWithRange::Epoch(_) => None,
2020 RunWithRange::Checkpoint(seq) => Some(seq),
2021 }
2022 }
2023}
2024
2025mod bech32_formatted_keypair {
2029 use std::ops::Deref;
2030
2031 use fastcrypto::encoding::{Base64, Encoding};
2032 use iota_sdk_crypto::{ToFromBech32, simple::SimpleKeypair};
2033 use serde::{Deserialize, Deserializer, Serializer};
2034
2035 pub fn serialize<S, T>(kp: &T, serializer: S) -> Result<S::Ok, S::Error>
2036 where
2037 S: Serializer,
2038 T: Deref<Target = SimpleKeypair>,
2039 {
2040 use serde::ser::Error;
2041
2042 let s = kp.to_bech32().map_err(Error::custom)?;
2044
2045 serializer.serialize_str(&s)
2046 }
2047
2048 pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
2049 where
2050 D: Deserializer<'de>,
2051 T: From<SimpleKeypair>,
2052 {
2053 use serde::de::Error;
2054
2055 let s = String::deserialize(deserializer)?;
2056
2057 SimpleKeypair::from_bech32(&s)
2059 .map_err(Error::custom)
2060 .or_else(|_: D::Error| {
2061 let bytes = Base64::decode(&s).map_err(Error::custom)?;
2063 SimpleKeypair::from_bytes(&bytes).map_err(Error::custom)
2064 })
2065 .map(Into::into)
2066 }
2067}