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_names::config::IotaNamesConfig;
18use iota_sdk_crypto::simple::SimpleKeypair;
19use iota_sdk_types::Address;
20use iota_types::{
21 committee::EpochId,
22 crypto::{
23 AccountKeyPair, AuthorityKeyPair, AuthorityPublicKeyBytes, KeypairTraits, NetworkKeyPair,
24 get_key_pair_from_rng, simple_to_network_keypair,
25 },
26 messages_checkpoint::CheckpointSequenceNumber,
27 multiaddr::Multiaddr,
28 supported_protocol_versions::{Chain, SupportedProtocolVersions},
29 traffic_control::{PolicyConfig, RemoteFirewallConfig},
30};
31use once_cell::sync::OnceCell;
32use rand::rngs::OsRng;
33use serde::{Deserialize, Serialize};
34use starfish_config::Parameters as StarfishParameters;
35use tracing::info;
36
37use crate::{
38 Config, certificate_deny_config::CertificateDenyConfig, genesis,
39 migration_tx_data::MigrationTxData, object_storage_config::ObjectStoreConfig, p2p::P2pConfig,
40 transaction_deny_config::TransactionDenyConfig, verifier_signing_config::VerifierSigningConfig,
41};
42
43pub const DEFAULT_VALIDATOR_GAS_PRICE: u64 = iota_types::transaction::DEFAULT_VALIDATOR_GAS_PRICE;
45
46pub const DEFAULT_COMMISSION_RATE: u64 = 200;
48
49pub const DEFAULT_FULL_CHECKPOINT_CONTENTS_CACHE_SIZE_MB: usize = 1024;
51
52#[derive(Clone, Debug, Deserialize, Serialize)]
53#[serde(rename_all = "kebab-case")]
54pub struct NodeConfig {
55 #[serde(default = "default_authority_key_pair")]
58 pub authority_key_pair: AuthorityKeyPairWithPath,
59 #[serde(default = "default_key_pair")]
62 pub protocol_key_pair: KeyPairWithPath,
63 #[serde(default = "default_key_pair")]
64 pub account_key_pair: KeyPairWithPath,
65 #[serde(default = "default_key_pair")]
68 pub network_key_pair: KeyPairWithPath,
69 pub db_path: PathBuf,
70
71 #[serde(default = "default_grpc_address")]
75 pub network_address: Multiaddr,
76 #[serde(default = "default_json_rpc_address")]
77 pub json_rpc_address: SocketAddr,
78
79 #[serde(default = "default_metrics_address")]
81 pub metrics_address: SocketAddr,
82
83 #[serde(default = "default_admin_interface_address")]
87 pub admin_interface_address: SocketAddr,
88
89 #[serde(skip_serializing_if = "Option::is_none")]
91 pub consensus_config: Option<ConsensusConfig>,
92
93 #[serde(default = "default_enable_index_processing")]
98 pub enable_index_processing: bool,
99
100 #[serde(default)]
102 pub jsonrpc_server_type: Option<ServerType>,
107
108 #[serde(default)]
112 pub grpc_load_shed: Option<bool>,
113
114 #[serde(default = "default_grpc_concurrency_limit_per_core")]
131 pub grpc_concurrency_limit_per_core: NonZeroUsize,
132
133 #[serde(default)]
135 pub p2p_config: P2pConfig,
136
137 pub genesis: Genesis,
141
142 pub migration_tx_data_path: Option<PathBuf>,
144
145 #[serde(default = "default_authority_store_pruning_config")]
148 pub authority_store_pruning_config: AuthorityStorePruningConfig,
149
150 #[serde(default = "default_end_of_epoch_broadcast_channel_capacity")]
155 pub end_of_epoch_broadcast_channel_capacity: usize,
156
157 #[serde(default)]
161 pub checkpoint_executor_config: CheckpointExecutorConfig,
162
163 #[serde(skip_serializing_if = "Option::is_none")]
164 pub metrics: Option<MetricsConfig>,
165
166 #[serde(skip)]
171 pub supported_protocol_versions: Option<SupportedProtocolVersions>,
172
173 #[serde(default)]
175 pub expensive_safety_check_config: ExpensiveSafetyCheckConfig,
176
177 #[serde(default)]
181 pub transaction_deny_config: TransactionDenyConfig,
182
183 #[serde(default)]
189 pub certificate_deny_config: CertificateDenyConfig,
190
191 #[serde(default)]
194 pub state_debug_dump_config: StateDebugDumpConfig,
195
196 #[serde(default)]
197 pub checkpoint_archive_config: Option<CheckpointArchiveConfig>,
198
199 #[serde(default)]
201 pub state_snapshot_write_config: StateSnapshotConfig,
202
203 #[serde(default)]
204 pub indexer_max_subscriptions: Option<usize>,
205
206 #[serde(default = "default_transaction_kv_store_config")]
207 pub transaction_kv_store_read_config: TransactionKeyValueStoreReadConfig,
208
209 #[serde(skip_serializing_if = "Option::is_none")]
211 pub transaction_kv_store_write_config: Option<TransactionKeyValueStoreWriteConfig>,
212
213 #[serde(default = "default_authority_overload_config")]
216 pub authority_overload_config: AuthorityOverloadConfig,
217
218 #[serde(skip_serializing_if = "Option::is_none")]
222 pub run_with_range: Option<RunWithRange>,
223
224 #[serde(
226 skip_serializing_if = "Option::is_none",
227 default = "default_traffic_controller_policy_config"
228 )]
229 pub policy_config: Option<PolicyConfig>,
230
231 #[serde(skip_serializing_if = "Option::is_none")]
232 pub firewall_config: Option<RemoteFirewallConfig>,
233
234 #[serde(default)]
235 pub execution_cache_config: ExecutionCacheConfig,
236
237 #[serde(default = "default_full_checkpoint_contents_cache_size_mb")]
248 pub full_checkpoint_contents_cache_size_mb: usize,
249
250 #[serde(default = "bool_true")]
251 pub enable_validator_tx_finalizer: bool,
252
253 #[serde(default = "bool_true")]
259 pub enable_soft_locking: bool,
260
261 #[serde(default)]
262 pub verifier_signing_config: VerifierSigningConfig,
263
264 #[serde(skip_serializing_if = "Option::is_none")]
268 pub enable_db_write_stall: Option<bool>,
269
270 #[serde(default, skip_serializing_if = "Option::is_none")]
271 pub iota_names_config: Option<IotaNamesConfig>,
272
273 #[serde(default)]
275 pub enable_grpc_api: bool,
276 #[serde(
277 default = "default_grpc_api_config",
278 skip_serializing_if = "Option::is_none"
279 )]
280 pub grpc_api_config: Option<GrpcApiConfig>,
281
282 #[serde(skip_serializing_if = "Option::is_none")]
287 pub chain_override_for_testing: Option<Chain>,
288
289 #[serde(default, skip_serializing_if = "Option::is_none")]
292 pub validator_client_monitor_config:
293 Option<crate::validator_client_monitor_config::ValidatorClientMonitorConfig>,
294}
295
296#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
297#[serde(rename_all = "kebab-case")]
298pub struct TlsConfig {
299 cert: String,
301 key: String,
303}
304
305impl TlsConfig {
306 pub fn cert(&self) -> &str {
307 &self.cert
308 }
309
310 pub fn key(&self) -> &str {
311 &self.key
312 }
313}
314
315#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
317#[serde(rename_all = "kebab-case")]
318pub struct GrpcApiConfig {
319 #[serde(default = "default_grpc_api_address")]
321 pub address: SocketAddr,
322
323 #[serde(skip_serializing_if = "Option::is_none")]
327 pub tls: Option<TlsConfig>,
328
329 #[serde(default = "default_grpc_api_max_message_size_bytes")]
331 pub max_message_size_bytes: u32,
332
333 #[serde(default = "default_grpc_api_broadcast_buffer_size")]
335 pub broadcast_buffer_size: u32,
336
337 #[serde(default = "default_grpc_api_max_concurrent_stream_subscribers")]
343 pub max_concurrent_stream_subscribers: u32,
344
345 #[serde(default = "default_grpc_api_max_json_move_value_size")]
348 pub max_json_move_value_size: usize,
349
350 #[serde(default = "default_grpc_api_max_execute_transaction_batch_size")]
353 pub max_execute_transaction_batch_size: u32,
354
355 #[serde(default = "default_grpc_api_max_simulate_transaction_batch_size")]
358 pub max_simulate_transaction_batch_size: u32,
359
360 #[serde(default = "default_grpc_api_max_get_objects_batch_size")]
362 pub max_get_objects_batch_size: u32,
363
364 #[serde(default = "default_grpc_api_max_get_transactions_batch_size")]
367 pub max_get_transactions_batch_size: u32,
368
369 #[serde(default = "default_grpc_api_max_checkpoint_inclusion_timeout_ms")]
373 pub max_checkpoint_inclusion_timeout_ms: u64,
374}
375
376fn default_grpc_api_address() -> SocketAddr {
377 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 50051)
378}
379
380fn default_grpc_api_broadcast_buffer_size() -> u32 {
381 100
382}
383
384fn default_grpc_api_max_concurrent_stream_subscribers() -> u32 {
385 1024
386}
387
388fn default_grpc_api_max_message_size_bytes() -> u32 {
389 128 * 1024 * 1024 }
391
392fn default_grpc_api_max_json_move_value_size() -> usize {
393 1024 * 1024 }
395
396fn default_grpc_api_max_execute_transaction_batch_size() -> u32 {
397 20
398}
399
400fn default_grpc_api_max_simulate_transaction_batch_size() -> u32 {
401 20
402}
403
404fn default_grpc_api_max_get_objects_batch_size() -> u32 {
405 1000
406}
407
408fn default_grpc_api_max_get_transactions_batch_size() -> u32 {
409 1000
410}
411
412fn default_grpc_api_max_checkpoint_inclusion_timeout_ms() -> u64 {
413 60_000 }
415
416impl Default for GrpcApiConfig {
417 fn default() -> Self {
418 Self {
419 address: default_grpc_api_address(),
420 tls: None,
421 max_message_size_bytes: default_grpc_api_max_message_size_bytes(),
422 broadcast_buffer_size: default_grpc_api_broadcast_buffer_size(),
423 max_concurrent_stream_subscribers: default_grpc_api_max_concurrent_stream_subscribers(),
424 max_json_move_value_size: default_grpc_api_max_json_move_value_size(),
425 max_execute_transaction_batch_size: default_grpc_api_max_execute_transaction_batch_size(
426 ),
427 max_simulate_transaction_batch_size:
428 default_grpc_api_max_simulate_transaction_batch_size(),
429 max_get_objects_batch_size: default_grpc_api_max_get_objects_batch_size(),
430 max_get_transactions_batch_size: default_grpc_api_max_get_transactions_batch_size(),
431 max_checkpoint_inclusion_timeout_ms:
432 default_grpc_api_max_checkpoint_inclusion_timeout_ms(),
433 }
434 }
435}
436
437impl GrpcApiConfig {
438 const GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE: u32 = 4 * 1024 * 1024; const GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES: u32 =
442 Self::GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE;
443
444 pub fn tls_config(&self) -> Option<&TlsConfig> {
445 self.tls.as_ref()
446 }
447
448 pub fn max_message_size_bytes(&self) -> u32 {
449 self.max_message_size_bytes
451 .max(Self::GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES)
452 }
453
454 pub fn max_message_size_client_bytes(&self, client_max_message_size_bytes: Option<u32>) -> u32 {
458 client_max_message_size_bytes
459 .unwrap_or(Self::GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE)
462 .clamp(
464 Self::GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES,
465 self.max_message_size_bytes(),
466 )
467 }
468}
469
470#[derive(Clone, Debug, Default, Deserialize, Serialize)]
471#[serde(rename_all = "kebab-case")]
472pub struct ExecutionCacheConfig {
473 #[serde(default)]
474 pub writeback_cache: WritebackCacheConfig,
475}
476
477#[derive(Clone, Debug, Default, Deserialize, Serialize)]
478#[serde(rename_all = "kebab-case")]
479pub struct WritebackCacheConfig {
480 #[serde(default, skip_serializing_if = "Option::is_none")]
483 pub max_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
486 pub package_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
489 pub object_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
491 pub marker_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
493 pub object_by_id_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
496 pub transaction_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
498 pub executed_effect_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
500 pub effect_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
503 pub events_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
506 pub transaction_objects_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
511 pub backpressure_threshold: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
517 pub backpressure_threshold_for_rpc: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
527 pub backpressure_soft_limit_pct: Option<u32>,
528}
529
530impl WritebackCacheConfig {
531 pub fn max_cache_size(&self) -> u64 {
532 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_MAX")
533 .ok()
534 .and_then(|s| s.parse().ok())
535 .or(self.max_cache_size)
536 .unwrap_or(100000)
537 }
538
539 pub fn package_cache_size(&self) -> u64 {
540 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_PACKAGE")
541 .ok()
542 .and_then(|s| s.parse().ok())
543 .or(self.package_cache_size)
544 .unwrap_or(1000)
545 }
546
547 pub fn object_cache_size(&self) -> u64 {
548 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_OBJECT")
549 .ok()
550 .and_then(|s| s.parse().ok())
551 .or(self.object_cache_size)
552 .unwrap_or_else(|| self.max_cache_size())
553 }
554
555 pub fn marker_cache_size(&self) -> u64 {
556 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_MARKER")
557 .ok()
558 .and_then(|s| s.parse().ok())
559 .or(self.marker_cache_size)
560 .unwrap_or_else(|| self.object_cache_size())
561 }
562
563 pub fn object_by_id_cache_size(&self) -> u64 {
564 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_OBJECT_BY_ID")
565 .ok()
566 .and_then(|s| s.parse().ok())
567 .or(self.object_by_id_cache_size)
568 .unwrap_or_else(|| self.object_cache_size())
569 }
570
571 pub fn transaction_cache_size(&self) -> u64 {
572 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_TRANSACTION")
573 .ok()
574 .and_then(|s| s.parse().ok())
575 .or(self.transaction_cache_size)
576 .unwrap_or_else(|| self.max_cache_size())
577 }
578
579 pub fn executed_effect_cache_size(&self) -> u64 {
580 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EXECUTED_EFFECT")
581 .ok()
582 .and_then(|s| s.parse().ok())
583 .or(self.executed_effect_cache_size)
584 .unwrap_or_else(|| self.transaction_cache_size())
585 }
586
587 pub fn effect_cache_size(&self) -> u64 {
588 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EFFECT")
589 .ok()
590 .and_then(|s| s.parse().ok())
591 .or(self.effect_cache_size)
592 .unwrap_or_else(|| self.executed_effect_cache_size())
593 }
594
595 pub fn events_cache_size(&self) -> u64 {
596 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EVENTS")
597 .ok()
598 .and_then(|s| s.parse().ok())
599 .or(self.events_cache_size)
600 .unwrap_or_else(|| self.transaction_cache_size())
601 }
602
603 pub fn transaction_objects_cache_size(&self) -> u64 {
604 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_TRANSACTION_OBJECTS")
605 .ok()
606 .and_then(|s| s.parse().ok())
607 .or(self.transaction_objects_cache_size)
608 .unwrap_or(1000)
609 }
610
611 pub fn backpressure_threshold(&self) -> u64 {
612 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_THRESHOLD")
613 .ok()
614 .and_then(|s| s.parse().ok())
615 .or(self.backpressure_threshold)
616 .unwrap_or(100_000)
617 }
618
619 pub fn backpressure_threshold_for_rpc(&self) -> u64 {
620 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_THRESHOLD_FOR_RPC")
621 .ok()
622 .and_then(|s| s.parse().ok())
623 .or(self.backpressure_threshold_for_rpc)
624 .unwrap_or(self.backpressure_threshold())
625 }
626
627 pub fn backpressure_soft_limit_pct(&self) -> u32 {
628 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_SOFT_LIMIT_PCT")
629 .ok()
630 .and_then(|s| s.parse().ok())
631 .or(self.backpressure_soft_limit_pct)
632 .unwrap_or(50)
633 .min(100)
634 }
635}
636
637#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
638#[serde(rename_all = "lowercase")]
639pub enum ServerType {
640 WebSocket,
641 Http,
642 Both,
643}
644
645#[derive(Clone, Debug, Deserialize, Serialize)]
646#[serde(rename_all = "kebab-case")]
647pub struct TransactionKeyValueStoreReadConfig {
648 #[serde(default = "default_base_url")]
649 pub base_url: String,
650
651 #[serde(default = "default_cache_size")]
652 pub cache_size: u64,
653}
654
655impl Default for TransactionKeyValueStoreReadConfig {
656 fn default() -> Self {
657 Self {
658 base_url: default_base_url(),
659 cache_size: default_cache_size(),
660 }
661 }
662}
663
664fn default_base_url() -> String {
665 "".to_string()
666}
667
668fn default_cache_size() -> u64 {
669 100_000
670}
671
672fn default_transaction_kv_store_config() -> TransactionKeyValueStoreReadConfig {
673 TransactionKeyValueStoreReadConfig::default()
674}
675
676fn default_authority_store_pruning_config() -> AuthorityStorePruningConfig {
677 AuthorityStorePruningConfig::default()
678}
679
680pub fn default_enable_index_processing() -> bool {
681 true
682}
683
684fn default_grpc_address() -> Multiaddr {
685 "/ip4/0.0.0.0/tcp/8080".parse().unwrap()
686}
687fn default_authority_key_pair() -> AuthorityKeyPairWithPath {
688 AuthorityKeyPairWithPath::new(get_key_pair_from_rng::<AuthorityKeyPair, _>(&mut OsRng).1)
689}
690
691fn default_key_pair() -> KeyPairWithPath {
692 KeyPairWithPath::new(
693 get_key_pair_from_rng::<AccountKeyPair, _>(&mut OsRng)
694 .1
695 .into(),
696 )
697}
698
699fn default_metrics_address() -> SocketAddr {
700 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9184)
701}
702
703pub fn default_admin_interface_address() -> SocketAddr {
704 SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 1337)
705}
706
707pub fn default_json_rpc_address() -> SocketAddr {
708 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9000)
709}
710
711pub fn default_grpc_api_config() -> Option<GrpcApiConfig> {
712 Some(GrpcApiConfig::default())
713}
714
715pub fn default_grpc_concurrency_limit_per_core() -> NonZeroUsize {
716 NonZeroUsize::new(1000).unwrap()
717}
718
719pub fn default_end_of_epoch_broadcast_channel_capacity() -> usize {
720 128
721}
722
723pub fn default_full_checkpoint_contents_cache_size_mb() -> usize {
724 DEFAULT_FULL_CHECKPOINT_CONTENTS_CACHE_SIZE_MB
725}
726
727pub fn bool_true() -> bool {
728 true
729}
730
731impl Config for NodeConfig {}
732
733impl NodeConfig {
734 pub fn authority_key_pair(&self) -> &AuthorityKeyPair {
735 self.authority_key_pair.authority_keypair()
736 }
737
738 pub fn protocol_key_pair(&self) -> &NetworkKeyPair {
739 self.protocol_key_pair.ed25519_keypair()
740 }
741
742 pub fn network_key_pair(&self) -> &NetworkKeyPair {
743 self.network_key_pair.ed25519_keypair()
744 }
745
746 pub fn authority_public_key(&self) -> AuthorityPublicKeyBytes {
747 self.authority_key_pair().public().into()
748 }
749
750 pub fn db_path(&self) -> PathBuf {
751 self.db_path.join("live")
752 }
753
754 pub fn db_checkpoint_path(&self) -> PathBuf {
755 self.db_path.join("db_checkpoints")
756 }
757
758 pub fn snapshot_path(&self) -> PathBuf {
759 self.db_path.join("snapshot")
760 }
761
762 pub fn network_address(&self) -> &Multiaddr {
763 &self.network_address
764 }
765
766 pub fn consensus_config(&self) -> Option<&ConsensusConfig> {
767 self.consensus_config.as_ref()
768 }
769
770 pub fn genesis(&self) -> Result<&genesis::Genesis> {
771 self.genesis.genesis()
772 }
773
774 pub fn load_migration_tx_data(&self) -> Result<MigrationTxData> {
775 let Some(location) = &self.migration_tx_data_path else {
776 anyhow::bail!("no file location set");
777 };
778
779 let migration_tx_data = MigrationTxData::load(location)?;
781
782 migration_tx_data.validate_from_genesis(self.genesis.genesis()?)?;
784 Ok(migration_tx_data)
785 }
786
787 pub fn iota_address(&self) -> Address {
788 self.account_key_pair
789 .keypair()
790 .public_key()
791 .derive_address()
792 }
793
794 pub fn checkpoint_archive_config(&self) -> Option<&CheckpointArchiveConfig> {
795 self.checkpoint_archive_config.as_ref()
796 }
797
798 pub fn jsonrpc_server_type(&self) -> ServerType {
799 self.jsonrpc_server_type.unwrap_or(ServerType::Http)
800 }
801}
802
803#[derive(Debug, Clone, Deserialize, Serialize)]
804#[serde(rename_all = "kebab-case")]
805pub struct ConsensusConfig {
806 pub db_path: PathBuf,
808
809 pub db_retention_epochs: Option<u64>,
813
814 pub db_pruner_period_secs: Option<u64>,
818
819 pub max_pending_transactions: Option<usize>,
830
831 pub max_submit_position: Option<usize>,
837
838 pub submit_delay_step_override_millis: Option<u64>,
844
845 #[serde(skip_serializing_if = "Option::is_none", alias = "starfish_parameters")]
847 pub parameters: Option<StarfishParameters>,
848
849 #[serde(skip_serializing_if = "Option::is_none")]
855 pub graduated_load_shedding_soft_limit_pct: Option<u32>,
856}
857
858impl ConsensusConfig {
859 pub fn db_path(&self) -> &Path {
860 &self.db_path
861 }
862
863 pub fn max_pending_transactions(&self) -> usize {
867 self.max_pending_transactions.unwrap_or(20_000)
868 }
869
870 pub fn graduated_load_shedding_soft_limit_pct(&self) -> u32 {
875 self.graduated_load_shedding_soft_limit_pct
876 .unwrap_or(50)
877 .min(100)
878 }
879
880 pub fn submit_delay_step_override(&self) -> Option<Duration> {
881 self.submit_delay_step_override_millis
882 .map(Duration::from_millis)
883 }
884
885 pub fn db_retention_epochs(&self) -> u64 {
886 self.db_retention_epochs.unwrap_or(0)
887 }
888
889 pub fn db_pruner_period(&self) -> Duration {
890 self.db_pruner_period_secs
892 .map(Duration::from_secs)
893 .unwrap_or(Duration::from_secs(3_600))
894 }
895}
896
897#[derive(Clone, Debug, Deserialize, Serialize)]
898#[serde(rename_all = "kebab-case")]
899pub struct CheckpointExecutorConfig {
900 #[serde(default = "default_checkpoint_execution_max_concurrency")]
905 pub checkpoint_execution_max_concurrency: usize,
906
907 #[serde(default = "default_local_execution_timeout_sec")]
913 pub local_execution_timeout_sec: u64,
914
915 #[serde(default, skip_serializing_if = "Option::is_none")]
920 pub data_ingestion_dir: Option<PathBuf>,
921}
922
923#[derive(Clone, Debug, Default, Deserialize, Serialize)]
924#[serde(rename_all = "kebab-case")]
925pub struct ExpensiveSafetyCheckConfig {
926 #[serde(default)]
931 enable_epoch_iota_conservation_check: bool,
932
933 #[serde(default)]
937 enable_deep_per_tx_iota_conservation_check: bool,
938
939 #[serde(default)]
942 force_disable_epoch_iota_conservation_check: bool,
943
944 #[serde(default)]
947 enable_state_consistency_check: bool,
948
949 #[serde(default)]
951 force_disable_state_consistency_check: bool,
952
953 #[serde(default)]
954 enable_secondary_index_checks: bool,
955 }
957
958impl ExpensiveSafetyCheckConfig {
959 pub fn new_enable_all() -> Self {
960 Self {
961 enable_epoch_iota_conservation_check: true,
962 enable_deep_per_tx_iota_conservation_check: true,
963 force_disable_epoch_iota_conservation_check: false,
964 enable_state_consistency_check: true,
965 force_disable_state_consistency_check: false,
966 enable_secondary_index_checks: false, }
968 }
969
970 pub fn new_disable_all() -> Self {
971 Self {
972 enable_epoch_iota_conservation_check: false,
973 enable_deep_per_tx_iota_conservation_check: false,
974 force_disable_epoch_iota_conservation_check: true,
975 enable_state_consistency_check: false,
976 force_disable_state_consistency_check: true,
977 enable_secondary_index_checks: false,
978 }
979 }
980
981 pub fn force_disable_epoch_iota_conservation_check(&mut self) {
982 self.force_disable_epoch_iota_conservation_check = true;
983 }
984
985 pub fn enable_epoch_iota_conservation_check(&self) -> bool {
986 (self.enable_epoch_iota_conservation_check || cfg!(debug_assertions))
987 && !self.force_disable_epoch_iota_conservation_check
988 }
989
990 pub fn force_disable_state_consistency_check(&mut self) {
991 self.force_disable_state_consistency_check = true;
992 }
993
994 pub fn enable_state_consistency_check(&self) -> bool {
995 (self.enable_state_consistency_check || cfg!(debug_assertions))
996 && !self.force_disable_state_consistency_check
997 }
998
999 pub fn enable_deep_per_tx_iota_conservation_check(&self) -> bool {
1000 self.enable_deep_per_tx_iota_conservation_check || cfg!(debug_assertions)
1001 }
1002
1003 pub fn enable_secondary_index_checks(&self) -> bool {
1004 self.enable_secondary_index_checks
1005 }
1006}
1007
1008fn default_checkpoint_execution_max_concurrency() -> usize {
1009 4
1010}
1011
1012fn default_local_execution_timeout_sec() -> u64 {
1013 30
1014}
1015
1016impl Default for CheckpointExecutorConfig {
1017 fn default() -> Self {
1018 Self {
1019 checkpoint_execution_max_concurrency: default_checkpoint_execution_max_concurrency(),
1020 local_execution_timeout_sec: default_local_execution_timeout_sec(),
1021 data_ingestion_dir: None,
1022 }
1023 }
1024}
1025
1026#[derive(Debug, Clone, Deserialize, Serialize)]
1027#[serde(rename_all = "kebab-case")]
1028pub struct AuthorityStorePruningConfig {
1029 #[serde(default = "default_num_latest_epoch_dbs_to_retain")]
1031 pub num_latest_epoch_dbs_to_retain: usize,
1032 #[serde(default)]
1037 pub num_epochs_to_retain: u64,
1038 #[serde(
1043 default = "default_periodic_compaction_threshold_days",
1044 skip_serializing_if = "Option::is_none"
1045 )]
1046 pub periodic_compaction_threshold_days: Option<usize>,
1047 #[serde(skip_serializing_if = "Option::is_none")]
1050 pub num_epochs_to_retain_for_checkpoints: Option<u64>,
1051 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1057 pub enable_compaction_filter: bool,
1058 #[serde(skip_serializing_if = "Option::is_none")]
1059 pub num_epochs_to_retain_for_indexes: Option<u64>,
1060}
1061
1062fn default_num_latest_epoch_dbs_to_retain() -> usize {
1063 3
1064}
1065
1066fn default_periodic_compaction_threshold_days() -> Option<usize> {
1067 Some(1)
1068}
1069
1070impl Default for AuthorityStorePruningConfig {
1071 fn default() -> Self {
1072 Self {
1073 num_latest_epoch_dbs_to_retain: default_num_latest_epoch_dbs_to_retain(),
1074 num_epochs_to_retain: 0,
1075 periodic_compaction_threshold_days: None,
1076 num_epochs_to_retain_for_checkpoints: if cfg!(msim) { Some(2) } else { None },
1077 enable_compaction_filter: cfg!(test) || cfg!(msim),
1078 num_epochs_to_retain_for_indexes: None,
1079 }
1080 }
1081}
1082
1083impl AuthorityStorePruningConfig {
1084 pub fn set_num_epochs_to_retain(&mut self, num_epochs_to_retain: u64) {
1085 self.num_epochs_to_retain = num_epochs_to_retain;
1086 }
1087
1088 pub fn set_num_epochs_to_retain_for_checkpoints(&mut self, num_epochs_to_retain: Option<u64>) {
1089 self.num_epochs_to_retain_for_checkpoints = num_epochs_to_retain;
1090 }
1091
1092 pub fn num_epochs_to_retain_for_checkpoints(&self) -> Option<u64> {
1093 self.num_epochs_to_retain_for_checkpoints
1094 .map(|n| {
1096 if n < 2 {
1097 info!("num_epochs_to_retain_for_checkpoints must be at least 2, rounding up from {}", n);
1098 2
1099 } else {
1100 n
1101 }
1102 })
1103 }
1104}
1105
1106#[derive(Debug, Clone, Deserialize, Serialize)]
1107#[serde(rename_all = "kebab-case")]
1108pub struct MetricsConfig {
1109 #[serde(skip_serializing_if = "Option::is_none")]
1110 pub push_interval_seconds: Option<u64>,
1111 #[serde(skip_serializing_if = "Option::is_none")]
1112 pub push_url: Option<String>,
1113 #[serde(skip_serializing_if = "Option::is_none")]
1114 pub groups: Option<MetricGroups>,
1115}
1116
1117fn default_checkpoint_archive_download_concurrency() -> usize {
1118 10
1119}
1120
1121#[derive(Debug, Clone, Deserialize, Serialize)]
1124#[serde(rename_all = "kebab-case")]
1125pub struct CheckpointArchiveConfig {
1126 pub url: String,
1128 #[serde(default = "default_checkpoint_archive_download_concurrency")]
1130 pub download_concurrency: usize,
1131}
1132
1133#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1141#[serde(rename_all = "kebab-case")]
1142pub struct StateSnapshotConfig {
1143 #[serde(skip_serializing_if = "Option::is_none")]
1144 pub object_store_config: Option<ObjectStoreConfig>,
1145 pub concurrency: usize,
1146}
1147
1148#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1149#[serde(rename_all = "kebab-case")]
1150pub struct TransactionKeyValueStoreWriteConfig {
1151 pub aws_access_key_id: String,
1152 pub aws_secret_access_key: String,
1153 pub aws_region: String,
1154 pub table_name: String,
1155 pub bucket_name: String,
1156 pub concurrency: usize,
1157}
1158
1159#[derive(Clone, Debug, Deserialize, Serialize)]
1164#[serde(rename_all = "kebab-case")]
1165pub struct AuthorityOverloadConfig {
1166 #[serde(default = "default_max_txn_age_in_queue")]
1170 pub max_txn_age_in_queue: Duration,
1171
1172 #[serde(default = "default_overload_monitor_interval")]
1174 pub overload_monitor_interval: Duration,
1175
1176 #[serde(default = "default_execution_queue_latency_soft_limit")]
1178 pub execution_queue_latency_soft_limit: Duration,
1179
1180 #[serde(default = "default_execution_queue_latency_hard_limit")]
1183 pub execution_queue_latency_hard_limit: Duration,
1184
1185 #[serde(default = "default_max_load_shedding_percentage")]
1187 pub max_load_shedding_percentage: u32,
1188
1189 #[serde(default = "default_min_load_shedding_percentage_above_hard_limit")]
1192 pub min_load_shedding_percentage_above_hard_limit: u32,
1193
1194 #[serde(default = "default_safe_transaction_ready_rate")]
1197 pub safe_transaction_ready_rate: u32,
1198
1199 #[serde(default = "default_check_system_overload_at_signing")]
1202 pub check_system_overload_at_signing: bool,
1203
1204 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1207 pub check_system_overload_at_execution: bool,
1208
1209 #[serde(default = "default_max_transaction_manager_queue_length")]
1213 pub max_transaction_manager_queue_length: usize,
1214
1215 #[serde(default = "default_max_transaction_manager_per_object_queue_length")]
1218 pub max_transaction_manager_per_object_queue_length: usize,
1219
1220 #[serde(default = "default_max_transaction_manager_queue_length_soft_limit_pct")]
1224 pub max_transaction_manager_queue_length_soft_limit_pct: u32,
1225}
1226
1227impl AuthorityOverloadConfig {
1228 pub fn max_transaction_manager_queue_length_soft_limit_pct(&self) -> u32 {
1231 self.max_transaction_manager_queue_length_soft_limit_pct
1232 .min(100)
1233 }
1234}
1235
1236fn default_max_txn_age_in_queue() -> Duration {
1237 Duration::from_millis(500)
1238}
1239
1240fn default_overload_monitor_interval() -> Duration {
1241 Duration::from_secs(10)
1242}
1243
1244fn default_execution_queue_latency_soft_limit() -> Duration {
1245 Duration::from_secs(1)
1246}
1247
1248fn default_execution_queue_latency_hard_limit() -> Duration {
1249 Duration::from_secs(10)
1250}
1251
1252fn default_max_load_shedding_percentage() -> u32 {
1253 95
1254}
1255
1256fn default_min_load_shedding_percentage_above_hard_limit() -> u32 {
1257 50
1258}
1259
1260fn default_safe_transaction_ready_rate() -> u32 {
1261 100
1262}
1263
1264fn default_check_system_overload_at_signing() -> bool {
1265 true
1266}
1267
1268fn default_max_transaction_manager_queue_length() -> usize {
1269 100_000
1270}
1271
1272fn default_max_transaction_manager_queue_length_soft_limit_pct() -> u32 {
1273 50
1274}
1275
1276fn default_max_transaction_manager_per_object_queue_length() -> usize {
1277 20
1278}
1279
1280impl Default for AuthorityOverloadConfig {
1281 fn default() -> Self {
1282 Self {
1283 max_txn_age_in_queue: default_max_txn_age_in_queue(),
1284 overload_monitor_interval: default_overload_monitor_interval(),
1285 execution_queue_latency_soft_limit: default_execution_queue_latency_soft_limit(),
1286 execution_queue_latency_hard_limit: default_execution_queue_latency_hard_limit(),
1287 max_load_shedding_percentage: default_max_load_shedding_percentage(),
1288 min_load_shedding_percentage_above_hard_limit:
1289 default_min_load_shedding_percentage_above_hard_limit(),
1290 safe_transaction_ready_rate: default_safe_transaction_ready_rate(),
1291 check_system_overload_at_signing: true,
1292 check_system_overload_at_execution: false,
1293 max_transaction_manager_queue_length: default_max_transaction_manager_queue_length(),
1294 max_transaction_manager_queue_length_soft_limit_pct:
1295 default_max_transaction_manager_queue_length_soft_limit_pct(),
1296 max_transaction_manager_per_object_queue_length:
1297 default_max_transaction_manager_per_object_queue_length(),
1298 }
1299 }
1300}
1301
1302fn default_authority_overload_config() -> AuthorityOverloadConfig {
1303 AuthorityOverloadConfig::default()
1304}
1305
1306fn default_traffic_controller_policy_config() -> Option<PolicyConfig> {
1307 Some(PolicyConfig::default_dos_protection_policy())
1308}
1309
1310#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1311pub struct Genesis {
1312 #[serde(flatten)]
1313 location: Option<GenesisLocation>,
1314
1315 #[serde(skip)]
1316 genesis: once_cell::sync::OnceCell<genesis::Genesis>,
1317}
1318
1319impl Genesis {
1320 pub fn new(genesis: genesis::Genesis) -> Self {
1321 Self {
1322 location: Some(GenesisLocation::InPlace {
1323 genesis: Box::new(genesis),
1324 }),
1325 genesis: Default::default(),
1326 }
1327 }
1328
1329 pub fn new_from_file<P: Into<PathBuf>>(path: P) -> Self {
1330 Self {
1331 location: Some(GenesisLocation::File {
1332 genesis_file_location: path.into(),
1333 }),
1334 genesis: Default::default(),
1335 }
1336 }
1337
1338 pub fn new_empty() -> Self {
1339 Self {
1340 location: None,
1341 genesis: Default::default(),
1342 }
1343 }
1344
1345 pub fn genesis(&self) -> Result<&genesis::Genesis> {
1346 match &self.location {
1347 Some(GenesisLocation::InPlace { genesis }) => Ok(genesis),
1348 Some(GenesisLocation::File {
1349 genesis_file_location,
1350 }) => self
1351 .genesis
1352 .get_or_try_init(|| genesis::Genesis::load(genesis_file_location)),
1353 None => anyhow::bail!("no genesis location set"),
1354 }
1355 }
1356}
1357
1358#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1359#[serde(untagged)]
1360enum GenesisLocation {
1361 InPlace {
1362 genesis: Box<genesis::Genesis>,
1363 },
1364 File {
1365 #[serde(rename = "genesis-file-location")]
1366 genesis_file_location: PathBuf,
1367 },
1368}
1369
1370#[derive(Clone, Debug, Deserialize, Serialize)]
1373pub struct KeyPairWithPath {
1374 #[serde(flatten)]
1375 location: KeyPairLocation,
1376
1377 #[serde(skip)]
1378 keypair: OnceCell<Arc<SimpleKeypair>>,
1379
1380 #[serde(skip)]
1386 ed25519_keypair: OnceCell<Arc<Ed25519KeyPair>>,
1387}
1388
1389impl PartialEq for KeyPairWithPath {
1390 fn eq(&self, other: &Self) -> bool {
1391 self.location == other.location
1392 }
1393}
1394
1395impl Eq for KeyPairWithPath {}
1396
1397#[derive(Debug, Clone, Deserialize, Serialize)]
1398#[serde(untagged)]
1399enum KeyPairLocation {
1400 InPlace {
1401 #[serde(with = "bech32_formatted_keypair")]
1402 value: Arc<SimpleKeypair>,
1403 },
1404 File {
1405 path: PathBuf,
1406 },
1407}
1408
1409impl PartialEq for KeyPairLocation {
1410 fn eq(&self, other: &Self) -> bool {
1411 match (self, other) {
1412 (Self::InPlace { value: a }, Self::InPlace { value: b }) => {
1413 a.to_bytes() == b.to_bytes()
1414 }
1415 (Self::File { path: a }, Self::File { path: b }) => a == b,
1416 _ => false,
1417 }
1418 }
1419}
1420
1421impl Eq for KeyPairLocation {}
1422
1423impl KeyPairWithPath {
1424 pub fn new(kp: SimpleKeypair) -> Self {
1425 let cell: OnceCell<Arc<SimpleKeypair>> = OnceCell::new();
1426 let arc_kp = Arc::new(kp);
1427 cell.set(arc_kp.clone()).expect("failed to set keypair");
1430 Self {
1431 location: KeyPairLocation::InPlace { value: arc_kp },
1432 keypair: cell,
1433 ed25519_keypair: OnceCell::new(),
1434 }
1435 }
1436
1437 pub fn new_from_path(path: PathBuf) -> Self {
1438 let cell: OnceCell<Arc<SimpleKeypair>> = OnceCell::new();
1439 cell.set(Arc::new(read_keypair_from_file(&path).unwrap_or_else(
1442 |e| panic!("invalid keypair file at path {path:?}: {e}"),
1443 )))
1444 .expect("failed to set keypair");
1445 Self {
1446 location: KeyPairLocation::File { path },
1447 keypair: cell,
1448 ed25519_keypair: OnceCell::new(),
1449 }
1450 }
1451
1452 pub fn keypair(&self) -> &SimpleKeypair {
1453 self.keypair
1454 .get_or_init(|| match &self.location {
1455 KeyPairLocation::InPlace { value } => value.clone(),
1456 KeyPairLocation::File { path } => {
1457 Arc::new(
1460 read_keypair_from_file(path).unwrap_or_else(|e| {
1461 panic!("invalid keypair file at path {path:?}: {e}")
1462 }),
1463 )
1464 }
1465 })
1466 .as_ref()
1467 }
1468
1469 pub fn ed25519_keypair(&self) -> &Ed25519KeyPair {
1473 self.ed25519_keypair
1474 .get_or_init(|| {
1475 Arc::new(
1476 simple_to_network_keypair(self.keypair())
1477 .expect("only Ed25519 network keys are allowed"),
1478 )
1479 })
1480 .as_ref()
1481 }
1482}
1483
1484#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
1487pub struct AuthorityKeyPairWithPath {
1488 #[serde(flatten)]
1489 location: AuthorityKeyPairLocation,
1490
1491 #[serde(skip)]
1492 keypair: OnceCell<Arc<AuthorityKeyPair>>,
1493}
1494
1495#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1496#[serde(untagged)]
1497enum AuthorityKeyPairLocation {
1498 InPlace { value: Arc<AuthorityKeyPair> },
1499 File { path: PathBuf },
1500}
1501
1502impl AuthorityKeyPairWithPath {
1503 pub fn new(kp: AuthorityKeyPair) -> Self {
1504 let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1505 let arc_kp = Arc::new(kp);
1506 cell.set(arc_kp.clone())
1509 .expect("failed to set authority keypair");
1510 Self {
1511 location: AuthorityKeyPairLocation::InPlace { value: arc_kp },
1512 keypair: cell,
1513 }
1514 }
1515
1516 pub fn new_from_path(path: PathBuf) -> Self {
1517 let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1518 cell.set(Arc::new(
1521 read_authority_keypair_from_file(&path)
1522 .unwrap_or_else(|_| panic!("invalid authority keypair file at path {path:?}")),
1523 ))
1524 .expect("failed to set authority keypair");
1525 Self {
1526 location: AuthorityKeyPairLocation::File { path },
1527 keypair: cell,
1528 }
1529 }
1530
1531 pub fn authority_keypair(&self) -> &AuthorityKeyPair {
1532 self.keypair
1533 .get_or_init(|| match &self.location {
1534 AuthorityKeyPairLocation::InPlace { value } => value.clone(),
1535 AuthorityKeyPairLocation::File { path } => {
1536 Arc::new(
1539 read_authority_keypair_from_file(path)
1540 .unwrap_or_else(|_| panic!("invalid authority keypair file {path:?}")),
1541 )
1542 }
1543 })
1544 .as_ref()
1545 }
1546}
1547
1548#[derive(Clone, Debug, Deserialize, Serialize, Default)]
1551#[serde(rename_all = "kebab-case")]
1552pub struct StateDebugDumpConfig {
1553 #[serde(skip_serializing_if = "Option::is_none")]
1554 pub dump_file_directory: Option<PathBuf>,
1555}
1556
1557#[cfg(test)]
1558mod tests {
1559 use std::path::PathBuf;
1560
1561 use fastcrypto::traits::KeyPair;
1562 use iota_keys::keypair_file::{write_authority_keypair_to_file, write_keypair_to_file};
1563 use iota_types::crypto::{
1564 AuthorityKeyPair, NetworkKeyPair, get_key_pair_from_rng, network_to_simple_keypair,
1565 };
1566 use rand::{SeedableRng, rngs::StdRng};
1567
1568 use super::Genesis;
1569 use crate::NodeConfig;
1570
1571 #[test]
1572 fn serialize_genesis_from_file() {
1573 let g = Genesis::new_from_file("path/to/file");
1574
1575 let s = serde_yaml::to_string(&g).unwrap();
1576 assert_eq!("---\ngenesis-file-location: path/to/file\n", s);
1577 let loaded_genesis: Genesis = serde_yaml::from_str(&s).unwrap();
1578 assert_eq!(g, loaded_genesis);
1579 }
1580
1581 #[test]
1582 fn fullnode_template() {
1583 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1584
1585 let _template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1586 }
1587
1588 #[test]
1589 fn enable_soft_locking_defaults_to_enabled() {
1590 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1593
1594 let config: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1595 assert!(config.enable_soft_locking);
1596 }
1597
1598 #[test]
1599 fn load_key_pairs_to_node_config() {
1600 let authority_key_pair: AuthorityKeyPair =
1601 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1602 let protocol_key_pair: NetworkKeyPair =
1603 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1604 let network_key_pair: NetworkKeyPair =
1605 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1606
1607 write_authority_keypair_to_file(&authority_key_pair, PathBuf::from("authority.key"))
1608 .unwrap();
1609 write_keypair_to_file(
1610 &network_to_simple_keypair(&protocol_key_pair),
1611 PathBuf::from("protocol.key"),
1612 )
1613 .unwrap();
1614 write_keypair_to_file(
1615 &network_to_simple_keypair(&network_key_pair),
1616 PathBuf::from("network.key"),
1617 )
1618 .unwrap();
1619
1620 const TEMPLATE: &str = include_str!("../data/fullnode-template-with-path.yaml");
1621 let template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1622 assert_eq!(
1623 template.authority_key_pair().public(),
1624 authority_key_pair.public()
1625 );
1626 assert_eq!(
1627 template.network_key_pair().public(),
1628 network_key_pair.public()
1629 );
1630 assert_eq!(
1631 template.protocol_key_pair().public(),
1632 protocol_key_pair.public()
1633 );
1634 }
1635}
1636
1637#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
1641pub enum RunWithRange {
1642 Epoch(EpochId),
1643 Checkpoint(CheckpointSequenceNumber),
1644}
1645
1646impl RunWithRange {
1647 pub fn is_epoch_gt(&self, epoch_id: EpochId) -> bool {
1649 matches!(self, RunWithRange::Epoch(e) if epoch_id > *e)
1650 }
1651
1652 pub fn matches_checkpoint(&self, seq_num: CheckpointSequenceNumber) -> bool {
1653 matches!(self, RunWithRange::Checkpoint(seq) if *seq == seq_num)
1654 }
1655
1656 pub fn into_checkpoint_bound(self) -> Option<CheckpointSequenceNumber> {
1657 match self {
1658 RunWithRange::Epoch(_) => None,
1659 RunWithRange::Checkpoint(seq) => Some(seq),
1660 }
1661 }
1662}
1663
1664mod bech32_formatted_keypair {
1668 use std::ops::Deref;
1669
1670 use fastcrypto::encoding::{Base64, Encoding};
1671 use iota_sdk_crypto::{ToFromBech32, simple::SimpleKeypair};
1672 use serde::{Deserialize, Deserializer, Serializer};
1673
1674 pub fn serialize<S, T>(kp: &T, serializer: S) -> Result<S::Ok, S::Error>
1675 where
1676 S: Serializer,
1677 T: Deref<Target = SimpleKeypair>,
1678 {
1679 use serde::ser::Error;
1680
1681 let s = kp.to_bech32().map_err(Error::custom)?;
1683
1684 serializer.serialize_str(&s)
1685 }
1686
1687 pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
1688 where
1689 D: Deserializer<'de>,
1690 T: From<SimpleKeypair>,
1691 {
1692 use serde::de::Error;
1693
1694 let s = String::deserialize(deserializer)?;
1695
1696 SimpleKeypair::from_bech32(&s)
1698 .map_err(Error::custom)
1699 .or_else(|_: D::Error| {
1700 let bytes = Base64::decode(&s).map_err(Error::custom)?;
1702 SimpleKeypair::from_bytes(&bytes).map_err(Error::custom)
1703 })
1704 .map(Into::into)
1705 }
1706}