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::{rand_core::UnwrapErr, rngs::SysRng};
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(
709 get_key_pair_from_rng::<AuthorityKeyPair, _>(&mut UnwrapErr(SysRng)).1,
710 )
711}
712
713fn default_key_pair() -> KeyPairWithPath {
714 KeyPairWithPath::new(AccountPrivateKey::random().into())
715}
716
717fn default_metrics_address() -> SocketAddr {
718 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9184)
719}
720
721pub fn default_admin_interface_address() -> SocketAddr {
722 SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 1337)
723}
724
725pub fn default_json_rpc_address() -> SocketAddr {
726 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9000)
727}
728
729pub fn default_grpc_api_config() -> Option<GrpcApiConfig> {
730 Some(GrpcApiConfig::default())
731}
732
733fn is_default_grpc_api_config(grpc_api_config: &Option<GrpcApiConfig>) -> bool {
734 serializes_like(grpc_api_config, &default_grpc_api_config())
735}
736
737fn serializes_like<T: Serialize>(value: &T, default: &T) -> bool {
743 match (serde_yaml::to_string(value), serde_yaml::to_string(default)) {
744 (Ok(value), Ok(default)) => value == default,
745 _ => false,
746 }
747}
748
749pub fn default_grpc_concurrency_limit_per_core() -> NonZeroUsize {
750 NonZeroUsize::new(1000).unwrap()
751}
752
753pub fn default_end_of_epoch_broadcast_channel_capacity() -> usize {
754 128
755}
756
757pub fn default_full_checkpoint_contents_cache_size_mb() -> usize {
758 DEFAULT_FULL_CHECKPOINT_CONTENTS_CACHE_SIZE_MB
759}
760
761pub fn bool_true() -> bool {
762 true
763}
764
765impl Config for NodeConfig {}
766
767impl NodeConfig {
768 pub fn authority_key_pair(&self) -> &AuthorityKeyPair {
769 self.authority_key_pair.authority_keypair()
770 }
771
772 pub fn protocol_key_pair(&self) -> &NetworkKeyPair {
773 self.protocol_key_pair.ed25519_keypair()
774 }
775
776 pub fn network_key_pair(&self) -> &NetworkKeyPair {
777 self.network_key_pair.ed25519_keypair()
778 }
779
780 pub fn authority_public_key(&self) -> AuthorityPublicKeyBytes {
781 self.authority_key_pair().public().into()
782 }
783
784 pub fn db_path(&self) -> PathBuf {
785 self.db_path.join("live")
786 }
787
788 pub fn snapshot_path(&self) -> PathBuf {
789 self.db_path.join("snapshot")
790 }
791
792 pub fn network_address(&self) -> &Multiaddr {
793 &self.network_address
794 }
795
796 pub fn consensus_config(&self) -> Option<&ConsensusConfig> {
797 self.consensus_config.as_ref()
798 }
799
800 pub fn genesis(&self) -> Result<&genesis::Genesis> {
801 self.genesis.genesis()
802 }
803
804 pub fn load_migration_tx_data(&self) -> Result<MigrationTxData> {
805 let Some(location) = &self.migration_tx_data_path else {
806 anyhow::bail!("no file location set");
807 };
808
809 let migration_tx_data = MigrationTxData::load(location)?;
811
812 migration_tx_data.validate_from_genesis(self.genesis.genesis()?)?;
814 Ok(migration_tx_data)
815 }
816
817 pub fn iota_address(&self) -> Address {
818 self.account_key_pair
819 .keypair()
820 .public_key()
821 .derive_address()
822 }
823
824 pub fn checkpoint_archive_config(&self) -> Option<&CheckpointArchiveConfig> {
825 self.checkpoint_archive_config.as_ref()
826 }
827
828 pub fn jsonrpc_server_type(&self) -> ServerType {
829 self.jsonrpc_server_type.unwrap_or(ServerType::Http)
830 }
831
832 pub fn is_validator(&self) -> bool {
835 self.consensus_config.is_some()
836 }
837
838 pub fn validate(&self) -> Result<()> {
842 if self.is_validator() {
845 if self.enable_grpc_api {
846 anyhow::bail!(
847 "`enable-grpc-api` is set, but validators do not expose the gRPC API; turn \
848 it off, or move the API to a fullnode"
849 );
850 }
851 if self
852 .state_snapshot_write_config
853 .object_store_config
854 .is_some()
855 {
856 anyhow::bail!(
857 "`state-snapshot-write-config.object-store-config` is set, but snapshot \
858 upload is only supported on fullnodes; remove the setting or move the \
859 upload to a fullnode"
860 );
861 }
862 }
863 if self.enable_grpc_api && self.grpc_api_config.is_none() {
867 anyhow::bail!(
868 "`enable-grpc-api` is set but `grpc-api-config` is `null`; give it a value, \
869 remove the key to take the default config, or turn off `enable-grpc-api`"
870 );
871 }
872 if self
874 .state_snapshot_write_config
875 .object_store_config
876 .as_ref()
877 .is_some_and(|store| store.object_store.is_none())
878 {
879 anyhow::bail!(
880 "`state-snapshot-write-config.object-store-config` has no `object-store`; \
881 snapshot upload needs a storage backend"
882 );
883 }
884 if self.firewall_config.is_some() && self.policy_config.is_none() {
889 anyhow::bail!(
890 "`firewall-config` is set but `policy-config` is `null`; the firewall is driven \
891 by the traffic controller, which does not run without a policy; remove \
892 `firewall-config` or set a `policy-config`"
893 );
894 }
895 Ok(())
896 }
897}
898
899#[derive(Debug, Clone, Deserialize, Serialize)]
900#[serde(rename_all = "kebab-case")]
901pub struct ConsensusConfig {
902 pub db_path: PathBuf,
904
905 pub db_retention_epochs: Option<u64>,
909
910 pub db_pruner_period_secs: Option<u64>,
914
915 pub max_pending_transactions: Option<usize>,
926
927 pub max_submit_position: Option<usize>,
933
934 pub submit_delay_step_override_millis: Option<u64>,
940
941 #[serde(skip_serializing_if = "Option::is_none", alias = "starfish_parameters")]
943 pub parameters: Option<StarfishParameters>,
944
945 #[serde(skip_serializing_if = "Option::is_none")]
951 pub graduated_load_shedding_soft_limit_pct: Option<u32>,
952}
953
954impl ConsensusConfig {
955 pub fn db_path(&self) -> &Path {
956 &self.db_path
957 }
958
959 pub fn max_pending_transactions(&self) -> usize {
963 self.max_pending_transactions.unwrap_or(20_000)
964 }
965
966 pub fn graduated_load_shedding_soft_limit_pct(&self) -> u32 {
971 self.graduated_load_shedding_soft_limit_pct
972 .unwrap_or(50)
973 .min(100)
974 }
975
976 pub fn submit_delay_step_override(&self) -> Option<Duration> {
977 self.submit_delay_step_override_millis
978 .map(Duration::from_millis)
979 }
980
981 pub fn db_retention_epochs(&self) -> u64 {
982 self.db_retention_epochs.unwrap_or(0)
983 }
984
985 pub fn db_pruner_period(&self) -> Duration {
986 self.db_pruner_period_secs
988 .map(Duration::from_secs)
989 .unwrap_or(Duration::from_secs(3_600))
990 }
991}
992
993#[derive(Clone, Debug, Deserialize, Serialize)]
994#[serde(rename_all = "kebab-case")]
995pub struct CheckpointExecutorConfig {
996 #[serde(default = "default_checkpoint_execution_max_concurrency")]
1001 pub checkpoint_execution_max_concurrency: usize,
1002
1003 #[serde(default = "default_local_execution_timeout_sec")]
1009 pub local_execution_timeout_sec: u64,
1010
1011 #[serde(default, skip_serializing_if = "Option::is_none")]
1016 pub data_ingestion_dir: Option<PathBuf>,
1017}
1018
1019#[derive(Clone, Debug, Default, Deserialize, Serialize)]
1020#[serde(rename_all = "kebab-case")]
1021pub struct ExpensiveSafetyCheckConfig {
1022 #[serde(default)]
1027 enable_epoch_iota_conservation_check: bool,
1028
1029 #[serde(default)]
1033 enable_deep_per_tx_iota_conservation_check: bool,
1034
1035 #[serde(default)]
1038 force_disable_epoch_iota_conservation_check: bool,
1039
1040 #[serde(default)]
1043 enable_state_consistency_check: bool,
1044
1045 #[serde(default)]
1047 force_disable_state_consistency_check: bool,
1048
1049 #[serde(default)]
1050 enable_secondary_index_checks: bool,
1051 }
1053
1054impl ExpensiveSafetyCheckConfig {
1055 pub fn new_enable_all() -> Self {
1056 Self {
1057 enable_epoch_iota_conservation_check: true,
1058 enable_deep_per_tx_iota_conservation_check: true,
1059 force_disable_epoch_iota_conservation_check: false,
1060 enable_state_consistency_check: true,
1061 force_disable_state_consistency_check: false,
1062 enable_secondary_index_checks: false, }
1064 }
1065
1066 pub fn new_disable_all() -> Self {
1067 Self {
1068 enable_epoch_iota_conservation_check: false,
1069 enable_deep_per_tx_iota_conservation_check: false,
1070 force_disable_epoch_iota_conservation_check: true,
1071 enable_state_consistency_check: false,
1072 force_disable_state_consistency_check: true,
1073 enable_secondary_index_checks: false,
1074 }
1075 }
1076
1077 pub fn force_disable_epoch_iota_conservation_check(&mut self) {
1078 self.force_disable_epoch_iota_conservation_check = true;
1079 }
1080
1081 pub fn enable_epoch_iota_conservation_check(&self) -> bool {
1082 (self.enable_epoch_iota_conservation_check || cfg!(debug_assertions))
1083 && !self.force_disable_epoch_iota_conservation_check
1084 }
1085
1086 pub fn force_disable_state_consistency_check(&mut self) {
1087 self.force_disable_state_consistency_check = true;
1088 }
1089
1090 pub fn enable_state_consistency_check(&self) -> bool {
1091 (self.enable_state_consistency_check || cfg!(debug_assertions))
1092 && !self.force_disable_state_consistency_check
1093 }
1094
1095 pub fn enable_deep_per_tx_iota_conservation_check(&self) -> bool {
1096 self.enable_deep_per_tx_iota_conservation_check || cfg!(debug_assertions)
1097 }
1098
1099 pub fn enable_secondary_index_checks(&self) -> bool {
1100 self.enable_secondary_index_checks
1101 }
1102}
1103
1104fn default_checkpoint_execution_max_concurrency() -> usize {
1105 4
1106}
1107
1108fn default_local_execution_timeout_sec() -> u64 {
1109 30
1110}
1111
1112impl Default for CheckpointExecutorConfig {
1113 fn default() -> Self {
1114 Self {
1115 checkpoint_execution_max_concurrency: default_checkpoint_execution_max_concurrency(),
1116 local_execution_timeout_sec: default_local_execution_timeout_sec(),
1117 data_ingestion_dir: None,
1118 }
1119 }
1120}
1121
1122#[derive(Debug, Clone, Deserialize, Serialize)]
1123#[serde(rename_all = "kebab-case")]
1124pub struct AuthorityStorePruningConfig {
1125 #[serde(default = "default_num_latest_epoch_dbs_to_retain")]
1127 pub num_latest_epoch_dbs_to_retain: usize,
1128 #[serde(default)]
1133 pub num_epochs_to_retain: u64,
1134 #[serde(
1143 default = "default_periodic_compaction_threshold_days",
1144 skip_serializing_if = "is_default_periodic_compaction_threshold_days"
1145 )]
1146 pub periodic_compaction_threshold_days: Option<usize>,
1147 #[serde(skip_serializing_if = "Option::is_none")]
1150 pub num_epochs_to_retain_for_checkpoints: Option<u64>,
1151 #[serde(skip_serializing_if = "Option::is_none")]
1152 pub num_epochs_to_retain_for_indexes: Option<u64>,
1153}
1154
1155fn default_num_latest_epoch_dbs_to_retain() -> usize {
1156 3
1157}
1158
1159fn default_periodic_compaction_threshold_days() -> Option<usize> {
1160 Some(1)
1161}
1162
1163fn is_default_periodic_compaction_threshold_days(days: &Option<usize>) -> bool {
1164 *days == default_periodic_compaction_threshold_days()
1165}
1166
1167impl Default for AuthorityStorePruningConfig {
1168 fn default() -> Self {
1169 Self {
1170 num_latest_epoch_dbs_to_retain: default_num_latest_epoch_dbs_to_retain(),
1171 num_epochs_to_retain: 0,
1172 periodic_compaction_threshold_days: default_periodic_compaction_threshold_days(),
1173 num_epochs_to_retain_for_checkpoints: if cfg!(msim) { Some(2) } else { None },
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
1221#[derive(Debug, Clone, Deserialize, Serialize)]
1224#[serde(rename_all = "kebab-case")]
1225pub struct CheckpointArchiveConfig {
1226 pub url: String,
1228 #[serde(default = "default_checkpoint_archive_download_concurrency")]
1230 pub download_concurrency: NonZeroUsize,
1231 #[serde(default = "default_checkpoint_archive_verify_concurrency")]
1234 pub verify_concurrency: NonZeroUsize,
1235}
1236
1237#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1245#[serde(rename_all = "kebab-case")]
1246pub struct StateSnapshotConfig {
1247 #[serde(skip_serializing_if = "Option::is_none")]
1248 pub object_store_config: Option<ObjectStoreConfig>,
1249 pub concurrency: usize,
1250}
1251
1252#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1253#[serde(rename_all = "kebab-case")]
1254pub struct TransactionKeyValueStoreWriteConfig {
1255 pub aws_access_key_id: String,
1256 pub aws_secret_access_key: String,
1257 pub aws_region: String,
1258 pub table_name: String,
1259 pub bucket_name: String,
1260 pub concurrency: usize,
1261}
1262
1263#[derive(Clone, Debug, Deserialize, Serialize)]
1268#[serde(rename_all = "kebab-case")]
1269pub struct AuthorityOverloadConfig {
1270 #[serde(default = "default_max_txn_age_in_queue")]
1274 pub max_txn_age_in_queue: Duration,
1275
1276 #[serde(default = "default_overload_monitor_interval")]
1278 pub overload_monitor_interval: Duration,
1279
1280 #[serde(default = "default_execution_queue_latency_soft_limit")]
1282 pub execution_queue_latency_soft_limit: Duration,
1283
1284 #[serde(default = "default_execution_queue_latency_hard_limit")]
1287 pub execution_queue_latency_hard_limit: Duration,
1288
1289 #[serde(default = "default_max_load_shedding_percentage")]
1291 pub max_load_shedding_percentage: u32,
1292
1293 #[serde(default = "default_min_load_shedding_percentage_above_hard_limit")]
1296 pub min_load_shedding_percentage_above_hard_limit: u32,
1297
1298 #[serde(default = "default_safe_transaction_ready_rate")]
1301 pub safe_transaction_ready_rate: u32,
1302
1303 #[serde(default = "default_check_system_overload_at_signing")]
1306 pub check_system_overload_at_signing: bool,
1307
1308 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1311 pub check_system_overload_at_execution: bool,
1312
1313 #[serde(default = "default_max_transaction_manager_queue_length")]
1317 pub max_transaction_manager_queue_length: usize,
1318
1319 #[serde(default = "default_max_transaction_manager_per_object_queue_length")]
1322 pub max_transaction_manager_per_object_queue_length: usize,
1323
1324 #[serde(default = "default_max_transaction_manager_queue_length_soft_limit_pct")]
1328 pub max_transaction_manager_queue_length_soft_limit_pct: u32,
1329}
1330
1331impl AuthorityOverloadConfig {
1332 pub fn max_transaction_manager_queue_length_soft_limit_pct(&self) -> u32 {
1335 self.max_transaction_manager_queue_length_soft_limit_pct
1336 .min(100)
1337 }
1338}
1339
1340fn default_max_txn_age_in_queue() -> Duration {
1341 Duration::from_millis(500)
1342}
1343
1344fn default_overload_monitor_interval() -> Duration {
1345 Duration::from_secs(10)
1346}
1347
1348fn default_execution_queue_latency_soft_limit() -> Duration {
1349 Duration::from_secs(1)
1350}
1351
1352fn default_execution_queue_latency_hard_limit() -> Duration {
1353 Duration::from_secs(10)
1354}
1355
1356fn default_max_load_shedding_percentage() -> u32 {
1357 95
1358}
1359
1360fn default_min_load_shedding_percentage_above_hard_limit() -> u32 {
1361 50
1362}
1363
1364fn default_safe_transaction_ready_rate() -> u32 {
1365 100
1366}
1367
1368fn default_check_system_overload_at_signing() -> bool {
1369 true
1370}
1371
1372fn default_max_transaction_manager_queue_length() -> usize {
1373 100_000
1374}
1375
1376fn default_max_transaction_manager_queue_length_soft_limit_pct() -> u32 {
1377 50
1378}
1379
1380fn default_max_transaction_manager_per_object_queue_length() -> usize {
1381 20
1382}
1383
1384impl Default for AuthorityOverloadConfig {
1385 fn default() -> Self {
1386 Self {
1387 max_txn_age_in_queue: default_max_txn_age_in_queue(),
1388 overload_monitor_interval: default_overload_monitor_interval(),
1389 execution_queue_latency_soft_limit: default_execution_queue_latency_soft_limit(),
1390 execution_queue_latency_hard_limit: default_execution_queue_latency_hard_limit(),
1391 max_load_shedding_percentage: default_max_load_shedding_percentage(),
1392 min_load_shedding_percentage_above_hard_limit:
1393 default_min_load_shedding_percentage_above_hard_limit(),
1394 safe_transaction_ready_rate: default_safe_transaction_ready_rate(),
1395 check_system_overload_at_signing: true,
1396 check_system_overload_at_execution: false,
1397 max_transaction_manager_queue_length: default_max_transaction_manager_queue_length(),
1398 max_transaction_manager_queue_length_soft_limit_pct:
1399 default_max_transaction_manager_queue_length_soft_limit_pct(),
1400 max_transaction_manager_per_object_queue_length:
1401 default_max_transaction_manager_per_object_queue_length(),
1402 }
1403 }
1404}
1405
1406fn default_authority_overload_config() -> AuthorityOverloadConfig {
1407 AuthorityOverloadConfig::default()
1408}
1409
1410fn default_traffic_controller_policy_config() -> Option<PolicyConfig> {
1411 Some(PolicyConfig::default_dos_protection_policy())
1412}
1413
1414fn is_default_traffic_controller_policy_config(policy_config: &Option<PolicyConfig>) -> bool {
1415 serializes_like(policy_config, &default_traffic_controller_policy_config())
1416}
1417
1418#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1419pub struct Genesis {
1420 #[serde(flatten)]
1421 location: Option<GenesisLocation>,
1422
1423 #[serde(skip)]
1424 genesis: once_cell::sync::OnceCell<genesis::Genesis>,
1425}
1426
1427impl Genesis {
1428 pub fn new(genesis: genesis::Genesis) -> Self {
1429 Self {
1430 location: Some(GenesisLocation::InPlace {
1431 genesis: Box::new(genesis),
1432 }),
1433 genesis: Default::default(),
1434 }
1435 }
1436
1437 pub fn new_from_file<P: Into<PathBuf>>(path: P) -> Self {
1438 Self {
1439 location: Some(GenesisLocation::File {
1440 genesis_file_location: path.into(),
1441 }),
1442 genesis: Default::default(),
1443 }
1444 }
1445
1446 pub fn new_empty() -> Self {
1447 Self {
1448 location: None,
1449 genesis: Default::default(),
1450 }
1451 }
1452
1453 pub fn genesis(&self) -> Result<&genesis::Genesis> {
1454 match &self.location {
1455 Some(GenesisLocation::InPlace { genesis }) => Ok(genesis),
1456 Some(GenesisLocation::File {
1457 genesis_file_location,
1458 }) => self
1459 .genesis
1460 .get_or_try_init(|| genesis::Genesis::load(genesis_file_location)),
1461 None => anyhow::bail!("no genesis location set"),
1462 }
1463 }
1464}
1465
1466#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1467#[serde(untagged)]
1468enum GenesisLocation {
1469 InPlace {
1470 genesis: Box<genesis::Genesis>,
1471 },
1472 File {
1473 #[serde(rename = "genesis-file-location")]
1474 genesis_file_location: PathBuf,
1475 },
1476}
1477
1478#[derive(Clone, Debug, Deserialize, Serialize)]
1481pub struct KeyPairWithPath {
1482 #[serde(flatten)]
1483 location: KeyPairLocation,
1484
1485 #[serde(skip)]
1486 keypair: OnceCell<Arc<SimpleKeypair>>,
1487
1488 #[serde(skip)]
1494 ed25519_keypair: OnceCell<Arc<Ed25519KeyPair>>,
1495}
1496
1497impl PartialEq for KeyPairWithPath {
1498 fn eq(&self, other: &Self) -> bool {
1499 self.location == other.location
1500 }
1501}
1502
1503impl Eq for KeyPairWithPath {}
1504
1505#[derive(Debug, Clone, Deserialize, Serialize)]
1506#[serde(untagged)]
1507enum KeyPairLocation {
1508 InPlace {
1509 #[serde(with = "bech32_formatted_keypair")]
1510 value: Arc<SimpleKeypair>,
1511 },
1512 File {
1513 path: PathBuf,
1514 },
1515}
1516
1517impl PartialEq for KeyPairLocation {
1518 fn eq(&self, other: &Self) -> bool {
1519 match (self, other) {
1520 (Self::InPlace { value: a }, Self::InPlace { value: b }) => {
1521 a.to_bytes() == b.to_bytes()
1522 }
1523 (Self::File { path: a }, Self::File { path: b }) => a == b,
1524 _ => false,
1525 }
1526 }
1527}
1528
1529impl Eq for KeyPairLocation {}
1530
1531impl KeyPairWithPath {
1532 pub fn new(kp: SimpleKeypair) -> Self {
1533 let cell: OnceCell<Arc<SimpleKeypair>> = OnceCell::new();
1534 let arc_kp = Arc::new(kp);
1535 cell.set(arc_kp.clone()).expect("failed to set keypair");
1538 Self {
1539 location: KeyPairLocation::InPlace { value: arc_kp },
1540 keypair: cell,
1541 ed25519_keypair: OnceCell::new(),
1542 }
1543 }
1544
1545 pub fn new_from_path(path: PathBuf) -> Self {
1546 let cell: OnceCell<Arc<SimpleKeypair>> = OnceCell::new();
1547 cell.set(Arc::new(read_keypair_from_file(&path).unwrap_or_else(
1550 |e| panic!("invalid keypair file at path {path:?}: {e}"),
1551 )))
1552 .expect("failed to set keypair");
1553 Self {
1554 location: KeyPairLocation::File { path },
1555 keypair: cell,
1556 ed25519_keypair: OnceCell::new(),
1557 }
1558 }
1559
1560 pub fn keypair(&self) -> &SimpleKeypair {
1561 self.keypair
1562 .get_or_init(|| match &self.location {
1563 KeyPairLocation::InPlace { value } => value.clone(),
1564 KeyPairLocation::File { path } => {
1565 Arc::new(
1568 read_keypair_from_file(path).unwrap_or_else(|e| {
1569 panic!("invalid keypair file at path {path:?}: {e}")
1570 }),
1571 )
1572 }
1573 })
1574 .as_ref()
1575 }
1576
1577 pub fn ed25519_keypair(&self) -> &Ed25519KeyPair {
1581 self.ed25519_keypair
1582 .get_or_init(|| {
1583 Arc::new(
1584 simple_to_network_keypair(self.keypair())
1585 .expect("only Ed25519 network keys are allowed"),
1586 )
1587 })
1588 .as_ref()
1589 }
1590}
1591
1592#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
1595pub struct AuthorityKeyPairWithPath {
1596 #[serde(flatten)]
1597 location: AuthorityKeyPairLocation,
1598
1599 #[serde(skip)]
1600 keypair: OnceCell<Arc<AuthorityKeyPair>>,
1601}
1602
1603#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1604#[serde(untagged)]
1605enum AuthorityKeyPairLocation {
1606 InPlace { value: Arc<AuthorityKeyPair> },
1607 File { path: PathBuf },
1608}
1609
1610impl AuthorityKeyPairWithPath {
1611 pub fn new(kp: AuthorityKeyPair) -> Self {
1612 let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1613 let arc_kp = Arc::new(kp);
1614 cell.set(arc_kp.clone())
1617 .expect("failed to set authority keypair");
1618 Self {
1619 location: AuthorityKeyPairLocation::InPlace { value: arc_kp },
1620 keypair: cell,
1621 }
1622 }
1623
1624 pub fn new_from_path(path: PathBuf) -> Self {
1625 let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1626 cell.set(Arc::new(
1629 read_authority_keypair_from_file(&path)
1630 .unwrap_or_else(|_| panic!("invalid authority keypair file at path {path:?}")),
1631 ))
1632 .expect("failed to set authority keypair");
1633 Self {
1634 location: AuthorityKeyPairLocation::File { path },
1635 keypair: cell,
1636 }
1637 }
1638
1639 pub fn authority_keypair(&self) -> &AuthorityKeyPair {
1640 self.keypair
1641 .get_or_init(|| match &self.location {
1642 AuthorityKeyPairLocation::InPlace { value } => value.clone(),
1643 AuthorityKeyPairLocation::File { path } => {
1644 Arc::new(
1647 read_authority_keypair_from_file(path)
1648 .unwrap_or_else(|_| panic!("invalid authority keypair file {path:?}")),
1649 )
1650 }
1651 })
1652 .as_ref()
1653 }
1654}
1655
1656#[derive(Clone, Debug, Deserialize, Serialize, Default)]
1659#[serde(rename_all = "kebab-case")]
1660pub struct StateDebugDumpConfig {
1661 #[serde(skip_serializing_if = "Option::is_none")]
1662 pub dump_file_directory: Option<PathBuf>,
1663}
1664
1665#[cfg(test)]
1666mod tests {
1667 use std::path::PathBuf;
1668
1669 use fastcrypto::traits::KeyPair;
1670 use iota_keys::keypair_file::{write_authority_keypair_to_file, write_keypair_to_file};
1671 use iota_types::{
1672 crypto::{
1673 AuthorityKeyPair, NetworkKeyPair, get_key_pair_from_rng, network_to_simple_keypair,
1674 },
1675 traffic_control::{PolicyConfig, RemoteFirewallConfig},
1676 };
1677 use rand::{SeedableRng, rngs::StdRng};
1678 use serde::Serialize;
1679 use serde_yaml::Value;
1680
1681 use super::{
1682 Genesis, GrpcApiConfig, ObjectStoreConfig, default_grpc_api_config,
1683 default_periodic_compaction_threshold_days, default_traffic_controller_policy_config,
1684 };
1685 use crate::{NodeConfig, object_storage_config::ObjectStoreType};
1686
1687 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1688
1689 const POLICY_CONFIG: &[&str] = &["policy-config"];
1690 const GRPC_API_CONFIG: &[&str] = &["grpc-api-config"];
1691 const COMPACTION_THRESHOLD: &[&str] = &[
1692 "authority-store-pruning-config",
1693 "periodic-compaction-threshold-days",
1694 ];
1695
1696 fn template_config() -> NodeConfig {
1697 serde_yaml::from_str(TEMPLATE).unwrap()
1698 }
1699
1700 fn consensus_config() -> super::ConsensusConfig {
1701 serde_yaml::from_str("db-path: /opt/iota/consensus-db").unwrap()
1702 }
1703
1704 fn object_store_config() -> ObjectStoreConfig {
1705 ObjectStoreConfig {
1706 object_store: Some(ObjectStoreType::File),
1707 directory: Some(PathBuf::from("/opt/iota/snapshots")),
1708 ..Default::default()
1709 }
1710 }
1711
1712 fn round_trip(config: &NodeConfig) -> NodeConfig {
1713 serde_yaml::from_str(&serde_yaml::to_string(config).unwrap()).unwrap()
1714 }
1715
1716 fn as_yaml<T: Serialize>(value: &T) -> String {
1717 serde_yaml::to_string(value).unwrap()
1718 }
1719
1720 fn written_at(value: &Value, path: &[&str]) -> Option<Value> {
1723 let (last, parents) = path.split_last().unwrap();
1724 let mut current = value;
1725 for name in parents {
1726 current = current
1727 .as_mapping()
1728 .unwrap()
1729 .get(&Value::String((*name).to_owned()))
1730 .unwrap();
1731 }
1732 current
1733 .as_mapping()
1734 .unwrap()
1735 .get(&Value::String((*last).to_owned()))
1736 .cloned()
1737 }
1738
1739 #[test]
1740 fn serialize_genesis_from_file() {
1741 let g = Genesis::new_from_file("path/to/file");
1742
1743 let s = serde_yaml::to_string(&g).unwrap();
1744 assert_eq!("---\ngenesis-file-location: path/to/file\n", s);
1745 let loaded_genesis: Genesis = serde_yaml::from_str(&s).unwrap();
1746 assert_eq!(g, loaded_genesis);
1747 }
1748
1749 #[test]
1750 fn fullnode_template() {
1751 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1752
1753 let _template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1754 }
1755
1756 #[test]
1757 fn validate_requires_a_grpc_config_when_the_api_is_enabled() {
1758 let mut config = template_config();
1761 config.grpc_api_config = None;
1762 config.validate().unwrap();
1763
1764 config.enable_grpc_api = true;
1765 let err = config.validate().unwrap_err().to_string();
1766 assert!(err.contains("`grpc-api-config` is `null`"), "{err}");
1767
1768 config.grpc_api_config = Some(GrpcApiConfig::default());
1769 config.validate().unwrap();
1770
1771 config.grpc_api_config = None;
1774 config.consensus_config = Some(consensus_config());
1775 let err = config.validate().unwrap_err().to_string();
1776 assert!(err.contains("validators do not expose"), "{err}");
1777 }
1778
1779 #[test]
1780 fn validate_rejects_the_grpc_api_on_a_validator() {
1781 let mut config = template_config();
1782 config.consensus_config = Some(consensus_config());
1783 config.validate().unwrap();
1784
1785 config.enable_grpc_api = true;
1786 let err = config.validate().unwrap_err().to_string();
1787 assert!(err.contains("validators do not expose"), "{err}");
1788
1789 config.consensus_config = None;
1791 config.validate().unwrap();
1792 }
1793
1794 #[test]
1795 fn validate_rejects_snapshot_upload_on_a_validator() {
1796 let mut config = template_config();
1797 config.state_snapshot_write_config.object_store_config = Some(object_store_config());
1798 config.validate().unwrap();
1799
1800 config.consensus_config = Some(consensus_config());
1801 let err = config.validate().unwrap_err().to_string();
1802 assert!(err.contains("snapshot upload"), "{err}");
1803 }
1804
1805 #[test]
1806 fn validate_rejects_a_snapshot_store_without_a_backend() {
1807 let mut config = template_config();
1808 config.state_snapshot_write_config.object_store_config = Some(ObjectStoreConfig::default());
1809
1810 let err = config.validate().unwrap_err().to_string();
1811 assert!(err.contains("storage backend"), "{err}");
1812 }
1813
1814 #[test]
1815 fn validate_rejects_a_firewall_without_a_policy() {
1816 let mut config = template_config();
1817 config.firewall_config = Some(RemoteFirewallConfig {
1818 remote_fw_url: "http://localhost:65000".to_owned(),
1819 destination_port: 8080,
1820 delegate_spam_blocking: false,
1821 delegate_error_blocking: false,
1822 drain_path: PathBuf::from("/tmp/drain"),
1823 drain_timeout_secs: 300,
1824 });
1825
1826 config.validate().unwrap();
1829
1830 config.policy_config = None;
1833 let err = config.validate().unwrap_err().to_string();
1834 assert!(err.contains("`firewall-config` is set"), "{err}");
1835 }
1836
1837 #[test]
1838 fn enable_soft_locking_defaults_to_enabled() {
1839 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1842
1843 let config: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1844 assert!(config.enable_soft_locking);
1845 }
1846
1847 #[test]
1848 fn load_key_pairs_to_node_config() {
1849 let authority_key_pair: AuthorityKeyPair =
1850 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1851 let protocol_key_pair: NetworkKeyPair =
1852 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1853 let network_key_pair: NetworkKeyPair =
1854 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1855
1856 write_authority_keypair_to_file(&authority_key_pair, PathBuf::from("authority.key"))
1857 .unwrap();
1858 write_keypair_to_file(
1859 &network_to_simple_keypair(&protocol_key_pair),
1860 PathBuf::from("protocol.key"),
1861 )
1862 .unwrap();
1863 write_keypair_to_file(
1864 &network_to_simple_keypair(&network_key_pair),
1865 PathBuf::from("network.key"),
1866 )
1867 .unwrap();
1868
1869 const TEMPLATE: &str = include_str!("../data/fullnode-template-with-path.yaml");
1870 let template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1871 assert_eq!(
1872 template.authority_key_pair().public(),
1873 authority_key_pair.public()
1874 );
1875 assert_eq!(
1876 template.network_key_pair().public(),
1877 network_key_pair.public()
1878 );
1879 assert_eq!(
1880 template.protocol_key_pair().public(),
1881 protocol_key_pair.public()
1882 );
1883 }
1884
1885 #[test]
1886 fn a_policy_config_survives_a_round_trip_in_all_three_states() {
1887 let mut config = template_config();
1888
1889 config.policy_config = None;
1890 assert!(round_trip(&config).policy_config.is_none());
1891
1892 config.policy_config = default_traffic_controller_policy_config();
1893 assert_eq!(
1894 as_yaml(&round_trip(&config).policy_config),
1895 as_yaml(&default_traffic_controller_policy_config())
1896 );
1897
1898 let configured = PolicyConfig {
1899 dry_run: !PolicyConfig::default_dos_protection_policy().dry_run,
1900 ..PolicyConfig::default_dos_protection_policy()
1901 };
1902 config.policy_config = Some(configured.clone());
1903 assert_eq!(
1904 as_yaml(&round_trip(&config).policy_config),
1905 as_yaml(&Some(configured))
1906 );
1907 }
1908
1909 #[test]
1910 fn a_grpc_api_config_survives_a_round_trip_in_all_three_states() {
1911 let mut config = template_config();
1912
1913 config.grpc_api_config = None;
1914 assert!(round_trip(&config).grpc_api_config.is_none());
1915
1916 config.grpc_api_config = default_grpc_api_config();
1917 assert_eq!(
1918 as_yaml(&round_trip(&config).grpc_api_config),
1919 as_yaml(&default_grpc_api_config())
1920 );
1921
1922 let configured = GrpcApiConfig {
1923 max_message_size_bytes: 1234,
1924 ..GrpcApiConfig::default()
1925 };
1926 config.grpc_api_config = Some(configured.clone());
1927 assert_eq!(
1928 as_yaml(&round_trip(&config).grpc_api_config),
1929 as_yaml(&Some(configured))
1930 );
1931 }
1932
1933 #[test]
1934 fn the_default_pruning_config_agrees_with_the_serde_default() {
1935 assert_eq!(
1936 super::AuthorityStorePruningConfig::default().periodic_compaction_threshold_days,
1937 default_periodic_compaction_threshold_days()
1938 );
1939 }
1940
1941 #[test]
1942 fn a_compaction_threshold_survives_a_round_trip_in_all_three_states() {
1943 let mut config = template_config();
1944
1945 for state in [None, default_periodic_compaction_threshold_days(), Some(7)] {
1946 config
1947 .authority_store_pruning_config
1948 .periodic_compaction_threshold_days = state;
1949 assert_eq!(
1950 round_trip(&config)
1951 .authority_store_pruning_config
1952 .periodic_compaction_threshold_days,
1953 state
1954 );
1955 }
1956 }
1957
1958 #[test]
1959 fn a_default_value_is_omitted_and_a_disabled_one_is_written_as_null() {
1960 let mut config = template_config();
1961 config.policy_config = default_traffic_controller_policy_config();
1962 config.grpc_api_config = default_grpc_api_config();
1963 config
1964 .authority_store_pruning_config
1965 .periodic_compaction_threshold_days = default_periodic_compaction_threshold_days();
1966
1967 let written = serde_yaml::to_value(&config).unwrap();
1968 assert_eq!(written_at(&written, POLICY_CONFIG), None);
1969 assert_eq!(written_at(&written, GRPC_API_CONFIG), None);
1970 assert_eq!(written_at(&written, COMPACTION_THRESHOLD), None);
1971
1972 config.policy_config = None;
1973 config.grpc_api_config = None;
1974 config
1975 .authority_store_pruning_config
1976 .periodic_compaction_threshold_days = None;
1977
1978 let written = serde_yaml::to_value(&config).unwrap();
1979 assert_eq!(written_at(&written, POLICY_CONFIG), Some(Value::Null));
1980 assert_eq!(written_at(&written, GRPC_API_CONFIG), Some(Value::Null));
1981 assert_eq!(
1982 written_at(&written, COMPACTION_THRESHOLD),
1983 Some(Value::Null)
1984 );
1985 }
1986}
1987
1988#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
1992pub enum RunWithRange {
1993 Epoch(EpochId),
1994 Checkpoint(CheckpointSequenceNumber),
1995}
1996
1997impl RunWithRange {
1998 pub fn is_epoch_gt(&self, epoch_id: EpochId) -> bool {
2000 matches!(self, RunWithRange::Epoch(e) if epoch_id > *e)
2001 }
2002
2003 pub fn matches_checkpoint(&self, seq_num: CheckpointSequenceNumber) -> bool {
2004 matches!(self, RunWithRange::Checkpoint(seq) if *seq == seq_num)
2005 }
2006
2007 pub fn into_checkpoint_bound(self) -> Option<CheckpointSequenceNumber> {
2008 match self {
2009 RunWithRange::Epoch(_) => None,
2010 RunWithRange::Checkpoint(seq) => Some(seq),
2011 }
2012 }
2013}
2014
2015mod bech32_formatted_keypair {
2019 use std::ops::Deref;
2020
2021 use fastcrypto::encoding::{Base64, Encoding};
2022 use iota_sdk_crypto::{ToFromBech32, simple::SimpleKeypair};
2023 use serde::{Deserialize, Deserializer, Serializer};
2024
2025 pub fn serialize<S, T>(kp: &T, serializer: S) -> Result<S::Ok, S::Error>
2026 where
2027 S: Serializer,
2028 T: Deref<Target = SimpleKeypair>,
2029 {
2030 use serde::ser::Error;
2031
2032 let s = kp.to_bech32().map_err(Error::custom)?;
2034
2035 serializer.serialize_str(&s)
2036 }
2037
2038 pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
2039 where
2040 D: Deserializer<'de>,
2041 T: From<SimpleKeypair>,
2042 {
2043 use serde::de::Error;
2044
2045 let s = String::deserialize(deserializer)?;
2046
2047 SimpleKeypair::from_bech32(&s)
2049 .map_err(Error::custom)
2050 .or_else(|_: D::Error| {
2051 let bytes = Base64::decode(&s).map_err(Error::custom)?;
2053 SimpleKeypair::from_bytes(&bytes).map_err(Error::custom)
2054 })
2055 .map(Into::into)
2056 }
2057}