1use std::{
6 net::{IpAddr, Ipv4Addr, SocketAddr},
7 num::{NonZeroU32, NonZeroUsize},
8 path::{Path, PathBuf},
9 sync::Arc,
10 time::Duration,
11};
12
13use anyhow::Result;
14use iota_keys::keypair_file::{read_authority_keypair_from_file, read_keypair_from_file};
15use iota_metrics::MetricGroups;
16use iota_multiaddr::Multiaddr;
17use iota_names::config::IotaNamesConfig;
18use iota_sdk_crypto::simple::SimpleKeypair;
19use iota_sdk_types::Address;
20use iota_types::{
21 committee::EpochId,
22 crypto::{
23 AccountPrivateKey, AuthorityKeyPair, AuthorityPublicKeyBytes, KeypairTraits,
24 NetworkPrivateKey, get_key_pair_from_rng,
25 },
26 messages_checkpoint::CheckpointSequenceNumber,
27 supported_protocol_versions::{Chain, SupportedProtocolVersions},
28 traffic_control::PolicyConfig,
29};
30use once_cell::sync::OnceCell;
31use rand::{rand_core::UnwrapErr, rngs::SysRng};
32use serde::{Deserialize, Serialize};
33use starfish_config::Parameters as StarfishParameters;
34
35use crate::{
36 Config, certificate_deny_config::CertificateDenyConfig, genesis,
37 migration_tx_data::MigrationTxData, object_storage_config::ObjectStoreConfig, p2p::P2pConfig,
38 setting::Setting, transaction_deny_config::TransactionDenyConfig,
39 verifier_signing_config::VerifierSigningConfig,
40};
41
42pub const DEFAULT_VALIDATOR_GAS_PRICE: u64 = iota_types::transaction::DEFAULT_VALIDATOR_GAS_PRICE;
44
45pub const DEFAULT_COMMISSION_RATE: u64 = 200;
47
48pub const DEFAULT_FULL_CHECKPOINT_CONTENTS_CACHE_SIZE_MB: usize = 1024;
50
51#[derive(Clone, Debug, Deserialize, Serialize)]
52#[serde(rename_all = "kebab-case")]
53pub struct NodeConfig {
54 #[serde(default = "default_authority_key_pair")]
57 pub authority_key_pair: AuthorityKeyPairWithPath,
58 #[serde(default = "default_key_pair")]
61 pub protocol_key_pair: KeyPairWithPath,
62 #[serde(default = "default_key_pair")]
63 pub account_key_pair: KeyPairWithPath,
64 #[serde(default = "default_key_pair")]
67 pub network_key_pair: KeyPairWithPath,
68 pub db_path: PathBuf,
69
70 #[serde(default = "default_grpc_address")]
74 pub network_address: Multiaddr,
75 #[serde(default = "default_json_rpc_address")]
76 pub json_rpc_address: SocketAddr,
77
78 #[serde(default = "default_metrics_address")]
80 pub metrics_address: SocketAddr,
81
82 #[serde(default = "default_admin_interface_address")]
86 pub admin_interface_address: SocketAddr,
87
88 #[serde(skip_serializing_if = "Option::is_none")]
90 pub consensus_config: Option<ConsensusConfig>,
91
92 #[serde(default = "default_enable_jsonrpc_api")]
95 pub enable_jsonrpc_api: bool,
96
97 #[serde(default)]
101 pub grpc_load_shed: Option<bool>,
102
103 #[serde(default = "default_grpc_concurrency_limit_per_core")]
124 pub grpc_concurrency_limit_per_core: NonZeroUsize,
125
126 #[serde(default)]
128 pub p2p_config: P2pConfig,
129
130 pub genesis: Genesis,
134
135 pub migration_tx_data_path: Option<PathBuf>,
137
138 #[serde(default = "default_authority_store_pruning_config")]
141 pub authority_store_pruning_config: AuthorityStorePruningConfig,
142
143 #[serde(default = "default_end_of_epoch_broadcast_channel_capacity")]
148 pub end_of_epoch_broadcast_channel_capacity: usize,
149
150 #[serde(default)]
154 pub checkpoint_executor_config: CheckpointExecutorConfig,
155
156 #[serde(skip_serializing_if = "Option::is_none")]
157 pub metrics: Option<MetricsConfig>,
158
159 #[serde(skip)]
164 pub supported_protocol_versions: Option<SupportedProtocolVersions>,
165
166 #[serde(default)]
168 pub expensive_safety_check_config: ExpensiveSafetyCheckConfig,
169
170 #[serde(default)]
174 pub transaction_deny_config: TransactionDenyConfig,
175
176 #[serde(default)]
182 pub certificate_deny_config: CertificateDenyConfig,
183
184 #[serde(default)]
187 pub state_debug_dump_config: StateDebugDumpConfig,
188
189 #[serde(default)]
190 pub checkpoint_archive_config: Option<CheckpointArchiveConfig>,
191
192 #[serde(default)]
194 pub state_snapshot_write_config: StateSnapshotConfig,
195
196 #[serde(default = "default_transaction_kv_store_config")]
197 pub transaction_kv_store_read_config: TransactionKeyValueStoreReadConfig,
198
199 #[serde(skip_serializing_if = "Option::is_none")]
201 pub transaction_kv_store_write_config: Option<TransactionKeyValueStoreWriteConfig>,
202
203 #[serde(default = "default_authority_overload_config")]
206 pub authority_overload_config: AuthorityOverloadConfig,
207
208 #[serde(skip_serializing_if = "Option::is_none")]
212 pub run_with_range: Option<RunWithRange>,
213
214 #[serde(
220 skip_serializing_if = "is_default_traffic_controller_policy_config",
221 default = "default_traffic_controller_policy_config"
222 )]
223 pub policy_config: Option<PolicyConfig>,
224
225 #[serde(default)]
226 pub execution_cache_config: ExecutionCacheConfig,
227
228 #[serde(default = "default_full_checkpoint_contents_cache_size_mb")]
239 pub full_checkpoint_contents_cache_size_mb: usize,
240
241 #[serde(default = "bool_true")]
242 pub enable_validator_tx_finalizer: bool,
243
244 #[serde(default = "bool_true")]
250 pub enable_soft_locking: bool,
251
252 #[serde(default)]
253 pub verifier_signing_config: VerifierSigningConfig,
254
255 #[serde(default, skip_serializing_if = "Option::is_none")]
261 pub post_consensus_validation_readers: Option<NonZeroUsize>,
262
263 #[serde(skip_serializing_if = "Option::is_none")]
267 pub enable_db_write_stall: Option<bool>,
268
269 #[serde(default, skip_serializing_if = "Option::is_none")]
270 pub iota_names_config: Option<IotaNamesConfig>,
271
272 #[serde(default)]
274 pub enable_grpc_api: bool,
275 #[serde(
281 default = "default_grpc_api_config",
282 skip_serializing_if = "is_default_grpc_api_config"
283 )]
284 pub grpc_api_config: Option<GrpcApiConfig>,
285
286 #[serde(skip_serializing_if = "Option::is_none")]
291 pub chain_override_for_testing: Option<Chain>,
292
293 #[serde(default, skip_serializing_if = "Option::is_none")]
296 pub validator_client_monitor_config:
297 Option<crate::validator_client_monitor_config::ValidatorClientMonitorConfig>,
298
299 #[serde(default, skip_serializing_if = "ListenerLimitsConfig::is_unset")]
301 pub validator_grpc_listener_limits: ListenerLimitsConfig,
302
303 #[serde(default, skip_serializing_if = "ListenerLimitsConfig::is_unset")]
305 pub json_rpc_listener_limits: ListenerLimitsConfig,
306
307 #[serde(default, skip_serializing_if = "ListenerLimitsConfig::is_unset")]
309 pub grpc_api_listener_limits: ListenerLimitsConfig,
310}
311
312#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
318#[serde(rename_all = "kebab-case")]
319pub struct ListenerLimitsConfig {
320 #[serde(default, skip_serializing_if = "Setting::is_unset")]
323 pub handshake_timeout: Setting<Duration>,
324
325 #[serde(default, skip_serializing_if = "Setting::is_unset")]
328 pub max_pending_connections: Setting<NonZeroUsize>,
329
330 #[serde(default, skip_serializing_if = "Setting::is_unset")]
332 pub max_connections: Setting<NonZeroUsize>,
333
334 #[serde(default, skip_serializing_if = "Setting::is_unset")]
336 pub max_connections_per_client_ip: Setting<NonZeroUsize>,
337
338 #[serde(default, skip_serializing_if = "Option::is_none")]
341 pub ipv6_prefix_len: Option<u8>,
342
343 #[serde(default, skip_serializing_if = "Setting::is_unset")]
346 pub max_connection_idle: Setting<Duration>,
347
348 #[serde(default, skip_serializing_if = "Setting::is_unset")]
350 pub max_concurrent_streams: Setting<NonZeroU32>,
351
352 #[serde(default, skip_serializing_if = "Setting::is_unset")]
355 pub http2_keepalive_interval: Setting<Duration>,
356
357 #[serde(default, skip_serializing_if = "Setting::is_unset")]
360 pub http1_header_read_timeout: Setting<Duration>,
361}
362
363impl ListenerLimitsConfig {
364 pub fn is_unset(&self) -> bool {
366 *self == Self::default()
367 }
368
369 fn validate(&self, key: &str) -> Result<()> {
372 for (name, duration) in [
373 ("handshake-timeout", self.handshake_timeout),
374 ("max-connection-idle", self.max_connection_idle),
375 ("http2-keepalive-interval", self.http2_keepalive_interval),
376 ("http1-header-read-timeout", self.http1_header_read_timeout),
377 ] {
378 if duration == Setting::Value(Duration::ZERO) {
379 anyhow::bail!(
380 "`{key}.{name}` is 0; set it greater than zero, or to `null` to turn it off"
381 );
382 }
383 }
384 if self.handshake_timeout == Setting::Disabled
387 && self.max_pending_connections != Setting::Disabled
388 {
389 anyhow::bail!(
390 "`{key}.handshake-timeout` is `null`, but `max-pending-connections` is on, and \
391 only the handshake timeout frees its slots; set a handshake timeout, or set \
392 `max-pending-connections` to `null` too"
393 );
394 }
395 if let Some(len) = self
396 .ipv6_prefix_len
397 .filter(|len| !(MIN_IPV6_PREFIX_LEN..=128).contains(len))
398 {
399 anyhow::bail!(
400 "`{key}.ipv6-prefix-len` is {len}; set it between {MIN_IPV6_PREFIX_LEN} and 128"
401 );
402 }
403 Ok(())
404 }
405}
406
407const MIN_IPV6_PREFIX_LEN: u8 = 32;
409
410#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
411#[serde(rename_all = "kebab-case")]
412pub struct TlsConfig {
413 cert: String,
415 key: String,
417}
418
419impl TlsConfig {
420 pub fn cert(&self) -> &str {
421 &self.cert
422 }
423
424 pub fn key(&self) -> &str {
425 &self.key
426 }
427}
428
429#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
431#[serde(rename_all = "kebab-case")]
432pub struct GrpcApiConfig {
433 #[serde(default = "default_grpc_api_address")]
435 pub address: SocketAddr,
436
437 #[serde(skip_serializing_if = "Option::is_none")]
441 pub tls: Option<TlsConfig>,
442
443 #[serde(default = "default_grpc_api_max_message_size_bytes")]
445 pub max_message_size_bytes: u32,
446
447 #[serde(default = "default_grpc_api_broadcast_buffer_size")]
449 pub broadcast_buffer_size: u32,
450
451 #[serde(default = "default_grpc_api_max_concurrent_stream_subscribers")]
457 pub max_concurrent_stream_subscribers: u32,
458
459 #[serde(default = "default_grpc_api_max_json_move_value_size")]
462 pub max_json_move_value_size: usize,
463
464 #[serde(default = "default_grpc_api_max_execute_transaction_batch_size")]
467 pub max_execute_transaction_batch_size: u32,
468
469 #[serde(default = "default_grpc_api_max_simulate_transaction_batch_size")]
472 pub max_simulate_transaction_batch_size: u32,
473
474 #[serde(default = "default_grpc_api_max_get_objects_batch_size")]
476 pub max_get_objects_batch_size: u32,
477
478 #[serde(default = "default_grpc_api_max_get_transactions_batch_size")]
481 pub max_get_transactions_batch_size: u32,
482
483 #[serde(default = "default_grpc_api_max_view_function_call_batch_size")]
486 pub max_view_function_call_batch_size: u32,
487
488 #[serde(default = "default_grpc_api_max_checkpoint_inclusion_timeout_ms")]
492 pub max_checkpoint_inclusion_timeout_ms: u64,
493}
494
495fn default_grpc_api_address() -> SocketAddr {
496 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 50051)
497}
498
499fn default_grpc_api_broadcast_buffer_size() -> u32 {
500 100
501}
502
503fn default_grpc_api_max_concurrent_stream_subscribers() -> u32 {
504 1024
505}
506
507fn default_grpc_api_max_message_size_bytes() -> u32 {
508 128 * 1024 * 1024 }
510
511fn default_grpc_api_max_json_move_value_size() -> usize {
512 1024 * 1024 }
514
515fn default_grpc_api_max_execute_transaction_batch_size() -> u32 {
516 20
517}
518
519fn default_grpc_api_max_simulate_transaction_batch_size() -> u32 {
520 20
521}
522
523fn default_grpc_api_max_get_objects_batch_size() -> u32 {
524 1000
525}
526
527fn default_grpc_api_max_get_transactions_batch_size() -> u32 {
528 1000
529}
530
531fn default_grpc_api_max_view_function_call_batch_size() -> u32 {
532 20
533}
534
535fn default_grpc_api_max_checkpoint_inclusion_timeout_ms() -> u64 {
536 60_000 }
538
539impl Default for GrpcApiConfig {
540 fn default() -> Self {
541 Self {
542 address: default_grpc_api_address(),
543 tls: None,
544 max_message_size_bytes: default_grpc_api_max_message_size_bytes(),
545 broadcast_buffer_size: default_grpc_api_broadcast_buffer_size(),
546 max_concurrent_stream_subscribers: default_grpc_api_max_concurrent_stream_subscribers(),
547 max_json_move_value_size: default_grpc_api_max_json_move_value_size(),
548 max_execute_transaction_batch_size: default_grpc_api_max_execute_transaction_batch_size(
549 ),
550 max_simulate_transaction_batch_size:
551 default_grpc_api_max_simulate_transaction_batch_size(),
552 max_get_objects_batch_size: default_grpc_api_max_get_objects_batch_size(),
553 max_get_transactions_batch_size: default_grpc_api_max_get_transactions_batch_size(),
554 max_view_function_call_batch_size: default_grpc_api_max_view_function_call_batch_size(),
555 max_checkpoint_inclusion_timeout_ms:
556 default_grpc_api_max_checkpoint_inclusion_timeout_ms(),
557 }
558 }
559}
560
561impl GrpcApiConfig {
562 const GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE: u32 = 4 * 1024 * 1024; const GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES: u32 =
566 Self::GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE;
567
568 pub fn tls_config(&self) -> Option<&TlsConfig> {
569 self.tls.as_ref()
570 }
571
572 pub fn max_message_size_bytes(&self) -> u32 {
573 self.max_message_size_bytes
575 .max(Self::GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES)
576 }
577
578 pub fn max_message_size_client_bytes(&self, client_max_message_size_bytes: Option<u32>) -> u32 {
582 client_max_message_size_bytes
583 .unwrap_or(Self::GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE)
586 .clamp(
588 Self::GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES,
589 self.max_message_size_bytes(),
590 )
591 }
592}
593
594#[derive(Clone, Debug, Default, Deserialize, Serialize)]
595#[serde(rename_all = "kebab-case")]
596pub struct ExecutionCacheConfig {
597 #[serde(default)]
598 pub writeback_cache: WritebackCacheConfig,
599}
600
601#[derive(Clone, Debug, Default, Deserialize, Serialize)]
602#[serde(rename_all = "kebab-case")]
603pub struct WritebackCacheConfig {
604 #[serde(default, skip_serializing_if = "Option::is_none")]
607 pub max_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
610 pub package_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
613 pub object_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
615 pub marker_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
617 pub object_by_id_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
620 pub transaction_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
622 pub executed_effect_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
624 pub effect_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
627 pub events_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
630 pub transaction_objects_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
635 pub backpressure_threshold: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
641 pub backpressure_threshold_for_rpc: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
651 pub backpressure_soft_limit_pct: Option<u32>,
652}
653
654impl WritebackCacheConfig {
655 pub fn max_cache_size(&self) -> u64 {
656 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_MAX")
657 .ok()
658 .and_then(|s| s.parse().ok())
659 .or(self.max_cache_size)
660 .unwrap_or(100000)
661 }
662
663 pub fn package_cache_size(&self) -> u64 {
664 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_PACKAGE")
665 .ok()
666 .and_then(|s| s.parse().ok())
667 .or(self.package_cache_size)
668 .unwrap_or(1000)
669 }
670
671 pub fn object_cache_size(&self) -> u64 {
672 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_OBJECT")
673 .ok()
674 .and_then(|s| s.parse().ok())
675 .or(self.object_cache_size)
676 .unwrap_or_else(|| self.max_cache_size())
677 }
678
679 pub fn marker_cache_size(&self) -> u64 {
680 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_MARKER")
681 .ok()
682 .and_then(|s| s.parse().ok())
683 .or(self.marker_cache_size)
684 .unwrap_or_else(|| self.object_cache_size())
685 }
686
687 pub fn object_by_id_cache_size(&self) -> u64 {
688 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_OBJECT_BY_ID")
689 .ok()
690 .and_then(|s| s.parse().ok())
691 .or(self.object_by_id_cache_size)
692 .unwrap_or_else(|| self.object_cache_size())
693 }
694
695 pub fn transaction_cache_size(&self) -> u64 {
696 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_TRANSACTION")
697 .ok()
698 .and_then(|s| s.parse().ok())
699 .or(self.transaction_cache_size)
700 .unwrap_or_else(|| self.max_cache_size())
701 }
702
703 pub fn executed_effect_cache_size(&self) -> u64 {
704 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EXECUTED_EFFECT")
705 .ok()
706 .and_then(|s| s.parse().ok())
707 .or(self.executed_effect_cache_size)
708 .unwrap_or_else(|| self.transaction_cache_size())
709 }
710
711 pub fn effect_cache_size(&self) -> u64 {
712 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EFFECT")
713 .ok()
714 .and_then(|s| s.parse().ok())
715 .or(self.effect_cache_size)
716 .unwrap_or_else(|| self.executed_effect_cache_size())
717 }
718
719 pub fn events_cache_size(&self) -> u64 {
720 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EVENTS")
721 .ok()
722 .and_then(|s| s.parse().ok())
723 .or(self.events_cache_size)
724 .unwrap_or_else(|| self.transaction_cache_size())
725 }
726
727 pub fn transaction_objects_cache_size(&self) -> u64 {
728 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_TRANSACTION_OBJECTS")
729 .ok()
730 .and_then(|s| s.parse().ok())
731 .or(self.transaction_objects_cache_size)
732 .unwrap_or(1000)
733 }
734
735 pub fn backpressure_threshold(&self) -> u64 {
736 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_THRESHOLD")
737 .ok()
738 .and_then(|s| s.parse().ok())
739 .or(self.backpressure_threshold)
740 .unwrap_or(100_000)
741 }
742
743 pub fn backpressure_threshold_for_rpc(&self) -> u64 {
744 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_THRESHOLD_FOR_RPC")
745 .ok()
746 .and_then(|s| s.parse().ok())
747 .or(self.backpressure_threshold_for_rpc)
748 .unwrap_or(self.backpressure_threshold())
749 }
750
751 pub fn backpressure_soft_limit_pct(&self) -> u32 {
752 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_SOFT_LIMIT_PCT")
753 .ok()
754 .and_then(|s| s.parse().ok())
755 .or(self.backpressure_soft_limit_pct)
756 .unwrap_or(50)
757 .min(100)
758 }
759}
760
761#[derive(Clone, Debug, Deserialize, Serialize)]
762#[serde(rename_all = "kebab-case")]
763pub struct TransactionKeyValueStoreReadConfig {
764 #[serde(default = "default_base_url")]
765 pub base_url: String,
766
767 #[serde(default = "default_cache_size")]
768 pub cache_size: u64,
769}
770
771impl Default for TransactionKeyValueStoreReadConfig {
772 fn default() -> Self {
773 Self {
774 base_url: default_base_url(),
775 cache_size: default_cache_size(),
776 }
777 }
778}
779
780fn default_base_url() -> String {
781 "".to_string()
782}
783
784fn default_cache_size() -> u64 {
785 100_000
786}
787
788fn default_transaction_kv_store_config() -> TransactionKeyValueStoreReadConfig {
789 TransactionKeyValueStoreReadConfig::default()
790}
791
792fn default_authority_store_pruning_config() -> AuthorityStorePruningConfig {
793 AuthorityStorePruningConfig::default()
794}
795
796pub fn default_enable_jsonrpc_api() -> bool {
797 true
798}
799
800fn default_grpc_address() -> Multiaddr {
801 "/ip4/0.0.0.0/tcp/8080".parse().unwrap()
802}
803fn default_authority_key_pair() -> AuthorityKeyPairWithPath {
804 AuthorityKeyPairWithPath::new(
805 get_key_pair_from_rng::<AuthorityKeyPair, _>(&mut UnwrapErr(SysRng)).1,
806 )
807}
808
809fn default_key_pair() -> KeyPairWithPath {
810 KeyPairWithPath::new(AccountPrivateKey::random().into())
811}
812
813fn default_metrics_address() -> SocketAddr {
814 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9184)
815}
816
817pub fn default_admin_interface_address() -> SocketAddr {
818 SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 1337)
819}
820
821pub fn default_json_rpc_address() -> SocketAddr {
822 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9000)
823}
824
825pub fn default_grpc_api_config() -> Option<GrpcApiConfig> {
826 Some(GrpcApiConfig::default())
827}
828
829fn is_default_grpc_api_config(grpc_api_config: &Option<GrpcApiConfig>) -> bool {
830 serializes_like(grpc_api_config, &default_grpc_api_config())
831}
832
833fn serializes_like<T: Serialize>(value: &T, default: &T) -> bool {
839 match (serde_yaml::to_string(value), serde_yaml::to_string(default)) {
840 (Ok(value), Ok(default)) => value == default,
841 _ => false,
842 }
843}
844
845pub fn default_grpc_concurrency_limit_per_core() -> NonZeroUsize {
846 NonZeroUsize::new(1000).unwrap()
847}
848
849pub fn default_end_of_epoch_broadcast_channel_capacity() -> usize {
850 128
851}
852
853pub fn default_full_checkpoint_contents_cache_size_mb() -> usize {
854 DEFAULT_FULL_CHECKPOINT_CONTENTS_CACHE_SIZE_MB
855}
856
857pub fn bool_true() -> bool {
858 true
859}
860
861impl Config for NodeConfig {}
862
863impl NodeConfig {
864 pub fn authority_key_pair(&self) -> &AuthorityKeyPair {
865 self.authority_key_pair.authority_keypair()
866 }
867
868 pub fn protocol_private_key(&self) -> NetworkPrivateKey {
869 self.protocol_key_pair.network_private_key()
870 }
871
872 pub fn network_private_key(&self) -> NetworkPrivateKey {
873 self.network_key_pair.network_private_key()
874 }
875
876 pub fn authority_public_key(&self) -> AuthorityPublicKeyBytes {
877 self.authority_key_pair().public().into()
878 }
879
880 pub fn db_path(&self) -> PathBuf {
881 self.db_path.join("live")
882 }
883
884 pub fn snapshot_path(&self) -> PathBuf {
885 self.db_path.join("snapshot")
886 }
887
888 pub fn network_address(&self) -> &Multiaddr {
889 &self.network_address
890 }
891
892 pub fn consensus_config(&self) -> Option<&ConsensusConfig> {
893 self.consensus_config.as_ref()
894 }
895
896 pub fn maintains_rpc_indexes(&self) -> bool {
899 self.consensus_config().is_none() && (self.enable_jsonrpc_api || self.enable_grpc_api)
900 }
901
902 pub fn genesis(&self) -> Result<&genesis::Genesis> {
903 self.genesis.genesis()
904 }
905
906 pub fn load_migration_tx_data(&self) -> Result<MigrationTxData> {
907 let Some(location) = &self.migration_tx_data_path else {
908 anyhow::bail!("no file location set");
909 };
910
911 let migration_tx_data = MigrationTxData::load(location)?;
913
914 migration_tx_data.validate_from_genesis(self.genesis.genesis()?)?;
916 Ok(migration_tx_data)
917 }
918
919 pub fn iota_address(&self) -> Address {
920 self.account_key_pair
921 .keypair()
922 .public_key()
923 .derive_address()
924 }
925
926 pub fn checkpoint_archive_config(&self) -> Option<&CheckpointArchiveConfig> {
927 self.checkpoint_archive_config.as_ref()
928 }
929
930 pub fn is_validator(&self) -> bool {
933 self.consensus_config.is_some()
934 }
935
936 pub fn validate(&self) -> Result<()> {
940 if self.is_validator() {
943 if self.enable_grpc_api {
944 anyhow::bail!(
945 "`enable-grpc-api` is set, but validators do not expose the gRPC API; turn \
946 it off, or move the API to a fullnode"
947 );
948 }
949 if self
950 .state_snapshot_write_config
951 .object_store_config
952 .is_some()
953 {
954 anyhow::bail!(
955 "`state-snapshot-write-config.object-store-config` is set, but snapshot \
956 upload is only supported on fullnodes; remove the setting or move the \
957 upload to a fullnode"
958 );
959 }
960 }
961 if self.enable_grpc_api && self.grpc_api_config.is_none() {
965 anyhow::bail!(
966 "`enable-grpc-api` is set but `grpc-api-config` is `null`; give it a value, \
967 remove the key to take the default config, or turn off `enable-grpc-api`"
968 );
969 }
970 if self
972 .state_snapshot_write_config
973 .object_store_config
974 .as_ref()
975 .is_some_and(|store| store.object_store.is_none())
976 {
977 anyhow::bail!(
978 "`state-snapshot-write-config.object-store-config` has no `object-store`; \
979 snapshot upload needs a storage backend"
980 );
981 }
982 if self
986 .authority_store_pruning_config
987 .num_epochs_to_retain_for_checkpoints()
988 == Some(0)
989 {
990 anyhow::bail!(
991 "`num-epochs-to-retain-for-checkpoints` is 0, but the previous epoch's \
992 checkpoints are still needed after an epoch boundary; set it to 1 or more"
993 );
994 }
995 for (key, limits) in [
998 (
999 "validator-grpc-listener-limits",
1000 &self.validator_grpc_listener_limits,
1001 ),
1002 ("json-rpc-listener-limits", &self.json_rpc_listener_limits),
1003 ("grpc-api-listener-limits", &self.grpc_api_listener_limits),
1004 ] {
1005 limits.validate(key)?;
1006 }
1007 Ok(())
1008 }
1009}
1010
1011#[derive(Debug, Clone, Deserialize, Serialize)]
1012#[serde(rename_all = "kebab-case")]
1013pub struct ConsensusConfig {
1014 pub db_path: PathBuf,
1016
1017 pub db_retention_epochs: Option<u64>,
1021
1022 pub db_pruner_period_secs: Option<u64>,
1026
1027 pub max_pending_transactions: Option<usize>,
1042
1043 pub max_submit_position: Option<usize>,
1049
1050 pub submit_delay_step_override_millis: Option<u64>,
1056
1057 #[serde(skip_serializing_if = "Option::is_none", alias = "starfish_parameters")]
1059 pub parameters: Option<StarfishParameters>,
1060
1061 #[serde(skip_serializing_if = "Option::is_none")]
1067 pub graduated_load_shedding_soft_limit_pct: Option<u32>,
1068}
1069
1070impl ConsensusConfig {
1071 pub fn db_path(&self) -> &Path {
1072 &self.db_path
1073 }
1074
1075 pub fn max_pending_transactions(&self) -> usize {
1083 self.max_pending_transactions.unwrap_or(20_000)
1084 }
1085
1086 pub fn graduated_load_shedding_soft_limit_pct(&self) -> u32 {
1091 self.graduated_load_shedding_soft_limit_pct
1092 .unwrap_or(50)
1093 .min(100)
1094 }
1095
1096 pub fn submit_delay_step_override(&self) -> Option<Duration> {
1097 self.submit_delay_step_override_millis
1098 .map(Duration::from_millis)
1099 }
1100
1101 pub fn db_retention_epochs(&self) -> u64 {
1102 self.db_retention_epochs.unwrap_or(0)
1103 }
1104
1105 pub fn db_pruner_period(&self) -> Duration {
1106 self.db_pruner_period_secs
1108 .map(Duration::from_secs)
1109 .unwrap_or(Duration::from_secs(3_600))
1110 }
1111}
1112
1113#[derive(Clone, Debug, Deserialize, Serialize)]
1114#[serde(rename_all = "kebab-case")]
1115pub struct CheckpointExecutorConfig {
1116 #[serde(default = "default_checkpoint_execution_max_concurrency")]
1121 pub checkpoint_execution_max_concurrency: usize,
1122
1123 #[serde(default = "default_local_execution_timeout_sec")]
1129 pub local_execution_timeout_sec: u64,
1130
1131 #[serde(default, skip_serializing_if = "Option::is_none")]
1136 pub data_ingestion_dir: Option<PathBuf>,
1137}
1138
1139#[derive(Clone, Debug, Default, Deserialize, Serialize)]
1140#[serde(rename_all = "kebab-case")]
1141pub struct ExpensiveSafetyCheckConfig {
1142 #[serde(default)]
1147 enable_epoch_iota_conservation_check: bool,
1148
1149 #[serde(default)]
1153 enable_deep_per_tx_iota_conservation_check: bool,
1154
1155 #[serde(default)]
1158 force_disable_epoch_iota_conservation_check: bool,
1159
1160 #[serde(default)]
1163 enable_state_consistency_check: bool,
1164
1165 #[serde(default)]
1167 force_disable_state_consistency_check: bool,
1168}
1169
1170impl ExpensiveSafetyCheckConfig {
1171 pub fn new_enable_all() -> Self {
1172 Self {
1173 enable_epoch_iota_conservation_check: true,
1174 enable_deep_per_tx_iota_conservation_check: true,
1175 force_disable_epoch_iota_conservation_check: false,
1176 enable_state_consistency_check: true,
1177 force_disable_state_consistency_check: false,
1178 }
1179 }
1180
1181 pub fn new_disable_all() -> Self {
1182 Self {
1183 enable_epoch_iota_conservation_check: false,
1184 enable_deep_per_tx_iota_conservation_check: false,
1185 force_disable_epoch_iota_conservation_check: true,
1186 enable_state_consistency_check: false,
1187 force_disable_state_consistency_check: true,
1188 }
1189 }
1190
1191 pub fn force_disable_epoch_iota_conservation_check(&mut self) {
1192 self.force_disable_epoch_iota_conservation_check = true;
1193 }
1194
1195 pub fn enable_epoch_iota_conservation_check(&self) -> bool {
1196 (self.enable_epoch_iota_conservation_check || cfg!(debug_assertions))
1197 && !self.force_disable_epoch_iota_conservation_check
1198 }
1199
1200 pub fn force_disable_state_consistency_check(&mut self) {
1201 self.force_disable_state_consistency_check = true;
1202 }
1203
1204 pub fn enable_state_consistency_check(&self) -> bool {
1205 (self.enable_state_consistency_check || cfg!(debug_assertions))
1206 && !self.force_disable_state_consistency_check
1207 }
1208
1209 pub fn enable_deep_per_tx_iota_conservation_check(&self) -> bool {
1210 self.enable_deep_per_tx_iota_conservation_check || cfg!(debug_assertions)
1211 }
1212}
1213
1214fn default_checkpoint_execution_max_concurrency() -> usize {
1215 4
1216}
1217
1218fn default_local_execution_timeout_sec() -> u64 {
1219 30
1220}
1221
1222impl Default for CheckpointExecutorConfig {
1223 fn default() -> Self {
1224 Self {
1225 checkpoint_execution_max_concurrency: default_checkpoint_execution_max_concurrency(),
1226 local_execution_timeout_sec: default_local_execution_timeout_sec(),
1227 data_ingestion_dir: None,
1228 }
1229 }
1230}
1231
1232#[derive(Debug, Clone, Deserialize, Serialize)]
1233#[serde(rename_all = "kebab-case")]
1234pub struct AuthorityStorePruningConfig {
1235 #[serde(default = "default_num_latest_epoch_dbs_to_retain")]
1237 pub num_latest_epoch_dbs_to_retain: usize,
1238 #[serde(default)]
1244 pub num_epochs_to_retain: u64,
1245 #[serde(
1254 default = "default_periodic_compaction_threshold_days",
1255 skip_serializing_if = "is_default_periodic_compaction_threshold_days"
1256 )]
1257 pub periodic_compaction_threshold_days: Option<usize>,
1258 #[serde(skip_serializing_if = "Option::is_none")]
1267 pub num_epochs_to_retain_for_checkpoints: Option<u64>,
1268 #[serde(skip_serializing_if = "Option::is_none")]
1280 pub num_epochs_to_retain_for_indexes: Option<u64>,
1281}
1282
1283pub const DEFAULT_NUM_EPOCHS_TO_RETAIN_FOR_CHECKPOINTS: u64 = 30;
1287
1288fn default_num_latest_epoch_dbs_to_retain() -> usize {
1289 3
1290}
1291
1292fn default_periodic_compaction_threshold_days() -> Option<usize> {
1293 Some(1)
1294}
1295
1296fn is_default_periodic_compaction_threshold_days(days: &Option<usize>) -> bool {
1297 *days == default_periodic_compaction_threshold_days()
1298}
1299
1300impl Default for AuthorityStorePruningConfig {
1301 fn default() -> Self {
1302 Self {
1303 num_latest_epoch_dbs_to_retain: default_num_latest_epoch_dbs_to_retain(),
1304 num_epochs_to_retain: 0,
1305 periodic_compaction_threshold_days: default_periodic_compaction_threshold_days(),
1306 num_epochs_to_retain_for_checkpoints: if cfg!(msim) { Some(2) } else { None },
1307 num_epochs_to_retain_for_indexes: None,
1308 }
1309 }
1310}
1311
1312impl AuthorityStorePruningConfig {
1313 pub fn set_num_epochs_to_retain(&mut self, num_epochs_to_retain: u64) {
1314 self.num_epochs_to_retain = num_epochs_to_retain;
1315 }
1316
1317 pub fn set_num_epochs_to_retain_for_checkpoints(&mut self, num_epochs_to_retain: Option<u64>) {
1318 self.num_epochs_to_retain_for_checkpoints = num_epochs_to_retain;
1319 }
1320
1321 pub fn num_epochs_to_retain(&self) -> Option<u64> {
1324 (self.num_epochs_to_retain != u64::MAX).then_some(self.num_epochs_to_retain)
1325 }
1326
1327 pub fn num_epochs_to_retain_for_checkpoints(&self) -> Option<u64> {
1332 match self.num_epochs_to_retain_for_checkpoints {
1333 Some(u64::MAX) => None,
1334 Some(n) => Some(n),
1335 None => Some(DEFAULT_NUM_EPOCHS_TO_RETAIN_FOR_CHECKPOINTS),
1336 }
1337 }
1338
1339 pub fn num_epochs_to_retain_for_indexes(&self) -> Option<u64> {
1343 match self.num_epochs_to_retain_for_indexes {
1344 Some(n) if n == u64::MAX => None,
1345 Some(n) => Some(n),
1346 None => self.num_epochs_to_retain_for_checkpoints(),
1347 }
1348 }
1349
1350 pub fn check_index_retention_within_ledger(&self) -> Result<()> {
1354 let Some(ledger) = self.num_epochs_to_retain_for_checkpoints() else {
1355 return Ok(());
1357 };
1358 let index = self.num_epochs_to_retain_for_indexes();
1359 if index.is_none_or(|index| index > ledger) {
1360 let index = index.map_or("unlimited".to_owned(), |index| index.to_string());
1361 anyhow::bail!(
1362 "num-epochs-to-retain-for-indexes ({index}) must not exceed \
1363 num-epochs-to-retain-for-checkpoints ({ledger}): a longer index retention \
1364 lets iotax_queryTransactionBlocks return a transaction digest whose ledger \
1365 data has already been pruned. Lower num-epochs-to-retain-for-indexes or \
1366 raise num-epochs-to-retain-for-checkpoints."
1367 );
1368 }
1369 Ok(())
1370 }
1371}
1372
1373#[derive(Debug, Clone, Deserialize, Serialize)]
1374#[serde(rename_all = "kebab-case")]
1375pub struct MetricsConfig {
1376 #[serde(skip_serializing_if = "Option::is_none")]
1377 pub push_interval_seconds: Option<u64>,
1378 #[serde(skip_serializing_if = "Option::is_none")]
1379 pub push_url: Option<String>,
1380 #[serde(skip_serializing_if = "Option::is_none")]
1381 pub groups: Option<MetricGroups>,
1382}
1383
1384fn default_checkpoint_archive_download_concurrency() -> NonZeroUsize {
1385 NonZeroUsize::new(10).unwrap()
1386}
1387
1388fn default_checkpoint_archive_verify_concurrency() -> NonZeroUsize {
1389 std::thread::available_parallelism().unwrap_or(NonZeroUsize::new(4).unwrap())
1390}
1391
1392#[derive(Debug, Clone, Deserialize, Serialize)]
1395#[serde(rename_all = "kebab-case")]
1396pub struct CheckpointArchiveConfig {
1397 pub url: String,
1399 #[serde(default = "default_checkpoint_archive_download_concurrency")]
1401 pub download_concurrency: NonZeroUsize,
1402 #[serde(default = "default_checkpoint_archive_verify_concurrency")]
1405 pub verify_concurrency: NonZeroUsize,
1406}
1407
1408#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1416#[serde(rename_all = "kebab-case")]
1417pub struct StateSnapshotConfig {
1418 #[serde(skip_serializing_if = "Option::is_none")]
1419 pub object_store_config: Option<ObjectStoreConfig>,
1420 pub concurrency: usize,
1421}
1422
1423#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1424#[serde(rename_all = "kebab-case")]
1425pub struct TransactionKeyValueStoreWriteConfig {
1426 pub aws_access_key_id: String,
1427 pub aws_secret_access_key: String,
1428 pub aws_region: String,
1429 pub table_name: String,
1430 pub bucket_name: String,
1431 pub concurrency: usize,
1432}
1433
1434#[derive(Clone, Debug, Deserialize, Serialize)]
1439#[serde(rename_all = "kebab-case")]
1440pub struct AuthorityOverloadConfig {
1441 #[serde(default = "default_max_txn_age_in_queue")]
1445 pub max_txn_age_in_queue: Duration,
1446
1447 #[serde(default = "default_overload_monitor_interval")]
1449 pub overload_monitor_interval: Duration,
1450
1451 #[serde(default = "default_execution_queue_latency_soft_limit")]
1453 pub execution_queue_latency_soft_limit: Duration,
1454
1455 #[serde(default = "default_execution_queue_latency_hard_limit")]
1458 pub execution_queue_latency_hard_limit: Duration,
1459
1460 #[serde(default = "default_max_load_shedding_percentage")]
1462 pub max_load_shedding_percentage: u32,
1463
1464 #[serde(default = "default_min_load_shedding_percentage_above_hard_limit")]
1467 pub min_load_shedding_percentage_above_hard_limit: u32,
1468
1469 #[serde(default = "default_safe_transaction_ready_rate")]
1472 pub safe_transaction_ready_rate: u32,
1473
1474 #[serde(default = "default_check_system_overload_at_signing")]
1478 pub check_system_overload_at_signing: bool,
1479
1480 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1483 pub check_system_overload_at_execution: bool,
1484
1485 #[serde(default = "default_max_transaction_manager_queue_length")]
1489 pub max_transaction_manager_queue_length: usize,
1490
1491 #[serde(default = "default_max_transaction_manager_per_object_queue_length")]
1494 pub max_transaction_manager_per_object_queue_length: usize,
1495
1496 #[serde(default = "default_max_transaction_manager_queue_length_soft_limit_pct")]
1500 pub max_transaction_manager_queue_length_soft_limit_pct: u32,
1501
1502 #[serde(default, skip_serializing_if = "Option::is_none")]
1505 pub max_concurrent_attestations: Option<NonZeroUsize>,
1506
1507 #[serde(default, skip_serializing_if = "Option::is_none")]
1514 pub max_queued_attestations: Option<usize>,
1515
1516 #[serde(default, skip_serializing_if = "Option::is_none")]
1524 pub max_attestation_wait: Option<Duration>,
1525}
1526
1527impl AuthorityOverloadConfig {
1528 pub fn max_transaction_manager_queue_length_soft_limit_pct(&self) -> u32 {
1531 self.max_transaction_manager_queue_length_soft_limit_pct
1532 .min(100)
1533 }
1534}
1535
1536fn default_max_txn_age_in_queue() -> Duration {
1537 Duration::from_millis(500)
1538}
1539
1540fn default_overload_monitor_interval() -> Duration {
1541 Duration::from_secs(10)
1542}
1543
1544fn default_execution_queue_latency_soft_limit() -> Duration {
1545 Duration::from_secs(1)
1546}
1547
1548fn default_execution_queue_latency_hard_limit() -> Duration {
1549 Duration::from_secs(10)
1550}
1551
1552fn default_max_load_shedding_percentage() -> u32 {
1553 95
1554}
1555
1556fn default_min_load_shedding_percentage_above_hard_limit() -> u32 {
1557 50
1558}
1559
1560fn default_safe_transaction_ready_rate() -> u32 {
1561 100
1562}
1563
1564fn default_check_system_overload_at_signing() -> bool {
1565 true
1566}
1567
1568fn default_max_transaction_manager_queue_length() -> usize {
1569 100_000
1570}
1571
1572fn default_max_transaction_manager_queue_length_soft_limit_pct() -> u32 {
1573 50
1574}
1575
1576fn default_max_transaction_manager_per_object_queue_length() -> usize {
1577 20
1578}
1579
1580impl Default for AuthorityOverloadConfig {
1581 fn default() -> Self {
1582 Self {
1583 max_txn_age_in_queue: default_max_txn_age_in_queue(),
1584 overload_monitor_interval: default_overload_monitor_interval(),
1585 execution_queue_latency_soft_limit: default_execution_queue_latency_soft_limit(),
1586 execution_queue_latency_hard_limit: default_execution_queue_latency_hard_limit(),
1587 max_load_shedding_percentage: default_max_load_shedding_percentage(),
1588 min_load_shedding_percentage_above_hard_limit:
1589 default_min_load_shedding_percentage_above_hard_limit(),
1590 safe_transaction_ready_rate: default_safe_transaction_ready_rate(),
1591 check_system_overload_at_signing: true,
1592 check_system_overload_at_execution: false,
1593 max_transaction_manager_queue_length: default_max_transaction_manager_queue_length(),
1594 max_transaction_manager_queue_length_soft_limit_pct:
1595 default_max_transaction_manager_queue_length_soft_limit_pct(),
1596 max_transaction_manager_per_object_queue_length:
1597 default_max_transaction_manager_per_object_queue_length(),
1598 max_concurrent_attestations: None,
1599 max_queued_attestations: None,
1600 max_attestation_wait: None,
1601 }
1602 }
1603}
1604
1605fn default_authority_overload_config() -> AuthorityOverloadConfig {
1606 AuthorityOverloadConfig::default()
1607}
1608
1609fn default_traffic_controller_policy_config() -> Option<PolicyConfig> {
1610 Some(PolicyConfig::default_dos_protection_policy())
1611}
1612
1613fn is_default_traffic_controller_policy_config(policy_config: &Option<PolicyConfig>) -> bool {
1614 serializes_like(policy_config, &default_traffic_controller_policy_config())
1615}
1616
1617#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1618pub struct Genesis {
1619 #[serde(flatten)]
1620 location: Option<GenesisLocation>,
1621
1622 #[serde(skip)]
1623 genesis: once_cell::sync::OnceCell<genesis::Genesis>,
1624}
1625
1626impl Genesis {
1627 pub fn new(genesis: genesis::Genesis) -> Self {
1628 Self {
1629 location: Some(GenesisLocation::InPlace {
1630 genesis: Box::new(genesis),
1631 }),
1632 genesis: Default::default(),
1633 }
1634 }
1635
1636 pub fn new_from_file<P: Into<PathBuf>>(path: P) -> Self {
1637 Self {
1638 location: Some(GenesisLocation::File {
1639 genesis_file_location: path.into(),
1640 }),
1641 genesis: Default::default(),
1642 }
1643 }
1644
1645 pub fn new_empty() -> Self {
1646 Self {
1647 location: None,
1648 genesis: Default::default(),
1649 }
1650 }
1651
1652 pub fn genesis(&self) -> Result<&genesis::Genesis> {
1653 match &self.location {
1654 Some(GenesisLocation::InPlace { genesis }) => Ok(genesis),
1655 Some(GenesisLocation::File {
1656 genesis_file_location,
1657 }) => self
1658 .genesis
1659 .get_or_try_init(|| genesis::Genesis::load(genesis_file_location)),
1660 None => anyhow::bail!("no genesis location set"),
1661 }
1662 }
1663}
1664
1665#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1666#[serde(untagged)]
1667enum GenesisLocation {
1668 InPlace {
1669 genesis: Box<genesis::Genesis>,
1670 },
1671 File {
1672 #[serde(rename = "genesis-file-location")]
1673 genesis_file_location: PathBuf,
1674 },
1675}
1676
1677#[derive(Clone, Debug, Deserialize, Serialize)]
1680pub struct KeyPairWithPath {
1681 #[serde(flatten)]
1682 location: KeyPairLocation,
1683
1684 #[serde(skip)]
1685 keypair: OnceCell<Arc<SimpleKeypair>>,
1686}
1687
1688impl PartialEq for KeyPairWithPath {
1689 fn eq(&self, other: &Self) -> bool {
1690 self.location == other.location
1691 }
1692}
1693
1694impl Eq for KeyPairWithPath {}
1695
1696#[derive(Debug, Clone, Deserialize, Serialize)]
1697#[serde(untagged)]
1698enum KeyPairLocation {
1699 InPlace {
1700 #[serde(with = "bech32_formatted_keypair")]
1701 value: Arc<SimpleKeypair>,
1702 },
1703 File {
1704 path: PathBuf,
1705 },
1706}
1707
1708impl PartialEq for KeyPairLocation {
1709 fn eq(&self, other: &Self) -> bool {
1710 match (self, other) {
1711 (Self::InPlace { value: a }, Self::InPlace { value: b }) => {
1712 a.to_bytes() == b.to_bytes()
1713 }
1714 (Self::File { path: a }, Self::File { path: b }) => a == b,
1715 _ => false,
1716 }
1717 }
1718}
1719
1720impl Eq for KeyPairLocation {}
1721
1722impl KeyPairWithPath {
1723 pub fn new(kp: SimpleKeypair) -> Self {
1724 let cell: OnceCell<Arc<SimpleKeypair>> = OnceCell::new();
1725 let arc_kp = Arc::new(kp);
1726 cell.set(arc_kp.clone()).expect("failed to set keypair");
1729 Self {
1730 location: KeyPairLocation::InPlace { value: arc_kp },
1731 keypair: cell,
1732 }
1733 }
1734
1735 pub fn new_from_path(path: PathBuf) -> Self {
1736 let cell: OnceCell<Arc<SimpleKeypair>> = OnceCell::new();
1737 cell.set(Arc::new(read_keypair_from_file(&path).unwrap_or_else(
1740 |e| panic!("invalid keypair file at path {path:?}: {e}"),
1741 )))
1742 .expect("failed to set keypair");
1743 Self {
1744 location: KeyPairLocation::File { path },
1745 keypair: cell,
1746 }
1747 }
1748
1749 pub fn keypair(&self) -> &SimpleKeypair {
1750 self.keypair
1751 .get_or_init(|| match &self.location {
1752 KeyPairLocation::InPlace { value } => value.clone(),
1753 KeyPairLocation::File { path } => {
1754 Arc::new(
1757 read_keypair_from_file(path).unwrap_or_else(|e| {
1758 panic!("invalid keypair file at path {path:?}: {e}")
1759 }),
1760 )
1761 }
1762 })
1763 .as_ref()
1764 }
1765
1766 pub fn network_private_key(&self) -> NetworkPrivateKey {
1770 self.keypair()
1771 .as_opt_ed25519()
1772 .cloned()
1773 .expect("only Ed25519 network keys are allowed")
1774 }
1775}
1776
1777#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
1780pub struct AuthorityKeyPairWithPath {
1781 #[serde(flatten)]
1782 location: AuthorityKeyPairLocation,
1783
1784 #[serde(skip)]
1785 keypair: OnceCell<Arc<AuthorityKeyPair>>,
1786}
1787
1788#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1789#[serde(untagged)]
1790enum AuthorityKeyPairLocation {
1791 InPlace { value: Arc<AuthorityKeyPair> },
1792 File { path: PathBuf },
1793}
1794
1795impl AuthorityKeyPairWithPath {
1796 pub fn new(kp: AuthorityKeyPair) -> Self {
1797 let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1798 let arc_kp = Arc::new(kp);
1799 cell.set(arc_kp.clone())
1802 .expect("failed to set authority keypair");
1803 Self {
1804 location: AuthorityKeyPairLocation::InPlace { value: arc_kp },
1805 keypair: cell,
1806 }
1807 }
1808
1809 pub fn new_from_path(path: PathBuf) -> Self {
1810 let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1811 cell.set(Arc::new(
1814 read_authority_keypair_from_file(&path)
1815 .unwrap_or_else(|_| panic!("invalid authority keypair file at path {path:?}")),
1816 ))
1817 .expect("failed to set authority keypair");
1818 Self {
1819 location: AuthorityKeyPairLocation::File { path },
1820 keypair: cell,
1821 }
1822 }
1823
1824 pub fn authority_keypair(&self) -> &AuthorityKeyPair {
1825 self.keypair
1826 .get_or_init(|| match &self.location {
1827 AuthorityKeyPairLocation::InPlace { value } => value.clone(),
1828 AuthorityKeyPairLocation::File { path } => {
1829 Arc::new(
1832 read_authority_keypair_from_file(path)
1833 .unwrap_or_else(|_| panic!("invalid authority keypair file {path:?}")),
1834 )
1835 }
1836 })
1837 .as_ref()
1838 }
1839}
1840
1841#[derive(Clone, Debug, Deserialize, Serialize, Default)]
1844#[serde(rename_all = "kebab-case")]
1845pub struct StateDebugDumpConfig {
1846 #[serde(skip_serializing_if = "Option::is_none")]
1847 pub dump_file_directory: Option<PathBuf>,
1848}
1849
1850#[cfg(test)]
1851mod tests {
1852 use std::{
1853 num::{NonZeroU32, NonZeroUsize},
1854 path::PathBuf,
1855 time::Duration,
1856 };
1857
1858 use fastcrypto::traits::KeyPair;
1859 use iota_keys::keypair_file::{write_authority_keypair_to_file, write_keypair_to_file};
1860 use iota_sdk_crypto::simple::SimpleKeypair;
1861 use iota_types::{
1862 crypto::{AuthorityKeyPair, NetworkPrivateKey, get_key_pair_from_rng},
1863 traffic_control::PolicyConfig,
1864 };
1865 use rand::{SeedableRng, rngs::StdRng};
1866 use serde::Serialize;
1867 use serde_yaml::Value;
1868
1869 use super::{
1870 AuthorityStorePruningConfig, DEFAULT_NUM_EPOCHS_TO_RETAIN_FOR_CHECKPOINTS, Genesis,
1871 GrpcApiConfig, ListenerLimitsConfig, ObjectStoreConfig, default_grpc_api_config,
1872 default_periodic_compaction_threshold_days, default_traffic_controller_policy_config,
1873 };
1874 use crate::{
1875 ConsensusConfig, NodeConfig, object_storage_config::ObjectStoreType, setting::Setting,
1876 };
1877
1878 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1879
1880 const POLICY_CONFIG: &[&str] = &["policy-config"];
1881 const GRPC_API_CONFIG: &[&str] = &["grpc-api-config"];
1882 const COMPACTION_THRESHOLD: &[&str] = &[
1883 "authority-store-pruning-config",
1884 "periodic-compaction-threshold-days",
1885 ];
1886
1887 fn template_config() -> NodeConfig {
1888 serde_yaml::from_str(TEMPLATE).unwrap()
1889 }
1890
1891 fn consensus_config() -> super::ConsensusConfig {
1892 serde_yaml::from_str("db-path: /opt/iota/consensus-db").unwrap()
1893 }
1894
1895 fn object_store_config() -> ObjectStoreConfig {
1896 ObjectStoreConfig {
1897 object_store: Some(ObjectStoreType::File),
1898 directory: Some(PathBuf::from("/opt/iota/snapshots")),
1899 ..Default::default()
1900 }
1901 }
1902
1903 fn round_trip(config: &NodeConfig) -> NodeConfig {
1904 serde_yaml::from_str(&serde_yaml::to_string(config).unwrap()).unwrap()
1905 }
1906
1907 fn as_yaml<T: Serialize>(value: &T) -> String {
1908 serde_yaml::to_string(value).unwrap()
1909 }
1910
1911 fn written_at(value: &Value, path: &[&str]) -> Option<Value> {
1914 let (last, parents) = path.split_last().unwrap();
1915 let mut current = value;
1916 for name in parents {
1917 current = current
1918 .as_mapping()
1919 .unwrap()
1920 .get(&Value::String((*name).to_owned()))
1921 .unwrap();
1922 }
1923 current
1924 .as_mapping()
1925 .unwrap()
1926 .get(&Value::String((*last).to_owned()))
1927 .cloned()
1928 }
1929
1930 #[test]
1931 fn a_retention_below_two_is_no_longer_rounded_up() {
1932 let config = AuthorityStorePruningConfig {
1933 num_epochs_to_retain_for_checkpoints: Some(1),
1934 ..Default::default()
1935 };
1936 assert_eq!(config.num_epochs_to_retain_for_checkpoints(), Some(1));
1937 }
1938
1939 #[test]
1940 fn index_retention_within_ledger_retention_is_accepted() {
1941 let config = AuthorityStorePruningConfig {
1942 num_epochs_to_retain_for_checkpoints: Some(2),
1943 num_epochs_to_retain_for_indexes: Some(2),
1944 ..Default::default()
1945 };
1946 assert!(config.check_index_retention_within_ledger().is_ok());
1947 }
1948
1949 #[test]
1950 fn index_retention_beyond_ledger_retention_is_refused() {
1951 let config = AuthorityStorePruningConfig {
1952 num_epochs_to_retain_for_checkpoints: Some(2),
1953 num_epochs_to_retain_for_indexes: Some(3),
1954 ..Default::default()
1955 };
1956 let err = config
1957 .check_index_retention_within_ledger()
1958 .unwrap_err()
1959 .to_string();
1960 assert!(err.contains("num-epochs-to-retain-for-indexes"), "{err}");
1961 assert!(
1962 err.contains("num-epochs-to-retain-for-checkpoints"),
1963 "{err}"
1964 );
1965 assert!(err.contains('3'), "{err}");
1966 assert!(err.contains('2'), "{err}");
1967 }
1968
1969 #[test]
1970 fn the_narrowest_ledger_retention_refuses_a_longer_index_retention() {
1971 let config = AuthorityStorePruningConfig {
1972 num_epochs_to_retain_for_checkpoints: Some(1),
1973 num_epochs_to_retain_for_indexes: Some(2),
1974 ..Default::default()
1975 };
1976 assert!(config.check_index_retention_within_ledger().is_err());
1977 }
1978
1979 #[test]
1980 fn equal_narrowest_retentions_are_accepted() {
1981 let config = AuthorityStorePruningConfig {
1982 num_epochs_to_retain_for_checkpoints: Some(1),
1983 num_epochs_to_retain_for_indexes: Some(1),
1984 ..Default::default()
1985 };
1986 assert!(config.check_index_retention_within_ledger().is_ok());
1987 }
1988
1989 #[test]
1990 fn unbounded_ledger_retention_accepts_any_index_retention() {
1991 let config = AuthorityStorePruningConfig {
1992 num_epochs_to_retain_for_checkpoints: Some(u64::MAX),
1993 num_epochs_to_retain_for_indexes: Some(1000),
1994 ..Default::default()
1995 };
1996 assert!(config.check_index_retention_within_ledger().is_ok());
1997 }
1998
1999 #[test]
2000 fn unset_ledger_retention_keeps_the_default_and_the_index_follows_it() {
2001 let config = AuthorityStorePruningConfig {
2002 num_epochs_to_retain_for_checkpoints: None,
2003 num_epochs_to_retain_for_indexes: None,
2004 ..Default::default()
2005 };
2006 assert_eq!(
2007 config.num_epochs_to_retain_for_checkpoints(),
2008 Some(DEFAULT_NUM_EPOCHS_TO_RETAIN_FOR_CHECKPOINTS)
2009 );
2010 assert_eq!(
2011 config.num_epochs_to_retain_for_indexes(),
2012 Some(DEFAULT_NUM_EPOCHS_TO_RETAIN_FOR_CHECKPOINTS)
2013 );
2014 assert!(config.check_index_retention_within_ledger().is_ok());
2015 }
2016
2017 #[test]
2018 fn unset_index_retention_follows_the_ledger() {
2019 let config = AuthorityStorePruningConfig {
2020 num_epochs_to_retain_for_checkpoints: Some(3),
2021 num_epochs_to_retain_for_indexes: None,
2022 ..Default::default()
2023 };
2024 assert_eq!(config.num_epochs_to_retain_for_indexes(), Some(3));
2025 assert!(config.check_index_retention_within_ledger().is_ok());
2026 }
2027
2028 #[test]
2029 fn index_pruning_turned_off_against_a_bounded_ledger_is_refused() {
2030 let config = AuthorityStorePruningConfig {
2032 num_epochs_to_retain_for_checkpoints: Some(2),
2033 num_epochs_to_retain_for_indexes: Some(u64::MAX),
2034 ..Default::default()
2035 };
2036 let err = config
2037 .check_index_retention_within_ledger()
2038 .unwrap_err()
2039 .to_string();
2040 assert!(err.contains("unlimited"), "{err}");
2041 }
2042
2043 #[test]
2044 fn max_retention_means_pruning_is_off_for_every_knob() {
2045 let config = AuthorityStorePruningConfig {
2046 num_epochs_to_retain: u64::MAX,
2047 num_epochs_to_retain_for_checkpoints: Some(u64::MAX),
2048 num_epochs_to_retain_for_indexes: Some(u64::MAX),
2049 ..Default::default()
2050 };
2051 assert_eq!(config.num_epochs_to_retain(), None);
2052 assert_eq!(config.num_epochs_to_retain_for_checkpoints(), None);
2053 assert_eq!(config.num_epochs_to_retain_for_indexes(), None);
2054 }
2055
2056 #[test]
2057 fn a_fullnode_serving_an_api_builds_the_indexes() {
2058 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
2059
2060 let config: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
2061 assert!(config.maintains_rpc_indexes());
2062 }
2063
2064 #[test]
2065 fn a_fullnode_with_both_apis_off_builds_no_indexes() {
2066 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
2067
2068 let mut config: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
2069 config.enable_jsonrpc_api = false;
2070 config.enable_grpc_api = false;
2071 assert!(!config.maintains_rpc_indexes());
2072 }
2073
2074 #[test]
2075 fn a_validator_builds_no_indexes_even_with_an_api_enabled() {
2076 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
2077
2078 let mut config: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
2079 config.enable_jsonrpc_api = true;
2080 config.consensus_config = Some(ConsensusConfig {
2081 db_path: PathBuf::from("/tmp/consensus"),
2082 db_retention_epochs: None,
2083 db_pruner_period_secs: None,
2084 max_pending_transactions: None,
2085 max_submit_position: None,
2086 submit_delay_step_override_millis: None,
2087 parameters: None,
2088 graduated_load_shedding_soft_limit_pct: None,
2089 });
2090 assert!(!config.maintains_rpc_indexes());
2091 }
2092
2093 #[test]
2094 fn serialize_genesis_from_file() {
2095 let g = Genesis::new_from_file("path/to/file");
2096
2097 let s = serde_yaml::to_string(&g).unwrap();
2098 assert_eq!("---\ngenesis-file-location: path/to/file\n", s);
2099 let loaded_genesis: Genesis = serde_yaml::from_str(&s).unwrap();
2100 assert_eq!(g, loaded_genesis);
2101 }
2102
2103 #[test]
2104 fn fullnode_template() {
2105 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
2106
2107 let _template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
2108 }
2109
2110 #[test]
2111 fn validate_requires_a_grpc_config_when_the_api_is_enabled() {
2112 let mut config = template_config();
2115 config.grpc_api_config = None;
2116 config.validate().unwrap();
2117
2118 config.enable_grpc_api = true;
2119 let err = config.validate().unwrap_err().to_string();
2120 assert!(err.contains("`grpc-api-config` is `null`"), "{err}");
2121
2122 config.grpc_api_config = Some(GrpcApiConfig::default());
2123 config.validate().unwrap();
2124
2125 config.grpc_api_config = None;
2128 config.consensus_config = Some(consensus_config());
2129 let err = config.validate().unwrap_err().to_string();
2130 assert!(err.contains("validators do not expose"), "{err}");
2131 }
2132
2133 #[test]
2134 fn validate_rejects_the_grpc_api_on_a_validator() {
2135 let mut config = template_config();
2136 config.consensus_config = Some(consensus_config());
2137 config.validate().unwrap();
2138
2139 config.enable_grpc_api = true;
2140 let err = config.validate().unwrap_err().to_string();
2141 assert!(err.contains("validators do not expose"), "{err}");
2142
2143 config.consensus_config = None;
2145 config.validate().unwrap();
2146 }
2147
2148 #[test]
2149 fn validate_rejects_snapshot_upload_on_a_validator() {
2150 let mut config = template_config();
2151 config.state_snapshot_write_config.object_store_config = Some(object_store_config());
2152 config.validate().unwrap();
2153
2154 config.consensus_config = Some(consensus_config());
2155 let err = config.validate().unwrap_err().to_string();
2156 assert!(err.contains("snapshot upload"), "{err}");
2157 }
2158
2159 #[test]
2160 fn validate_rejects_a_snapshot_store_without_a_backend() {
2161 let mut config = template_config();
2162 config.state_snapshot_write_config.object_store_config = Some(ObjectStoreConfig::default());
2163
2164 let err = config.validate().unwrap_err().to_string();
2165 assert!(err.contains("storage backend"), "{err}");
2166 }
2167
2168 #[test]
2169 fn validate_rejects_a_zero_checkpoint_retention() {
2170 let mut config = template_config();
2171 config
2172 .authority_store_pruning_config
2173 .set_num_epochs_to_retain_for_checkpoints(Some(0));
2174 let err = config.validate().unwrap_err().to_string();
2175 assert!(
2176 err.contains("num-epochs-to-retain-for-checkpoints"),
2177 "{err}"
2178 );
2179
2180 config
2181 .authority_store_pruning_config
2182 .set_num_epochs_to_retain_for_checkpoints(Some(1));
2183 config.validate().unwrap();
2184 }
2185
2186 const LISTENER_LIMITS_KEYS: [&str; 3] = [
2188 "validator-grpc-listener-limits",
2189 "json-rpc-listener-limits",
2190 "grpc-api-listener-limits",
2191 ];
2192
2193 fn config_with_listener_limits(key: &str, limits: &str) -> NodeConfig {
2195 serde_yaml::from_str(&format!("{TEMPLATE}\n{key}: {limits}\n")).unwrap()
2196 }
2197
2198 #[test]
2204 fn validate_rejects_a_handshake_timeout_turned_off_alone() {
2205 for key in LISTENER_LIMITS_KEYS {
2206 for limits in [
2207 "{handshake-timeout: null}",
2208 "{handshake-timeout: null, max-pending-connections: 1}",
2209 ] {
2210 let err = config_with_listener_limits(key, limits)
2211 .validate()
2212 .unwrap_err()
2213 .to_string();
2214 assert!(
2215 err.contains(&format!("`{key}.handshake-timeout` is `null`")),
2216 "{limits}: {err}"
2217 );
2218 }
2219 config_with_listener_limits(
2220 key,
2221 "{handshake-timeout: null, max-pending-connections: null}",
2222 )
2223 .validate()
2224 .unwrap();
2225 }
2226 }
2227
2228 #[test]
2231 fn validate_rejects_a_zero_listener_duration() {
2232 for key in LISTENER_LIMITS_KEYS {
2233 for name in [
2234 "handshake-timeout",
2235 "max-connection-idle",
2236 "http2-keepalive-interval",
2237 "http1-header-read-timeout",
2238 ] {
2239 let err =
2240 config_with_listener_limits(key, &format!("{{{name}: {{secs: 0, nanos: 0}}}}"))
2241 .validate()
2242 .unwrap_err()
2243 .to_string();
2244 assert!(err.contains(&format!("`{key}.{name}` is 0")), "{err}");
2245
2246 config_with_listener_limits(key, &format!("{{{name}: {{secs: 1, nanos: 0}}}}"))
2247 .validate()
2248 .unwrap();
2249 }
2250 }
2251 }
2252
2253 #[test]
2255 fn validate_rejects_an_ipv6_prefix_len_out_of_range() {
2256 for key in LISTENER_LIMITS_KEYS {
2257 for len in [0, 31, 129] {
2258 let err = config_with_listener_limits(key, &format!("{{ipv6-prefix-len: {len}}}"))
2259 .validate()
2260 .unwrap_err()
2261 .to_string();
2262 assert!(
2263 err.contains(&format!("`{key}.ipv6-prefix-len` is {len}")),
2264 "{err}"
2265 );
2266 }
2267 for len in [32, 128] {
2268 config_with_listener_limits(key, &format!("{{ipv6-prefix-len: {len}}}"))
2269 .validate()
2270 .unwrap();
2271 }
2272 }
2273 }
2274
2275 #[test]
2276 fn enable_soft_locking_defaults_to_enabled() {
2277 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
2280
2281 let config: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
2282 assert!(config.enable_soft_locking);
2283 }
2284
2285 #[test]
2286 fn load_key_pairs_to_node_config() {
2287 let authority_key_pair: AuthorityKeyPair =
2288 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
2289 let protocol_private_key: NetworkPrivateKey =
2290 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
2291 let network_private_key: NetworkPrivateKey =
2292 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
2293
2294 write_authority_keypair_to_file(&authority_key_pair, PathBuf::from("authority.key"))
2295 .unwrap();
2296 write_keypair_to_file(
2297 &SimpleKeypair::from(protocol_private_key.clone()),
2298 PathBuf::from("protocol.key"),
2299 )
2300 .unwrap();
2301 write_keypair_to_file(
2302 &SimpleKeypair::from(network_private_key.clone()),
2303 PathBuf::from("network.key"),
2304 )
2305 .unwrap();
2306
2307 const TEMPLATE: &str = include_str!("../data/fullnode-template-with-path.yaml");
2308 let template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
2309 assert_eq!(
2310 template.authority_key_pair().public(),
2311 authority_key_pair.public()
2312 );
2313 assert_eq!(
2314 template.network_private_key().public_key(),
2315 network_private_key.public_key()
2316 );
2317 assert_eq!(
2318 template.protocol_private_key().public_key(),
2319 protocol_private_key.public_key()
2320 );
2321 }
2322
2323 #[test]
2324 fn a_policy_config_survives_a_round_trip_in_all_three_states() {
2325 let mut config = template_config();
2326
2327 config.policy_config = None;
2328 assert!(round_trip(&config).policy_config.is_none());
2329
2330 config.policy_config = default_traffic_controller_policy_config();
2331 assert_eq!(
2332 as_yaml(&round_trip(&config).policy_config),
2333 as_yaml(&default_traffic_controller_policy_config())
2334 );
2335
2336 let configured = PolicyConfig {
2337 dry_run: !PolicyConfig::default_dos_protection_policy().dry_run,
2338 ..PolicyConfig::default_dos_protection_policy()
2339 };
2340 config.policy_config = Some(configured.clone());
2341 assert_eq!(
2342 as_yaml(&round_trip(&config).policy_config),
2343 as_yaml(&Some(configured))
2344 );
2345 }
2346
2347 #[test]
2348 fn a_grpc_api_config_survives_a_round_trip_in_all_three_states() {
2349 let mut config = template_config();
2350
2351 config.grpc_api_config = None;
2352 assert!(round_trip(&config).grpc_api_config.is_none());
2353
2354 config.grpc_api_config = default_grpc_api_config();
2355 assert_eq!(
2356 as_yaml(&round_trip(&config).grpc_api_config),
2357 as_yaml(&default_grpc_api_config())
2358 );
2359
2360 let configured = GrpcApiConfig {
2361 max_message_size_bytes: 1234,
2362 ..GrpcApiConfig::default()
2363 };
2364 config.grpc_api_config = Some(configured.clone());
2365 assert_eq!(
2366 as_yaml(&round_trip(&config).grpc_api_config),
2367 as_yaml(&Some(configured))
2368 );
2369 }
2370
2371 #[test]
2372 fn the_default_pruning_config_agrees_with_the_serde_default() {
2373 assert_eq!(
2374 super::AuthorityStorePruningConfig::default().periodic_compaction_threshold_days,
2375 default_periodic_compaction_threshold_days()
2376 );
2377 }
2378
2379 #[test]
2380 fn a_compaction_threshold_survives_a_round_trip_in_all_three_states() {
2381 let mut config = template_config();
2382
2383 for state in [None, default_periodic_compaction_threshold_days(), Some(7)] {
2384 config
2385 .authority_store_pruning_config
2386 .periodic_compaction_threshold_days = state;
2387 assert_eq!(
2388 round_trip(&config)
2389 .authority_store_pruning_config
2390 .periodic_compaction_threshold_days,
2391 state
2392 );
2393 }
2394 }
2395
2396 #[test]
2397 fn a_default_value_is_omitted_and_a_disabled_one_is_written_as_null() {
2398 let mut config = template_config();
2399 config.policy_config = default_traffic_controller_policy_config();
2400 config.grpc_api_config = default_grpc_api_config();
2401 config
2402 .authority_store_pruning_config
2403 .periodic_compaction_threshold_days = default_periodic_compaction_threshold_days();
2404
2405 let written = serde_yaml::to_value(&config).unwrap();
2406 assert_eq!(written_at(&written, POLICY_CONFIG), None);
2407 assert_eq!(written_at(&written, GRPC_API_CONFIG), None);
2408 assert_eq!(written_at(&written, COMPACTION_THRESHOLD), None);
2409
2410 config.policy_config = None;
2411 config.grpc_api_config = None;
2412 config
2413 .authority_store_pruning_config
2414 .periodic_compaction_threshold_days = None;
2415
2416 let written = serde_yaml::to_value(&config).unwrap();
2417 assert_eq!(written_at(&written, POLICY_CONFIG), Some(Value::Null));
2418 assert_eq!(written_at(&written, GRPC_API_CONFIG), Some(Value::Null));
2419 assert_eq!(
2420 written_at(&written, COMPACTION_THRESHOLD),
2421 Some(Value::Null)
2422 );
2423 }
2424
2425 fn limits(yaml: &str) -> ListenerLimitsConfig {
2426 serde_yaml::from_str(yaml).unwrap()
2427 }
2428
2429 #[test]
2430 fn a_node_config_without_listener_limits_leaves_every_limit_unset() {
2431 let config = template_config();
2432 assert_eq!(
2433 config.validator_grpc_listener_limits,
2434 ListenerLimitsConfig::default()
2435 );
2436 assert_eq!(
2437 config.json_rpc_listener_limits,
2438 ListenerLimitsConfig::default()
2439 );
2440 assert_eq!(
2441 config.grpc_api_listener_limits,
2442 ListenerLimitsConfig::default()
2443 );
2444 }
2445
2446 #[test]
2447 fn a_listener_limit_left_out_is_unset_and_null_disables_it() {
2448 assert_eq!(
2449 limits("max-connections: 30\nmax-connection-idle: null"),
2450 ListenerLimitsConfig {
2451 max_connections: Setting::Value(NonZeroUsize::new(30).unwrap()),
2452 max_connection_idle: Setting::Disabled,
2453 ..Default::default()
2454 }
2455 );
2456 }
2457
2458 #[test]
2460 fn every_listener_limit_is_read_from_its_own_key() {
2461 let read = limits(
2462 "
2463 handshake-timeout: {secs: 1, nanos: 0}
2464 max-pending-connections: 2
2465 max-connections: 3
2466 max-connections-per-client-ip: 4
2467 ipv6-prefix-len: 48
2468 max-connection-idle: {secs: 5, nanos: 0}
2469 max-concurrent-streams: 6
2470 http2-keepalive-interval: {secs: 7, nanos: 0}
2471 http1-header-read-timeout: {secs: 8, nanos: 0}
2472 ",
2473 );
2474 assert_eq!(
2475 read,
2476 ListenerLimitsConfig {
2477 handshake_timeout: Setting::Value(Duration::from_secs(1)),
2478 max_pending_connections: Setting::Value(NonZeroUsize::new(2).unwrap()),
2479 max_connections: Setting::Value(NonZeroUsize::new(3).unwrap()),
2480 max_connections_per_client_ip: Setting::Value(NonZeroUsize::new(4).unwrap()),
2481 ipv6_prefix_len: Some(48),
2482 max_connection_idle: Setting::Value(Duration::from_secs(5)),
2483 max_concurrent_streams: Setting::Value(NonZeroU32::new(6).unwrap()),
2484 http2_keepalive_interval: Setting::Value(Duration::from_secs(7)),
2485 http1_header_read_timeout: Setting::Value(Duration::from_secs(8)),
2486 }
2487 );
2488 }
2489
2490 #[test]
2491 fn every_listener_limit_can_be_disabled() {
2492 let read = limits(
2493 "
2494 handshake-timeout: null
2495 max-pending-connections: null
2496 max-connections: null
2497 max-connections-per-client-ip: null
2498 ipv6-prefix-len: null
2499 max-connection-idle: null
2500 max-concurrent-streams: null
2501 http2-keepalive-interval: null
2502 http1-header-read-timeout: null
2503 ",
2504 );
2505 assert_eq!(
2506 read,
2507 ListenerLimitsConfig {
2508 handshake_timeout: Setting::Disabled,
2509 max_pending_connections: Setting::Disabled,
2510 max_connections: Setting::Disabled,
2511 max_connections_per_client_ip: Setting::Disabled,
2512 ipv6_prefix_len: None,
2513 max_connection_idle: Setting::Disabled,
2514 max_concurrent_streams: Setting::Disabled,
2515 http2_keepalive_interval: Setting::Disabled,
2516 http1_header_read_timeout: Setting::Disabled,
2517 }
2518 );
2519 }
2520
2521 #[test]
2522 fn listener_limits_are_written_only_when_set() {
2523 let mut config = template_config();
2524 let written = serde_yaml::to_value(&config).unwrap();
2525 for key in [
2526 "validator-grpc-listener-limits",
2527 "json-rpc-listener-limits",
2528 "grpc-api-listener-limits",
2529 ] {
2530 assert_eq!(written_at(&written, &[key]), None, "{key} was written");
2531 }
2532
2533 config.json_rpc_listener_limits.max_connections = Setting::Value(NonZeroUsize::MIN);
2534 config.grpc_api_listener_limits.max_connection_idle = Setting::Disabled;
2535 let read_back = round_trip(&config);
2536 assert_eq!(
2537 read_back.json_rpc_listener_limits,
2538 config.json_rpc_listener_limits
2539 );
2540 assert_eq!(
2541 read_back.grpc_api_listener_limits,
2542 config.grpc_api_listener_limits
2543 );
2544 assert!(read_back.validator_grpc_listener_limits.is_unset());
2545 }
2546
2547 #[test]
2550 fn config_with_zero_concurrent_attestations_fails_to_load() {
2551 let zero = serde_yaml::from_str::<super::AuthorityOverloadConfig>(
2552 "max-concurrent-attestations: 0",
2553 );
2554 assert!(zero.is_err(), "{zero:?}");
2555
2556 let one: super::AuthorityOverloadConfig =
2557 serde_yaml::from_str("max-concurrent-attestations: 1").unwrap();
2558 assert_eq!(one.max_concurrent_attestations, NonZeroUsize::new(1));
2559 }
2560}
2561
2562#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
2566pub enum RunWithRange {
2567 Epoch(EpochId),
2568 Checkpoint(CheckpointSequenceNumber),
2569}
2570
2571impl RunWithRange {
2572 pub fn is_epoch_gt(&self, epoch_id: EpochId) -> bool {
2574 matches!(self, RunWithRange::Epoch(e) if epoch_id > *e)
2575 }
2576
2577 pub fn matches_checkpoint(&self, seq_num: CheckpointSequenceNumber) -> bool {
2578 matches!(self, RunWithRange::Checkpoint(seq) if *seq == seq_num)
2579 }
2580
2581 pub fn into_checkpoint_bound(self) -> Option<CheckpointSequenceNumber> {
2582 match self {
2583 RunWithRange::Epoch(_) => None,
2584 RunWithRange::Checkpoint(seq) => Some(seq),
2585 }
2586 }
2587}
2588
2589mod bech32_formatted_keypair {
2593 use std::ops::Deref;
2594
2595 use fastcrypto::encoding::{Base64, Encoding};
2596 use iota_sdk_crypto::{ToFromBech32, simple::SimpleKeypair};
2597 use serde::{Deserialize, Deserializer, Serializer};
2598
2599 pub fn serialize<S, T>(kp: &T, serializer: S) -> Result<S::Ok, S::Error>
2600 where
2601 S: Serializer,
2602 T: Deref<Target = SimpleKeypair>,
2603 {
2604 use serde::ser::Error;
2605
2606 let s = kp.to_bech32().map_err(Error::custom)?;
2608
2609 serializer.serialize_str(&s)
2610 }
2611
2612 pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
2613 where
2614 D: Deserializer<'de>,
2615 T: From<SimpleKeypair>,
2616 {
2617 use serde::de::Error;
2618
2619 let s = String::deserialize(deserializer)?;
2620
2621 SimpleKeypair::from_bech32(&s)
2623 .map_err(Error::custom)
2624 .or_else(|_: D::Error| {
2625 let bytes = Base64::decode(&s).map_err(Error::custom)?;
2627 SimpleKeypair::from_bytes(&bytes).map_err(Error::custom)
2628 })
2629 .map(Into::into)
2630 }
2631}