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_checkpoint_inclusion_timeout_ms")]
383 pub max_checkpoint_inclusion_timeout_ms: u64,
384}
385
386fn default_grpc_api_address() -> SocketAddr {
387 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 50051)
388}
389
390fn default_grpc_api_broadcast_buffer_size() -> u32 {
391 100
392}
393
394fn default_grpc_api_max_concurrent_stream_subscribers() -> u32 {
395 1024
396}
397
398fn default_grpc_api_max_message_size_bytes() -> u32 {
399 128 * 1024 * 1024 }
401
402fn default_grpc_api_max_json_move_value_size() -> usize {
403 1024 * 1024 }
405
406fn default_grpc_api_max_execute_transaction_batch_size() -> u32 {
407 20
408}
409
410fn default_grpc_api_max_simulate_transaction_batch_size() -> u32 {
411 20
412}
413
414fn default_grpc_api_max_get_objects_batch_size() -> u32 {
415 1000
416}
417
418fn default_grpc_api_max_get_transactions_batch_size() -> u32 {
419 1000
420}
421
422fn default_grpc_api_max_checkpoint_inclusion_timeout_ms() -> u64 {
423 60_000 }
425
426impl Default for GrpcApiConfig {
427 fn default() -> Self {
428 Self {
429 address: default_grpc_api_address(),
430 tls: None,
431 max_message_size_bytes: default_grpc_api_max_message_size_bytes(),
432 broadcast_buffer_size: default_grpc_api_broadcast_buffer_size(),
433 max_concurrent_stream_subscribers: default_grpc_api_max_concurrent_stream_subscribers(),
434 max_json_move_value_size: default_grpc_api_max_json_move_value_size(),
435 max_execute_transaction_batch_size: default_grpc_api_max_execute_transaction_batch_size(
436 ),
437 max_simulate_transaction_batch_size:
438 default_grpc_api_max_simulate_transaction_batch_size(),
439 max_get_objects_batch_size: default_grpc_api_max_get_objects_batch_size(),
440 max_get_transactions_batch_size: default_grpc_api_max_get_transactions_batch_size(),
441 max_checkpoint_inclusion_timeout_ms:
442 default_grpc_api_max_checkpoint_inclusion_timeout_ms(),
443 }
444 }
445}
446
447impl GrpcApiConfig {
448 const GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE: u32 = 4 * 1024 * 1024; const GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES: u32 =
452 Self::GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE;
453
454 pub fn tls_config(&self) -> Option<&TlsConfig> {
455 self.tls.as_ref()
456 }
457
458 pub fn max_message_size_bytes(&self) -> u32 {
459 self.max_message_size_bytes
461 .max(Self::GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES)
462 }
463
464 pub fn max_message_size_client_bytes(&self, client_max_message_size_bytes: Option<u32>) -> u32 {
468 client_max_message_size_bytes
469 .unwrap_or(Self::GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE)
472 .clamp(
474 Self::GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES,
475 self.max_message_size_bytes(),
476 )
477 }
478}
479
480#[derive(Clone, Debug, Default, Deserialize, Serialize)]
481#[serde(rename_all = "kebab-case")]
482pub struct ExecutionCacheConfig {
483 #[serde(default)]
484 pub writeback_cache: WritebackCacheConfig,
485}
486
487#[derive(Clone, Debug, Default, Deserialize, Serialize)]
488#[serde(rename_all = "kebab-case")]
489pub struct WritebackCacheConfig {
490 #[serde(default, skip_serializing_if = "Option::is_none")]
493 pub max_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
496 pub package_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
499 pub object_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
501 pub marker_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
503 pub object_by_id_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
506 pub transaction_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
508 pub executed_effect_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
510 pub effect_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
513 pub events_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
516 pub transaction_objects_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
521 pub backpressure_threshold: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
527 pub backpressure_threshold_for_rpc: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
537 pub backpressure_soft_limit_pct: Option<u32>,
538}
539
540impl WritebackCacheConfig {
541 pub fn max_cache_size(&self) -> u64 {
542 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_MAX")
543 .ok()
544 .and_then(|s| s.parse().ok())
545 .or(self.max_cache_size)
546 .unwrap_or(100000)
547 }
548
549 pub fn package_cache_size(&self) -> u64 {
550 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_PACKAGE")
551 .ok()
552 .and_then(|s| s.parse().ok())
553 .or(self.package_cache_size)
554 .unwrap_or(1000)
555 }
556
557 pub fn object_cache_size(&self) -> u64 {
558 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_OBJECT")
559 .ok()
560 .and_then(|s| s.parse().ok())
561 .or(self.object_cache_size)
562 .unwrap_or_else(|| self.max_cache_size())
563 }
564
565 pub fn marker_cache_size(&self) -> u64 {
566 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_MARKER")
567 .ok()
568 .and_then(|s| s.parse().ok())
569 .or(self.marker_cache_size)
570 .unwrap_or_else(|| self.object_cache_size())
571 }
572
573 pub fn object_by_id_cache_size(&self) -> u64 {
574 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_OBJECT_BY_ID")
575 .ok()
576 .and_then(|s| s.parse().ok())
577 .or(self.object_by_id_cache_size)
578 .unwrap_or_else(|| self.object_cache_size())
579 }
580
581 pub fn transaction_cache_size(&self) -> u64 {
582 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_TRANSACTION")
583 .ok()
584 .and_then(|s| s.parse().ok())
585 .or(self.transaction_cache_size)
586 .unwrap_or_else(|| self.max_cache_size())
587 }
588
589 pub fn executed_effect_cache_size(&self) -> u64 {
590 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EXECUTED_EFFECT")
591 .ok()
592 .and_then(|s| s.parse().ok())
593 .or(self.executed_effect_cache_size)
594 .unwrap_or_else(|| self.transaction_cache_size())
595 }
596
597 pub fn effect_cache_size(&self) -> u64 {
598 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EFFECT")
599 .ok()
600 .and_then(|s| s.parse().ok())
601 .or(self.effect_cache_size)
602 .unwrap_or_else(|| self.executed_effect_cache_size())
603 }
604
605 pub fn events_cache_size(&self) -> u64 {
606 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EVENTS")
607 .ok()
608 .and_then(|s| s.parse().ok())
609 .or(self.events_cache_size)
610 .unwrap_or_else(|| self.transaction_cache_size())
611 }
612
613 pub fn transaction_objects_cache_size(&self) -> u64 {
614 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_TRANSACTION_OBJECTS")
615 .ok()
616 .and_then(|s| s.parse().ok())
617 .or(self.transaction_objects_cache_size)
618 .unwrap_or(1000)
619 }
620
621 pub fn backpressure_threshold(&self) -> u64 {
622 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_THRESHOLD")
623 .ok()
624 .and_then(|s| s.parse().ok())
625 .or(self.backpressure_threshold)
626 .unwrap_or(100_000)
627 }
628
629 pub fn backpressure_threshold_for_rpc(&self) -> u64 {
630 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_THRESHOLD_FOR_RPC")
631 .ok()
632 .and_then(|s| s.parse().ok())
633 .or(self.backpressure_threshold_for_rpc)
634 .unwrap_or(self.backpressure_threshold())
635 }
636
637 pub fn backpressure_soft_limit_pct(&self) -> u32 {
638 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_SOFT_LIMIT_PCT")
639 .ok()
640 .and_then(|s| s.parse().ok())
641 .or(self.backpressure_soft_limit_pct)
642 .unwrap_or(50)
643 .min(100)
644 }
645}
646
647#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
648#[serde(rename_all = "lowercase")]
649pub enum ServerType {
650 WebSocket,
651 Http,
652 Both,
653}
654
655#[derive(Clone, Debug, Deserialize, Serialize)]
656#[serde(rename_all = "kebab-case")]
657pub struct TransactionKeyValueStoreReadConfig {
658 #[serde(default = "default_base_url")]
659 pub base_url: String,
660
661 #[serde(default = "default_cache_size")]
662 pub cache_size: u64,
663}
664
665impl Default for TransactionKeyValueStoreReadConfig {
666 fn default() -> Self {
667 Self {
668 base_url: default_base_url(),
669 cache_size: default_cache_size(),
670 }
671 }
672}
673
674fn default_base_url() -> String {
675 "".to_string()
676}
677
678fn default_cache_size() -> u64 {
679 100_000
680}
681
682fn default_transaction_kv_store_config() -> TransactionKeyValueStoreReadConfig {
683 TransactionKeyValueStoreReadConfig::default()
684}
685
686fn default_authority_store_pruning_config() -> AuthorityStorePruningConfig {
687 AuthorityStorePruningConfig::default()
688}
689
690pub fn default_enable_index_processing() -> bool {
691 true
692}
693
694fn default_grpc_address() -> Multiaddr {
695 "/ip4/0.0.0.0/tcp/8080".parse().unwrap()
696}
697fn default_authority_key_pair() -> AuthorityKeyPairWithPath {
698 AuthorityKeyPairWithPath::new(get_key_pair_from_rng::<AuthorityKeyPair, _>(&mut OsRng).1)
699}
700
701fn default_key_pair() -> KeyPairWithPath {
702 KeyPairWithPath::new(AccountPrivateKey::random().into())
703}
704
705fn default_metrics_address() -> SocketAddr {
706 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9184)
707}
708
709pub fn default_admin_interface_address() -> SocketAddr {
710 SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 1337)
711}
712
713pub fn default_json_rpc_address() -> SocketAddr {
714 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9000)
715}
716
717pub fn default_grpc_api_config() -> Option<GrpcApiConfig> {
718 Some(GrpcApiConfig::default())
719}
720
721fn is_default_grpc_api_config(grpc_api_config: &Option<GrpcApiConfig>) -> bool {
722 serializes_like(grpc_api_config, &default_grpc_api_config())
723}
724
725fn serializes_like<T: Serialize>(value: &T, default: &T) -> bool {
731 match (serde_yaml::to_string(value), serde_yaml::to_string(default)) {
732 (Ok(value), Ok(default)) => value == default,
733 _ => false,
734 }
735}
736
737pub fn default_grpc_concurrency_limit_per_core() -> NonZeroUsize {
738 NonZeroUsize::new(1000).unwrap()
739}
740
741pub fn default_end_of_epoch_broadcast_channel_capacity() -> usize {
742 128
743}
744
745pub fn default_full_checkpoint_contents_cache_size_mb() -> usize {
746 DEFAULT_FULL_CHECKPOINT_CONTENTS_CACHE_SIZE_MB
747}
748
749pub fn bool_true() -> bool {
750 true
751}
752
753impl Config for NodeConfig {}
754
755impl NodeConfig {
756 pub fn authority_key_pair(&self) -> &AuthorityKeyPair {
757 self.authority_key_pair.authority_keypair()
758 }
759
760 pub fn protocol_key_pair(&self) -> &NetworkKeyPair {
761 self.protocol_key_pair.ed25519_keypair()
762 }
763
764 pub fn network_key_pair(&self) -> &NetworkKeyPair {
765 self.network_key_pair.ed25519_keypair()
766 }
767
768 pub fn authority_public_key(&self) -> AuthorityPublicKeyBytes {
769 self.authority_key_pair().public().into()
770 }
771
772 pub fn db_path(&self) -> PathBuf {
773 self.db_path.join("live")
774 }
775
776 pub fn db_checkpoint_path(&self) -> PathBuf {
777 self.db_path.join("db_checkpoints")
778 }
779
780 pub fn snapshot_path(&self) -> PathBuf {
781 self.db_path.join("snapshot")
782 }
783
784 pub fn network_address(&self) -> &Multiaddr {
785 &self.network_address
786 }
787
788 pub fn consensus_config(&self) -> Option<&ConsensusConfig> {
789 self.consensus_config.as_ref()
790 }
791
792 pub fn genesis(&self) -> Result<&genesis::Genesis> {
793 self.genesis.genesis()
794 }
795
796 pub fn load_migration_tx_data(&self) -> Result<MigrationTxData> {
797 let Some(location) = &self.migration_tx_data_path else {
798 anyhow::bail!("no file location set");
799 };
800
801 let migration_tx_data = MigrationTxData::load(location)?;
803
804 migration_tx_data.validate_from_genesis(self.genesis.genesis()?)?;
806 Ok(migration_tx_data)
807 }
808
809 pub fn iota_address(&self) -> Address {
810 self.account_key_pair
811 .keypair()
812 .public_key()
813 .derive_address()
814 }
815
816 pub fn checkpoint_archive_config(&self) -> Option<&CheckpointArchiveConfig> {
817 self.checkpoint_archive_config.as_ref()
818 }
819
820 pub fn jsonrpc_server_type(&self) -> ServerType {
821 self.jsonrpc_server_type.unwrap_or(ServerType::Http)
822 }
823
824 pub fn is_validator(&self) -> bool {
827 self.consensus_config.is_some()
828 }
829
830 pub fn validate(&self) -> Result<()> {
834 if self.is_validator() {
837 if self.enable_grpc_api {
838 anyhow::bail!(
839 "`enable-grpc-api` is set, but validators do not expose the gRPC API; turn \
840 it off, or move the API to a fullnode"
841 );
842 }
843 if self
844 .state_snapshot_write_config
845 .object_store_config
846 .is_some()
847 {
848 anyhow::bail!(
849 "`state-snapshot-write-config.object-store-config` is set, but snapshot \
850 upload is only supported on fullnodes; remove the setting or move the \
851 upload to a fullnode"
852 );
853 }
854 }
855 if self.enable_grpc_api && self.grpc_api_config.is_none() {
859 anyhow::bail!(
860 "`enable-grpc-api` is set but `grpc-api-config` is `null`; give it a value, \
861 remove the key to take the default config, or turn off `enable-grpc-api`"
862 );
863 }
864 if self
866 .state_snapshot_write_config
867 .object_store_config
868 .as_ref()
869 .is_some_and(|store| store.object_store.is_none())
870 {
871 anyhow::bail!(
872 "`state-snapshot-write-config.object-store-config` has no `object-store`; \
873 snapshot upload needs a storage backend"
874 );
875 }
876 if self.firewall_config.is_some() && self.policy_config.is_none() {
881 anyhow::bail!(
882 "`firewall-config` is set but `policy-config` is `null`; the firewall is driven \
883 by the traffic controller, which does not run without a policy; remove \
884 `firewall-config` or set a `policy-config`"
885 );
886 }
887 Ok(())
888 }
889}
890
891#[derive(Debug, Clone, Deserialize, Serialize)]
892#[serde(rename_all = "kebab-case")]
893pub struct ConsensusConfig {
894 pub db_path: PathBuf,
896
897 pub db_retention_epochs: Option<u64>,
901
902 pub db_pruner_period_secs: Option<u64>,
906
907 pub max_pending_transactions: Option<usize>,
918
919 pub max_submit_position: Option<usize>,
925
926 pub submit_delay_step_override_millis: Option<u64>,
932
933 #[serde(skip_serializing_if = "Option::is_none", alias = "starfish_parameters")]
935 pub parameters: Option<StarfishParameters>,
936
937 #[serde(skip_serializing_if = "Option::is_none")]
943 pub graduated_load_shedding_soft_limit_pct: Option<u32>,
944}
945
946impl ConsensusConfig {
947 pub fn db_path(&self) -> &Path {
948 &self.db_path
949 }
950
951 pub fn max_pending_transactions(&self) -> usize {
955 self.max_pending_transactions.unwrap_or(20_000)
956 }
957
958 pub fn graduated_load_shedding_soft_limit_pct(&self) -> u32 {
963 self.graduated_load_shedding_soft_limit_pct
964 .unwrap_or(50)
965 .min(100)
966 }
967
968 pub fn submit_delay_step_override(&self) -> Option<Duration> {
969 self.submit_delay_step_override_millis
970 .map(Duration::from_millis)
971 }
972
973 pub fn db_retention_epochs(&self) -> u64 {
974 self.db_retention_epochs.unwrap_or(0)
975 }
976
977 pub fn db_pruner_period(&self) -> Duration {
978 self.db_pruner_period_secs
980 .map(Duration::from_secs)
981 .unwrap_or(Duration::from_secs(3_600))
982 }
983}
984
985#[derive(Clone, Debug, Deserialize, Serialize)]
986#[serde(rename_all = "kebab-case")]
987pub struct CheckpointExecutorConfig {
988 #[serde(default = "default_checkpoint_execution_max_concurrency")]
993 pub checkpoint_execution_max_concurrency: usize,
994
995 #[serde(default = "default_local_execution_timeout_sec")]
1001 pub local_execution_timeout_sec: u64,
1002
1003 #[serde(default, skip_serializing_if = "Option::is_none")]
1008 pub data_ingestion_dir: Option<PathBuf>,
1009}
1010
1011#[derive(Clone, Debug, Default, Deserialize, Serialize)]
1012#[serde(rename_all = "kebab-case")]
1013pub struct ExpensiveSafetyCheckConfig {
1014 #[serde(default)]
1019 enable_epoch_iota_conservation_check: bool,
1020
1021 #[serde(default)]
1025 enable_deep_per_tx_iota_conservation_check: bool,
1026
1027 #[serde(default)]
1030 force_disable_epoch_iota_conservation_check: bool,
1031
1032 #[serde(default)]
1035 enable_state_consistency_check: bool,
1036
1037 #[serde(default)]
1039 force_disable_state_consistency_check: bool,
1040
1041 #[serde(default)]
1042 enable_secondary_index_checks: bool,
1043 }
1045
1046impl ExpensiveSafetyCheckConfig {
1047 pub fn new_enable_all() -> Self {
1048 Self {
1049 enable_epoch_iota_conservation_check: true,
1050 enable_deep_per_tx_iota_conservation_check: true,
1051 force_disable_epoch_iota_conservation_check: false,
1052 enable_state_consistency_check: true,
1053 force_disable_state_consistency_check: false,
1054 enable_secondary_index_checks: false, }
1056 }
1057
1058 pub fn new_disable_all() -> Self {
1059 Self {
1060 enable_epoch_iota_conservation_check: false,
1061 enable_deep_per_tx_iota_conservation_check: false,
1062 force_disable_epoch_iota_conservation_check: true,
1063 enable_state_consistency_check: false,
1064 force_disable_state_consistency_check: true,
1065 enable_secondary_index_checks: false,
1066 }
1067 }
1068
1069 pub fn force_disable_epoch_iota_conservation_check(&mut self) {
1070 self.force_disable_epoch_iota_conservation_check = true;
1071 }
1072
1073 pub fn enable_epoch_iota_conservation_check(&self) -> bool {
1074 (self.enable_epoch_iota_conservation_check || cfg!(debug_assertions))
1075 && !self.force_disable_epoch_iota_conservation_check
1076 }
1077
1078 pub fn force_disable_state_consistency_check(&mut self) {
1079 self.force_disable_state_consistency_check = true;
1080 }
1081
1082 pub fn enable_state_consistency_check(&self) -> bool {
1083 (self.enable_state_consistency_check || cfg!(debug_assertions))
1084 && !self.force_disable_state_consistency_check
1085 }
1086
1087 pub fn enable_deep_per_tx_iota_conservation_check(&self) -> bool {
1088 self.enable_deep_per_tx_iota_conservation_check || cfg!(debug_assertions)
1089 }
1090
1091 pub fn enable_secondary_index_checks(&self) -> bool {
1092 self.enable_secondary_index_checks
1093 }
1094}
1095
1096fn default_checkpoint_execution_max_concurrency() -> usize {
1097 4
1098}
1099
1100fn default_local_execution_timeout_sec() -> u64 {
1101 30
1102}
1103
1104impl Default for CheckpointExecutorConfig {
1105 fn default() -> Self {
1106 Self {
1107 checkpoint_execution_max_concurrency: default_checkpoint_execution_max_concurrency(),
1108 local_execution_timeout_sec: default_local_execution_timeout_sec(),
1109 data_ingestion_dir: None,
1110 }
1111 }
1112}
1113
1114#[derive(Debug, Clone, Deserialize, Serialize)]
1115#[serde(rename_all = "kebab-case")]
1116pub struct AuthorityStorePruningConfig {
1117 #[serde(default = "default_num_latest_epoch_dbs_to_retain")]
1119 pub num_latest_epoch_dbs_to_retain: usize,
1120 #[serde(default)]
1125 pub num_epochs_to_retain: u64,
1126 #[serde(
1135 default = "default_periodic_compaction_threshold_days",
1136 skip_serializing_if = "is_default_periodic_compaction_threshold_days"
1137 )]
1138 pub periodic_compaction_threshold_days: Option<usize>,
1139 #[serde(skip_serializing_if = "Option::is_none")]
1142 pub num_epochs_to_retain_for_checkpoints: Option<u64>,
1143 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1149 pub enable_compaction_filter: bool,
1150 #[serde(skip_serializing_if = "Option::is_none")]
1151 pub num_epochs_to_retain_for_indexes: Option<u64>,
1152}
1153
1154fn default_num_latest_epoch_dbs_to_retain() -> usize {
1155 3
1156}
1157
1158fn default_periodic_compaction_threshold_days() -> Option<usize> {
1159 Some(1)
1160}
1161
1162fn is_default_periodic_compaction_threshold_days(days: &Option<usize>) -> bool {
1163 *days == default_periodic_compaction_threshold_days()
1164}
1165
1166impl Default for AuthorityStorePruningConfig {
1167 fn default() -> Self {
1168 Self {
1169 num_latest_epoch_dbs_to_retain: default_num_latest_epoch_dbs_to_retain(),
1170 num_epochs_to_retain: 0,
1171 periodic_compaction_threshold_days: default_periodic_compaction_threshold_days(),
1172 num_epochs_to_retain_for_checkpoints: if cfg!(msim) { Some(2) } else { None },
1173 enable_compaction_filter: cfg!(test) || cfg!(msim),
1174 num_epochs_to_retain_for_indexes: None,
1175 }
1176 }
1177}
1178
1179impl AuthorityStorePruningConfig {
1180 pub fn set_num_epochs_to_retain(&mut self, num_epochs_to_retain: u64) {
1181 self.num_epochs_to_retain = num_epochs_to_retain;
1182 }
1183
1184 pub fn set_num_epochs_to_retain_for_checkpoints(&mut self, num_epochs_to_retain: Option<u64>) {
1185 self.num_epochs_to_retain_for_checkpoints = num_epochs_to_retain;
1186 }
1187
1188 pub fn num_epochs_to_retain_for_checkpoints(&self) -> Option<u64> {
1189 self.num_epochs_to_retain_for_checkpoints
1190 .map(|n| {
1192 if n < 2 {
1193 info!("num_epochs_to_retain_for_checkpoints must be at least 2, rounding up from {}", n);
1194 2
1195 } else {
1196 n
1197 }
1198 })
1199 }
1200}
1201
1202#[derive(Debug, Clone, Deserialize, Serialize)]
1203#[serde(rename_all = "kebab-case")]
1204pub struct MetricsConfig {
1205 #[serde(skip_serializing_if = "Option::is_none")]
1206 pub push_interval_seconds: Option<u64>,
1207 #[serde(skip_serializing_if = "Option::is_none")]
1208 pub push_url: Option<String>,
1209 #[serde(skip_serializing_if = "Option::is_none")]
1210 pub groups: Option<MetricGroups>,
1211}
1212
1213fn default_checkpoint_archive_download_concurrency() -> NonZeroUsize {
1214 NonZeroUsize::new(10).unwrap()
1215}
1216
1217fn default_checkpoint_archive_verify_concurrency() -> NonZeroUsize {
1218 std::thread::available_parallelism().unwrap_or(NonZeroUsize::new(4).unwrap())
1219}
1220
1221fn default_checkpoint_archive_max_checkpoints_ahead_of_execution() -> NonZeroUsize {
1222 NonZeroUsize::new(100_000).unwrap()
1223}
1224
1225#[derive(Debug, Clone, Deserialize, Serialize)]
1228#[serde(rename_all = "kebab-case")]
1229pub struct CheckpointArchiveConfig {
1230 pub url: String,
1232 #[serde(default = "default_checkpoint_archive_download_concurrency")]
1234 pub download_concurrency: NonZeroUsize,
1235 #[serde(default = "default_checkpoint_archive_verify_concurrency")]
1238 pub verify_concurrency: NonZeroUsize,
1239 #[serde(default = "default_checkpoint_archive_max_checkpoints_ahead_of_execution")]
1245 pub max_checkpoints_ahead_of_execution: NonZeroUsize,
1246}
1247
1248#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1256#[serde(rename_all = "kebab-case")]
1257pub struct StateSnapshotConfig {
1258 #[serde(skip_serializing_if = "Option::is_none")]
1259 pub object_store_config: Option<ObjectStoreConfig>,
1260 pub concurrency: usize,
1261}
1262
1263#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1264#[serde(rename_all = "kebab-case")]
1265pub struct TransactionKeyValueStoreWriteConfig {
1266 pub aws_access_key_id: String,
1267 pub aws_secret_access_key: String,
1268 pub aws_region: String,
1269 pub table_name: String,
1270 pub bucket_name: String,
1271 pub concurrency: usize,
1272}
1273
1274#[derive(Clone, Debug, Deserialize, Serialize)]
1279#[serde(rename_all = "kebab-case")]
1280pub struct AuthorityOverloadConfig {
1281 #[serde(default = "default_max_txn_age_in_queue")]
1285 pub max_txn_age_in_queue: Duration,
1286
1287 #[serde(default = "default_overload_monitor_interval")]
1289 pub overload_monitor_interval: Duration,
1290
1291 #[serde(default = "default_execution_queue_latency_soft_limit")]
1293 pub execution_queue_latency_soft_limit: Duration,
1294
1295 #[serde(default = "default_execution_queue_latency_hard_limit")]
1298 pub execution_queue_latency_hard_limit: Duration,
1299
1300 #[serde(default = "default_max_load_shedding_percentage")]
1302 pub max_load_shedding_percentage: u32,
1303
1304 #[serde(default = "default_min_load_shedding_percentage_above_hard_limit")]
1307 pub min_load_shedding_percentage_above_hard_limit: u32,
1308
1309 #[serde(default = "default_safe_transaction_ready_rate")]
1312 pub safe_transaction_ready_rate: u32,
1313
1314 #[serde(default = "default_check_system_overload_at_signing")]
1317 pub check_system_overload_at_signing: bool,
1318
1319 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1322 pub check_system_overload_at_execution: bool,
1323
1324 #[serde(default = "default_max_transaction_manager_queue_length")]
1328 pub max_transaction_manager_queue_length: usize,
1329
1330 #[serde(default = "default_max_transaction_manager_per_object_queue_length")]
1333 pub max_transaction_manager_per_object_queue_length: usize,
1334
1335 #[serde(default = "default_max_transaction_manager_queue_length_soft_limit_pct")]
1339 pub max_transaction_manager_queue_length_soft_limit_pct: u32,
1340}
1341
1342impl AuthorityOverloadConfig {
1343 pub fn max_transaction_manager_queue_length_soft_limit_pct(&self) -> u32 {
1346 self.max_transaction_manager_queue_length_soft_limit_pct
1347 .min(100)
1348 }
1349}
1350
1351fn default_max_txn_age_in_queue() -> Duration {
1352 Duration::from_millis(500)
1353}
1354
1355fn default_overload_monitor_interval() -> Duration {
1356 Duration::from_secs(10)
1357}
1358
1359fn default_execution_queue_latency_soft_limit() -> Duration {
1360 Duration::from_secs(1)
1361}
1362
1363fn default_execution_queue_latency_hard_limit() -> Duration {
1364 Duration::from_secs(10)
1365}
1366
1367fn default_max_load_shedding_percentage() -> u32 {
1368 95
1369}
1370
1371fn default_min_load_shedding_percentage_above_hard_limit() -> u32 {
1372 50
1373}
1374
1375fn default_safe_transaction_ready_rate() -> u32 {
1376 100
1377}
1378
1379fn default_check_system_overload_at_signing() -> bool {
1380 true
1381}
1382
1383fn default_max_transaction_manager_queue_length() -> usize {
1384 100_000
1385}
1386
1387fn default_max_transaction_manager_queue_length_soft_limit_pct() -> u32 {
1388 50
1389}
1390
1391fn default_max_transaction_manager_per_object_queue_length() -> usize {
1392 20
1393}
1394
1395impl Default for AuthorityOverloadConfig {
1396 fn default() -> Self {
1397 Self {
1398 max_txn_age_in_queue: default_max_txn_age_in_queue(),
1399 overload_monitor_interval: default_overload_monitor_interval(),
1400 execution_queue_latency_soft_limit: default_execution_queue_latency_soft_limit(),
1401 execution_queue_latency_hard_limit: default_execution_queue_latency_hard_limit(),
1402 max_load_shedding_percentage: default_max_load_shedding_percentage(),
1403 min_load_shedding_percentage_above_hard_limit:
1404 default_min_load_shedding_percentage_above_hard_limit(),
1405 safe_transaction_ready_rate: default_safe_transaction_ready_rate(),
1406 check_system_overload_at_signing: true,
1407 check_system_overload_at_execution: false,
1408 max_transaction_manager_queue_length: default_max_transaction_manager_queue_length(),
1409 max_transaction_manager_queue_length_soft_limit_pct:
1410 default_max_transaction_manager_queue_length_soft_limit_pct(),
1411 max_transaction_manager_per_object_queue_length:
1412 default_max_transaction_manager_per_object_queue_length(),
1413 }
1414 }
1415}
1416
1417fn default_authority_overload_config() -> AuthorityOverloadConfig {
1418 AuthorityOverloadConfig::default()
1419}
1420
1421fn default_traffic_controller_policy_config() -> Option<PolicyConfig> {
1422 Some(PolicyConfig::default_dos_protection_policy())
1423}
1424
1425fn is_default_traffic_controller_policy_config(policy_config: &Option<PolicyConfig>) -> bool {
1426 serializes_like(policy_config, &default_traffic_controller_policy_config())
1427}
1428
1429#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1430pub struct Genesis {
1431 #[serde(flatten)]
1432 location: Option<GenesisLocation>,
1433
1434 #[serde(skip)]
1435 genesis: once_cell::sync::OnceCell<genesis::Genesis>,
1436}
1437
1438impl Genesis {
1439 pub fn new(genesis: genesis::Genesis) -> Self {
1440 Self {
1441 location: Some(GenesisLocation::InPlace {
1442 genesis: Box::new(genesis),
1443 }),
1444 genesis: Default::default(),
1445 }
1446 }
1447
1448 pub fn new_from_file<P: Into<PathBuf>>(path: P) -> Self {
1449 Self {
1450 location: Some(GenesisLocation::File {
1451 genesis_file_location: path.into(),
1452 }),
1453 genesis: Default::default(),
1454 }
1455 }
1456
1457 pub fn new_empty() -> Self {
1458 Self {
1459 location: None,
1460 genesis: Default::default(),
1461 }
1462 }
1463
1464 pub fn genesis(&self) -> Result<&genesis::Genesis> {
1465 match &self.location {
1466 Some(GenesisLocation::InPlace { genesis }) => Ok(genesis),
1467 Some(GenesisLocation::File {
1468 genesis_file_location,
1469 }) => self
1470 .genesis
1471 .get_or_try_init(|| genesis::Genesis::load(genesis_file_location)),
1472 None => anyhow::bail!("no genesis location set"),
1473 }
1474 }
1475}
1476
1477#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1478#[serde(untagged)]
1479enum GenesisLocation {
1480 InPlace {
1481 genesis: Box<genesis::Genesis>,
1482 },
1483 File {
1484 #[serde(rename = "genesis-file-location")]
1485 genesis_file_location: PathBuf,
1486 },
1487}
1488
1489#[derive(Clone, Debug, Deserialize, Serialize)]
1492pub struct KeyPairWithPath {
1493 #[serde(flatten)]
1494 location: KeyPairLocation,
1495
1496 #[serde(skip)]
1497 keypair: OnceCell<Arc<SimpleKeypair>>,
1498
1499 #[serde(skip)]
1505 ed25519_keypair: OnceCell<Arc<Ed25519KeyPair>>,
1506}
1507
1508impl PartialEq for KeyPairWithPath {
1509 fn eq(&self, other: &Self) -> bool {
1510 self.location == other.location
1511 }
1512}
1513
1514impl Eq for KeyPairWithPath {}
1515
1516#[derive(Debug, Clone, Deserialize, Serialize)]
1517#[serde(untagged)]
1518enum KeyPairLocation {
1519 InPlace {
1520 #[serde(with = "bech32_formatted_keypair")]
1521 value: Arc<SimpleKeypair>,
1522 },
1523 File {
1524 path: PathBuf,
1525 },
1526}
1527
1528impl PartialEq for KeyPairLocation {
1529 fn eq(&self, other: &Self) -> bool {
1530 match (self, other) {
1531 (Self::InPlace { value: a }, Self::InPlace { value: b }) => {
1532 a.to_bytes() == b.to_bytes()
1533 }
1534 (Self::File { path: a }, Self::File { path: b }) => a == b,
1535 _ => false,
1536 }
1537 }
1538}
1539
1540impl Eq for KeyPairLocation {}
1541
1542impl KeyPairWithPath {
1543 pub fn new(kp: SimpleKeypair) -> Self {
1544 let cell: OnceCell<Arc<SimpleKeypair>> = OnceCell::new();
1545 let arc_kp = Arc::new(kp);
1546 cell.set(arc_kp.clone()).expect("failed to set keypair");
1549 Self {
1550 location: KeyPairLocation::InPlace { value: arc_kp },
1551 keypair: cell,
1552 ed25519_keypair: OnceCell::new(),
1553 }
1554 }
1555
1556 pub fn new_from_path(path: PathBuf) -> Self {
1557 let cell: OnceCell<Arc<SimpleKeypair>> = OnceCell::new();
1558 cell.set(Arc::new(read_keypair_from_file(&path).unwrap_or_else(
1561 |e| panic!("invalid keypair file at path {path:?}: {e}"),
1562 )))
1563 .expect("failed to set keypair");
1564 Self {
1565 location: KeyPairLocation::File { path },
1566 keypair: cell,
1567 ed25519_keypair: OnceCell::new(),
1568 }
1569 }
1570
1571 pub fn keypair(&self) -> &SimpleKeypair {
1572 self.keypair
1573 .get_or_init(|| match &self.location {
1574 KeyPairLocation::InPlace { value } => value.clone(),
1575 KeyPairLocation::File { path } => {
1576 Arc::new(
1579 read_keypair_from_file(path).unwrap_or_else(|e| {
1580 panic!("invalid keypair file at path {path:?}: {e}")
1581 }),
1582 )
1583 }
1584 })
1585 .as_ref()
1586 }
1587
1588 pub fn ed25519_keypair(&self) -> &Ed25519KeyPair {
1592 self.ed25519_keypair
1593 .get_or_init(|| {
1594 Arc::new(
1595 simple_to_network_keypair(self.keypair())
1596 .expect("only Ed25519 network keys are allowed"),
1597 )
1598 })
1599 .as_ref()
1600 }
1601}
1602
1603#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
1606pub struct AuthorityKeyPairWithPath {
1607 #[serde(flatten)]
1608 location: AuthorityKeyPairLocation,
1609
1610 #[serde(skip)]
1611 keypair: OnceCell<Arc<AuthorityKeyPair>>,
1612}
1613
1614#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1615#[serde(untagged)]
1616enum AuthorityKeyPairLocation {
1617 InPlace { value: Arc<AuthorityKeyPair> },
1618 File { path: PathBuf },
1619}
1620
1621impl AuthorityKeyPairWithPath {
1622 pub fn new(kp: AuthorityKeyPair) -> Self {
1623 let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1624 let arc_kp = Arc::new(kp);
1625 cell.set(arc_kp.clone())
1628 .expect("failed to set authority keypair");
1629 Self {
1630 location: AuthorityKeyPairLocation::InPlace { value: arc_kp },
1631 keypair: cell,
1632 }
1633 }
1634
1635 pub fn new_from_path(path: PathBuf) -> Self {
1636 let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1637 cell.set(Arc::new(
1640 read_authority_keypair_from_file(&path)
1641 .unwrap_or_else(|_| panic!("invalid authority keypair file at path {path:?}")),
1642 ))
1643 .expect("failed to set authority keypair");
1644 Self {
1645 location: AuthorityKeyPairLocation::File { path },
1646 keypair: cell,
1647 }
1648 }
1649
1650 pub fn authority_keypair(&self) -> &AuthorityKeyPair {
1651 self.keypair
1652 .get_or_init(|| match &self.location {
1653 AuthorityKeyPairLocation::InPlace { value } => value.clone(),
1654 AuthorityKeyPairLocation::File { path } => {
1655 Arc::new(
1658 read_authority_keypair_from_file(path)
1659 .unwrap_or_else(|_| panic!("invalid authority keypair file {path:?}")),
1660 )
1661 }
1662 })
1663 .as_ref()
1664 }
1665}
1666
1667#[derive(Clone, Debug, Deserialize, Serialize, Default)]
1670#[serde(rename_all = "kebab-case")]
1671pub struct StateDebugDumpConfig {
1672 #[serde(skip_serializing_if = "Option::is_none")]
1673 pub dump_file_directory: Option<PathBuf>,
1674}
1675
1676#[cfg(test)]
1677mod tests {
1678 use std::path::PathBuf;
1679
1680 use fastcrypto::traits::KeyPair;
1681 use iota_keys::keypair_file::{write_authority_keypair_to_file, write_keypair_to_file};
1682 use iota_types::{
1683 crypto::{
1684 AuthorityKeyPair, NetworkKeyPair, get_key_pair_from_rng, network_to_simple_keypair,
1685 },
1686 traffic_control::{PolicyConfig, RemoteFirewallConfig},
1687 };
1688 use rand::{SeedableRng, rngs::StdRng};
1689 use serde::Serialize;
1690 use serde_yaml::Value;
1691
1692 use super::{
1693 Genesis, GrpcApiConfig, ObjectStoreConfig, default_grpc_api_config,
1694 default_periodic_compaction_threshold_days, default_traffic_controller_policy_config,
1695 };
1696 use crate::{NodeConfig, object_storage_config::ObjectStoreType};
1697
1698 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1699
1700 const POLICY_CONFIG: &[&str] = &["policy-config"];
1701 const GRPC_API_CONFIG: &[&str] = &["grpc-api-config"];
1702 const COMPACTION_THRESHOLD: &[&str] = &[
1703 "authority-store-pruning-config",
1704 "periodic-compaction-threshold-days",
1705 ];
1706
1707 fn template_config() -> NodeConfig {
1708 serde_yaml::from_str(TEMPLATE).unwrap()
1709 }
1710
1711 fn consensus_config() -> super::ConsensusConfig {
1712 serde_yaml::from_str("db-path: /opt/iota/consensus-db").unwrap()
1713 }
1714
1715 fn object_store_config() -> ObjectStoreConfig {
1716 ObjectStoreConfig {
1717 object_store: Some(ObjectStoreType::File),
1718 directory: Some(PathBuf::from("/opt/iota/snapshots")),
1719 ..Default::default()
1720 }
1721 }
1722
1723 fn round_trip(config: &NodeConfig) -> NodeConfig {
1724 serde_yaml::from_str(&serde_yaml::to_string(config).unwrap()).unwrap()
1725 }
1726
1727 fn as_yaml<T: Serialize>(value: &T) -> String {
1728 serde_yaml::to_string(value).unwrap()
1729 }
1730
1731 fn written_at(value: &Value, path: &[&str]) -> Option<Value> {
1734 let (last, parents) = path.split_last().unwrap();
1735 let mut current = value;
1736 for name in parents {
1737 current = current
1738 .as_mapping()
1739 .unwrap()
1740 .get(&Value::String((*name).to_owned()))
1741 .unwrap();
1742 }
1743 current
1744 .as_mapping()
1745 .unwrap()
1746 .get(&Value::String((*last).to_owned()))
1747 .cloned()
1748 }
1749
1750 #[test]
1751 fn serialize_genesis_from_file() {
1752 let g = Genesis::new_from_file("path/to/file");
1753
1754 let s = serde_yaml::to_string(&g).unwrap();
1755 assert_eq!("---\ngenesis-file-location: path/to/file\n", s);
1756 let loaded_genesis: Genesis = serde_yaml::from_str(&s).unwrap();
1757 assert_eq!(g, loaded_genesis);
1758 }
1759
1760 #[test]
1761 fn fullnode_template() {
1762 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1763
1764 let _template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1765 }
1766
1767 #[test]
1768 fn validate_requires_a_grpc_config_when_the_api_is_enabled() {
1769 let mut config = template_config();
1772 config.grpc_api_config = None;
1773 config.validate().unwrap();
1774
1775 config.enable_grpc_api = true;
1776 let err = config.validate().unwrap_err().to_string();
1777 assert!(err.contains("`grpc-api-config` is `null`"), "{err}");
1778
1779 config.grpc_api_config = Some(GrpcApiConfig::default());
1780 config.validate().unwrap();
1781
1782 config.grpc_api_config = None;
1785 config.consensus_config = Some(consensus_config());
1786 let err = config.validate().unwrap_err().to_string();
1787 assert!(err.contains("validators do not expose"), "{err}");
1788 }
1789
1790 #[test]
1791 fn validate_rejects_the_grpc_api_on_a_validator() {
1792 let mut config = template_config();
1793 config.consensus_config = Some(consensus_config());
1794 config.validate().unwrap();
1795
1796 config.enable_grpc_api = true;
1797 let err = config.validate().unwrap_err().to_string();
1798 assert!(err.contains("validators do not expose"), "{err}");
1799
1800 config.consensus_config = None;
1802 config.validate().unwrap();
1803 }
1804
1805 #[test]
1806 fn validate_rejects_snapshot_upload_on_a_validator() {
1807 let mut config = template_config();
1808 config.state_snapshot_write_config.object_store_config = Some(object_store_config());
1809 config.validate().unwrap();
1810
1811 config.consensus_config = Some(consensus_config());
1812 let err = config.validate().unwrap_err().to_string();
1813 assert!(err.contains("snapshot upload"), "{err}");
1814 }
1815
1816 #[test]
1817 fn validate_rejects_a_snapshot_store_without_a_backend() {
1818 let mut config = template_config();
1819 config.state_snapshot_write_config.object_store_config = Some(ObjectStoreConfig::default());
1820
1821 let err = config.validate().unwrap_err().to_string();
1822 assert!(err.contains("storage backend"), "{err}");
1823 }
1824
1825 #[test]
1826 fn validate_rejects_a_firewall_without_a_policy() {
1827 let mut config = template_config();
1828 config.firewall_config = Some(RemoteFirewallConfig {
1829 remote_fw_url: "http://localhost:65000".to_owned(),
1830 destination_port: 8080,
1831 delegate_spam_blocking: false,
1832 delegate_error_blocking: false,
1833 drain_path: PathBuf::from("/tmp/drain"),
1834 drain_timeout_secs: 300,
1835 });
1836
1837 config.validate().unwrap();
1840
1841 config.policy_config = None;
1844 let err = config.validate().unwrap_err().to_string();
1845 assert!(err.contains("`firewall-config` is set"), "{err}");
1846 }
1847
1848 #[test]
1849 fn enable_soft_locking_defaults_to_enabled() {
1850 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1853
1854 let config: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1855 assert!(config.enable_soft_locking);
1856 }
1857
1858 #[test]
1859 fn load_key_pairs_to_node_config() {
1860 let authority_key_pair: AuthorityKeyPair =
1861 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1862 let protocol_key_pair: NetworkKeyPair =
1863 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1864 let network_key_pair: NetworkKeyPair =
1865 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1866
1867 write_authority_keypair_to_file(&authority_key_pair, PathBuf::from("authority.key"))
1868 .unwrap();
1869 write_keypair_to_file(
1870 &network_to_simple_keypair(&protocol_key_pair),
1871 PathBuf::from("protocol.key"),
1872 )
1873 .unwrap();
1874 write_keypair_to_file(
1875 &network_to_simple_keypair(&network_key_pair),
1876 PathBuf::from("network.key"),
1877 )
1878 .unwrap();
1879
1880 const TEMPLATE: &str = include_str!("../data/fullnode-template-with-path.yaml");
1881 let template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1882 assert_eq!(
1883 template.authority_key_pair().public(),
1884 authority_key_pair.public()
1885 );
1886 assert_eq!(
1887 template.network_key_pair().public(),
1888 network_key_pair.public()
1889 );
1890 assert_eq!(
1891 template.protocol_key_pair().public(),
1892 protocol_key_pair.public()
1893 );
1894 }
1895
1896 #[test]
1897 fn a_policy_config_survives_a_round_trip_in_all_three_states() {
1898 let mut config = template_config();
1899
1900 config.policy_config = None;
1901 assert!(round_trip(&config).policy_config.is_none());
1902
1903 config.policy_config = default_traffic_controller_policy_config();
1904 assert_eq!(
1905 as_yaml(&round_trip(&config).policy_config),
1906 as_yaml(&default_traffic_controller_policy_config())
1907 );
1908
1909 let configured = PolicyConfig {
1910 dry_run: !PolicyConfig::default_dos_protection_policy().dry_run,
1911 ..PolicyConfig::default_dos_protection_policy()
1912 };
1913 config.policy_config = Some(configured.clone());
1914 assert_eq!(
1915 as_yaml(&round_trip(&config).policy_config),
1916 as_yaml(&Some(configured))
1917 );
1918 }
1919
1920 #[test]
1921 fn a_grpc_api_config_survives_a_round_trip_in_all_three_states() {
1922 let mut config = template_config();
1923
1924 config.grpc_api_config = None;
1925 assert!(round_trip(&config).grpc_api_config.is_none());
1926
1927 config.grpc_api_config = default_grpc_api_config();
1928 assert_eq!(
1929 as_yaml(&round_trip(&config).grpc_api_config),
1930 as_yaml(&default_grpc_api_config())
1931 );
1932
1933 let configured = GrpcApiConfig {
1934 max_message_size_bytes: 1234,
1935 ..GrpcApiConfig::default()
1936 };
1937 config.grpc_api_config = Some(configured.clone());
1938 assert_eq!(
1939 as_yaml(&round_trip(&config).grpc_api_config),
1940 as_yaml(&Some(configured))
1941 );
1942 }
1943
1944 #[test]
1945 fn the_default_pruning_config_agrees_with_the_serde_default() {
1946 assert_eq!(
1947 super::AuthorityStorePruningConfig::default().periodic_compaction_threshold_days,
1948 default_periodic_compaction_threshold_days()
1949 );
1950 }
1951
1952 #[test]
1953 fn a_compaction_threshold_survives_a_round_trip_in_all_three_states() {
1954 let mut config = template_config();
1955
1956 for state in [None, default_periodic_compaction_threshold_days(), Some(7)] {
1957 config
1958 .authority_store_pruning_config
1959 .periodic_compaction_threshold_days = state;
1960 assert_eq!(
1961 round_trip(&config)
1962 .authority_store_pruning_config
1963 .periodic_compaction_threshold_days,
1964 state
1965 );
1966 }
1967 }
1968
1969 #[test]
1970 fn a_default_value_is_omitted_and_a_disabled_one_is_written_as_null() {
1971 let mut config = template_config();
1972 config.policy_config = default_traffic_controller_policy_config();
1973 config.grpc_api_config = default_grpc_api_config();
1974 config
1975 .authority_store_pruning_config
1976 .periodic_compaction_threshold_days = default_periodic_compaction_threshold_days();
1977
1978 let written = serde_yaml::to_value(&config).unwrap();
1979 assert_eq!(written_at(&written, POLICY_CONFIG), None);
1980 assert_eq!(written_at(&written, GRPC_API_CONFIG), None);
1981 assert_eq!(written_at(&written, COMPACTION_THRESHOLD), None);
1982
1983 config.policy_config = None;
1984 config.grpc_api_config = None;
1985 config
1986 .authority_store_pruning_config
1987 .periodic_compaction_threshold_days = None;
1988
1989 let written = serde_yaml::to_value(&config).unwrap();
1990 assert_eq!(written_at(&written, POLICY_CONFIG), Some(Value::Null));
1991 assert_eq!(written_at(&written, GRPC_API_CONFIG), Some(Value::Null));
1992 assert_eq!(
1993 written_at(&written, COMPACTION_THRESHOLD),
1994 Some(Value::Null)
1995 );
1996 }
1997}
1998
1999#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
2003pub enum RunWithRange {
2004 Epoch(EpochId),
2005 Checkpoint(CheckpointSequenceNumber),
2006}
2007
2008impl RunWithRange {
2009 pub fn is_epoch_gt(&self, epoch_id: EpochId) -> bool {
2011 matches!(self, RunWithRange::Epoch(e) if epoch_id > *e)
2012 }
2013
2014 pub fn matches_checkpoint(&self, seq_num: CheckpointSequenceNumber) -> bool {
2015 matches!(self, RunWithRange::Checkpoint(seq) if *seq == seq_num)
2016 }
2017
2018 pub fn into_checkpoint_bound(self) -> Option<CheckpointSequenceNumber> {
2019 match self {
2020 RunWithRange::Epoch(_) => None,
2021 RunWithRange::Checkpoint(seq) => Some(seq),
2022 }
2023 }
2024}
2025
2026mod bech32_formatted_keypair {
2030 use std::ops::Deref;
2031
2032 use fastcrypto::encoding::{Base64, Encoding};
2033 use iota_sdk_crypto::{ToFromBech32, simple::SimpleKeypair};
2034 use serde::{Deserialize, Deserializer, Serializer};
2035
2036 pub fn serialize<S, T>(kp: &T, serializer: S) -> Result<S::Ok, S::Error>
2037 where
2038 S: Serializer,
2039 T: Deref<Target = SimpleKeypair>,
2040 {
2041 use serde::ser::Error;
2042
2043 let s = kp.to_bech32().map_err(Error::custom)?;
2045
2046 serializer.serialize_str(&s)
2047 }
2048
2049 pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
2050 where
2051 D: Deserializer<'de>,
2052 T: From<SimpleKeypair>,
2053 {
2054 use serde::de::Error;
2055
2056 let s = String::deserialize(deserializer)?;
2057
2058 SimpleKeypair::from_bech32(&s)
2060 .map_err(Error::custom)
2061 .or_else(|_: D::Error| {
2062 let bytes = Base64::decode(&s).map_err(Error::custom)?;
2064 SimpleKeypair::from_bytes(&bytes).map_err(Error::custom)
2065 })
2066 .map(Into::into)
2067 }
2068}