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(AccountKeyPair::random().into())
693}
694
695fn default_metrics_address() -> SocketAddr {
696 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9184)
697}
698
699pub fn default_admin_interface_address() -> SocketAddr {
700 SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 1337)
701}
702
703pub fn default_json_rpc_address() -> SocketAddr {
704 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9000)
705}
706
707pub fn default_grpc_api_config() -> Option<GrpcApiConfig> {
708 Some(GrpcApiConfig::default())
709}
710
711pub fn default_grpc_concurrency_limit_per_core() -> NonZeroUsize {
712 NonZeroUsize::new(1000).unwrap()
713}
714
715pub fn default_end_of_epoch_broadcast_channel_capacity() -> usize {
716 128
717}
718
719pub fn default_full_checkpoint_contents_cache_size_mb() -> usize {
720 DEFAULT_FULL_CHECKPOINT_CONTENTS_CACHE_SIZE_MB
721}
722
723pub fn bool_true() -> bool {
724 true
725}
726
727impl Config for NodeConfig {}
728
729impl NodeConfig {
730 pub fn authority_key_pair(&self) -> &AuthorityKeyPair {
731 self.authority_key_pair.authority_keypair()
732 }
733
734 pub fn protocol_key_pair(&self) -> &NetworkKeyPair {
735 self.protocol_key_pair.ed25519_keypair()
736 }
737
738 pub fn network_key_pair(&self) -> &NetworkKeyPair {
739 self.network_key_pair.ed25519_keypair()
740 }
741
742 pub fn authority_public_key(&self) -> AuthorityPublicKeyBytes {
743 self.authority_key_pair().public().into()
744 }
745
746 pub fn db_path(&self) -> PathBuf {
747 self.db_path.join("live")
748 }
749
750 pub fn db_checkpoint_path(&self) -> PathBuf {
751 self.db_path.join("db_checkpoints")
752 }
753
754 pub fn snapshot_path(&self) -> PathBuf {
755 self.db_path.join("snapshot")
756 }
757
758 pub fn network_address(&self) -> &Multiaddr {
759 &self.network_address
760 }
761
762 pub fn consensus_config(&self) -> Option<&ConsensusConfig> {
763 self.consensus_config.as_ref()
764 }
765
766 pub fn genesis(&self) -> Result<&genesis::Genesis> {
767 self.genesis.genesis()
768 }
769
770 pub fn load_migration_tx_data(&self) -> Result<MigrationTxData> {
771 let Some(location) = &self.migration_tx_data_path else {
772 anyhow::bail!("no file location set");
773 };
774
775 let migration_tx_data = MigrationTxData::load(location)?;
777
778 migration_tx_data.validate_from_genesis(self.genesis.genesis()?)?;
780 Ok(migration_tx_data)
781 }
782
783 pub fn iota_address(&self) -> Address {
784 self.account_key_pair
785 .keypair()
786 .public_key()
787 .derive_address()
788 }
789
790 pub fn checkpoint_archive_config(&self) -> Option<&CheckpointArchiveConfig> {
791 self.checkpoint_archive_config.as_ref()
792 }
793
794 pub fn jsonrpc_server_type(&self) -> ServerType {
795 self.jsonrpc_server_type.unwrap_or(ServerType::Http)
796 }
797}
798
799#[derive(Debug, Clone, Deserialize, Serialize)]
800#[serde(rename_all = "kebab-case")]
801pub struct ConsensusConfig {
802 pub db_path: PathBuf,
804
805 pub db_retention_epochs: Option<u64>,
809
810 pub db_pruner_period_secs: Option<u64>,
814
815 pub max_pending_transactions: Option<usize>,
826
827 pub max_submit_position: Option<usize>,
833
834 pub submit_delay_step_override_millis: Option<u64>,
840
841 #[serde(skip_serializing_if = "Option::is_none", alias = "starfish_parameters")]
843 pub parameters: Option<StarfishParameters>,
844
845 #[serde(skip_serializing_if = "Option::is_none")]
851 pub graduated_load_shedding_soft_limit_pct: Option<u32>,
852}
853
854impl ConsensusConfig {
855 pub fn db_path(&self) -> &Path {
856 &self.db_path
857 }
858
859 pub fn max_pending_transactions(&self) -> usize {
863 self.max_pending_transactions.unwrap_or(20_000)
864 }
865
866 pub fn graduated_load_shedding_soft_limit_pct(&self) -> u32 {
871 self.graduated_load_shedding_soft_limit_pct
872 .unwrap_or(50)
873 .min(100)
874 }
875
876 pub fn submit_delay_step_override(&self) -> Option<Duration> {
877 self.submit_delay_step_override_millis
878 .map(Duration::from_millis)
879 }
880
881 pub fn db_retention_epochs(&self) -> u64 {
882 self.db_retention_epochs.unwrap_or(0)
883 }
884
885 pub fn db_pruner_period(&self) -> Duration {
886 self.db_pruner_period_secs
888 .map(Duration::from_secs)
889 .unwrap_or(Duration::from_secs(3_600))
890 }
891}
892
893#[derive(Clone, Debug, Deserialize, Serialize)]
894#[serde(rename_all = "kebab-case")]
895pub struct CheckpointExecutorConfig {
896 #[serde(default = "default_checkpoint_execution_max_concurrency")]
901 pub checkpoint_execution_max_concurrency: usize,
902
903 #[serde(default = "default_local_execution_timeout_sec")]
909 pub local_execution_timeout_sec: u64,
910
911 #[serde(default, skip_serializing_if = "Option::is_none")]
916 pub data_ingestion_dir: Option<PathBuf>,
917}
918
919#[derive(Clone, Debug, Default, Deserialize, Serialize)]
920#[serde(rename_all = "kebab-case")]
921pub struct ExpensiveSafetyCheckConfig {
922 #[serde(default)]
927 enable_epoch_iota_conservation_check: bool,
928
929 #[serde(default)]
933 enable_deep_per_tx_iota_conservation_check: bool,
934
935 #[serde(default)]
938 force_disable_epoch_iota_conservation_check: bool,
939
940 #[serde(default)]
943 enable_state_consistency_check: bool,
944
945 #[serde(default)]
947 force_disable_state_consistency_check: bool,
948
949 #[serde(default)]
950 enable_secondary_index_checks: bool,
951 }
953
954impl ExpensiveSafetyCheckConfig {
955 pub fn new_enable_all() -> Self {
956 Self {
957 enable_epoch_iota_conservation_check: true,
958 enable_deep_per_tx_iota_conservation_check: true,
959 force_disable_epoch_iota_conservation_check: false,
960 enable_state_consistency_check: true,
961 force_disable_state_consistency_check: false,
962 enable_secondary_index_checks: false, }
964 }
965
966 pub fn new_disable_all() -> Self {
967 Self {
968 enable_epoch_iota_conservation_check: false,
969 enable_deep_per_tx_iota_conservation_check: false,
970 force_disable_epoch_iota_conservation_check: true,
971 enable_state_consistency_check: false,
972 force_disable_state_consistency_check: true,
973 enable_secondary_index_checks: false,
974 }
975 }
976
977 pub fn force_disable_epoch_iota_conservation_check(&mut self) {
978 self.force_disable_epoch_iota_conservation_check = true;
979 }
980
981 pub fn enable_epoch_iota_conservation_check(&self) -> bool {
982 (self.enable_epoch_iota_conservation_check || cfg!(debug_assertions))
983 && !self.force_disable_epoch_iota_conservation_check
984 }
985
986 pub fn force_disable_state_consistency_check(&mut self) {
987 self.force_disable_state_consistency_check = true;
988 }
989
990 pub fn enable_state_consistency_check(&self) -> bool {
991 (self.enable_state_consistency_check || cfg!(debug_assertions))
992 && !self.force_disable_state_consistency_check
993 }
994
995 pub fn enable_deep_per_tx_iota_conservation_check(&self) -> bool {
996 self.enable_deep_per_tx_iota_conservation_check || cfg!(debug_assertions)
997 }
998
999 pub fn enable_secondary_index_checks(&self) -> bool {
1000 self.enable_secondary_index_checks
1001 }
1002}
1003
1004fn default_checkpoint_execution_max_concurrency() -> usize {
1005 4
1006}
1007
1008fn default_local_execution_timeout_sec() -> u64 {
1009 30
1010}
1011
1012impl Default for CheckpointExecutorConfig {
1013 fn default() -> Self {
1014 Self {
1015 checkpoint_execution_max_concurrency: default_checkpoint_execution_max_concurrency(),
1016 local_execution_timeout_sec: default_local_execution_timeout_sec(),
1017 data_ingestion_dir: None,
1018 }
1019 }
1020}
1021
1022#[derive(Debug, Clone, Deserialize, Serialize)]
1023#[serde(rename_all = "kebab-case")]
1024pub struct AuthorityStorePruningConfig {
1025 #[serde(default = "default_num_latest_epoch_dbs_to_retain")]
1027 pub num_latest_epoch_dbs_to_retain: usize,
1028 #[serde(default)]
1033 pub num_epochs_to_retain: u64,
1034 #[serde(
1039 default = "default_periodic_compaction_threshold_days",
1040 skip_serializing_if = "Option::is_none"
1041 )]
1042 pub periodic_compaction_threshold_days: Option<usize>,
1043 #[serde(skip_serializing_if = "Option::is_none")]
1046 pub num_epochs_to_retain_for_checkpoints: Option<u64>,
1047 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1053 pub enable_compaction_filter: bool,
1054 #[serde(skip_serializing_if = "Option::is_none")]
1055 pub num_epochs_to_retain_for_indexes: Option<u64>,
1056}
1057
1058fn default_num_latest_epoch_dbs_to_retain() -> usize {
1059 3
1060}
1061
1062fn default_periodic_compaction_threshold_days() -> Option<usize> {
1063 Some(1)
1064}
1065
1066impl Default for AuthorityStorePruningConfig {
1067 fn default() -> Self {
1068 Self {
1069 num_latest_epoch_dbs_to_retain: default_num_latest_epoch_dbs_to_retain(),
1070 num_epochs_to_retain: 0,
1071 periodic_compaction_threshold_days: None,
1072 num_epochs_to_retain_for_checkpoints: if cfg!(msim) { Some(2) } else { None },
1073 enable_compaction_filter: cfg!(test) || cfg!(msim),
1074 num_epochs_to_retain_for_indexes: None,
1075 }
1076 }
1077}
1078
1079impl AuthorityStorePruningConfig {
1080 pub fn set_num_epochs_to_retain(&mut self, num_epochs_to_retain: u64) {
1081 self.num_epochs_to_retain = num_epochs_to_retain;
1082 }
1083
1084 pub fn set_num_epochs_to_retain_for_checkpoints(&mut self, num_epochs_to_retain: Option<u64>) {
1085 self.num_epochs_to_retain_for_checkpoints = num_epochs_to_retain;
1086 }
1087
1088 pub fn num_epochs_to_retain_for_checkpoints(&self) -> Option<u64> {
1089 self.num_epochs_to_retain_for_checkpoints
1090 .map(|n| {
1092 if n < 2 {
1093 info!("num_epochs_to_retain_for_checkpoints must be at least 2, rounding up from {}", n);
1094 2
1095 } else {
1096 n
1097 }
1098 })
1099 }
1100}
1101
1102#[derive(Debug, Clone, Deserialize, Serialize)]
1103#[serde(rename_all = "kebab-case")]
1104pub struct MetricsConfig {
1105 #[serde(skip_serializing_if = "Option::is_none")]
1106 pub push_interval_seconds: Option<u64>,
1107 #[serde(skip_serializing_if = "Option::is_none")]
1108 pub push_url: Option<String>,
1109 #[serde(skip_serializing_if = "Option::is_none")]
1110 pub groups: Option<MetricGroups>,
1111}
1112
1113fn default_checkpoint_archive_download_concurrency() -> usize {
1114 10
1115}
1116
1117#[derive(Debug, Clone, Deserialize, Serialize)]
1120#[serde(rename_all = "kebab-case")]
1121pub struct CheckpointArchiveConfig {
1122 pub url: String,
1124 #[serde(default = "default_checkpoint_archive_download_concurrency")]
1126 pub download_concurrency: usize,
1127}
1128
1129#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1137#[serde(rename_all = "kebab-case")]
1138pub struct StateSnapshotConfig {
1139 #[serde(skip_serializing_if = "Option::is_none")]
1140 pub object_store_config: Option<ObjectStoreConfig>,
1141 pub concurrency: usize,
1142}
1143
1144#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1145#[serde(rename_all = "kebab-case")]
1146pub struct TransactionKeyValueStoreWriteConfig {
1147 pub aws_access_key_id: String,
1148 pub aws_secret_access_key: String,
1149 pub aws_region: String,
1150 pub table_name: String,
1151 pub bucket_name: String,
1152 pub concurrency: usize,
1153}
1154
1155#[derive(Clone, Debug, Deserialize, Serialize)]
1160#[serde(rename_all = "kebab-case")]
1161pub struct AuthorityOverloadConfig {
1162 #[serde(default = "default_max_txn_age_in_queue")]
1166 pub max_txn_age_in_queue: Duration,
1167
1168 #[serde(default = "default_overload_monitor_interval")]
1170 pub overload_monitor_interval: Duration,
1171
1172 #[serde(default = "default_execution_queue_latency_soft_limit")]
1174 pub execution_queue_latency_soft_limit: Duration,
1175
1176 #[serde(default = "default_execution_queue_latency_hard_limit")]
1179 pub execution_queue_latency_hard_limit: Duration,
1180
1181 #[serde(default = "default_max_load_shedding_percentage")]
1183 pub max_load_shedding_percentage: u32,
1184
1185 #[serde(default = "default_min_load_shedding_percentage_above_hard_limit")]
1188 pub min_load_shedding_percentage_above_hard_limit: u32,
1189
1190 #[serde(default = "default_safe_transaction_ready_rate")]
1193 pub safe_transaction_ready_rate: u32,
1194
1195 #[serde(default = "default_check_system_overload_at_signing")]
1198 pub check_system_overload_at_signing: bool,
1199
1200 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1203 pub check_system_overload_at_execution: bool,
1204
1205 #[serde(default = "default_max_transaction_manager_queue_length")]
1209 pub max_transaction_manager_queue_length: usize,
1210
1211 #[serde(default = "default_max_transaction_manager_per_object_queue_length")]
1214 pub max_transaction_manager_per_object_queue_length: usize,
1215
1216 #[serde(default = "default_max_transaction_manager_queue_length_soft_limit_pct")]
1220 pub max_transaction_manager_queue_length_soft_limit_pct: u32,
1221}
1222
1223impl AuthorityOverloadConfig {
1224 pub fn max_transaction_manager_queue_length_soft_limit_pct(&self) -> u32 {
1227 self.max_transaction_manager_queue_length_soft_limit_pct
1228 .min(100)
1229 }
1230}
1231
1232fn default_max_txn_age_in_queue() -> Duration {
1233 Duration::from_millis(500)
1234}
1235
1236fn default_overload_monitor_interval() -> Duration {
1237 Duration::from_secs(10)
1238}
1239
1240fn default_execution_queue_latency_soft_limit() -> Duration {
1241 Duration::from_secs(1)
1242}
1243
1244fn default_execution_queue_latency_hard_limit() -> Duration {
1245 Duration::from_secs(10)
1246}
1247
1248fn default_max_load_shedding_percentage() -> u32 {
1249 95
1250}
1251
1252fn default_min_load_shedding_percentage_above_hard_limit() -> u32 {
1253 50
1254}
1255
1256fn default_safe_transaction_ready_rate() -> u32 {
1257 100
1258}
1259
1260fn default_check_system_overload_at_signing() -> bool {
1261 true
1262}
1263
1264fn default_max_transaction_manager_queue_length() -> usize {
1265 100_000
1266}
1267
1268fn default_max_transaction_manager_queue_length_soft_limit_pct() -> u32 {
1269 50
1270}
1271
1272fn default_max_transaction_manager_per_object_queue_length() -> usize {
1273 20
1274}
1275
1276impl Default for AuthorityOverloadConfig {
1277 fn default() -> Self {
1278 Self {
1279 max_txn_age_in_queue: default_max_txn_age_in_queue(),
1280 overload_monitor_interval: default_overload_monitor_interval(),
1281 execution_queue_latency_soft_limit: default_execution_queue_latency_soft_limit(),
1282 execution_queue_latency_hard_limit: default_execution_queue_latency_hard_limit(),
1283 max_load_shedding_percentage: default_max_load_shedding_percentage(),
1284 min_load_shedding_percentage_above_hard_limit:
1285 default_min_load_shedding_percentage_above_hard_limit(),
1286 safe_transaction_ready_rate: default_safe_transaction_ready_rate(),
1287 check_system_overload_at_signing: true,
1288 check_system_overload_at_execution: false,
1289 max_transaction_manager_queue_length: default_max_transaction_manager_queue_length(),
1290 max_transaction_manager_queue_length_soft_limit_pct:
1291 default_max_transaction_manager_queue_length_soft_limit_pct(),
1292 max_transaction_manager_per_object_queue_length:
1293 default_max_transaction_manager_per_object_queue_length(),
1294 }
1295 }
1296}
1297
1298fn default_authority_overload_config() -> AuthorityOverloadConfig {
1299 AuthorityOverloadConfig::default()
1300}
1301
1302fn default_traffic_controller_policy_config() -> Option<PolicyConfig> {
1303 Some(PolicyConfig::default_dos_protection_policy())
1304}
1305
1306#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1307pub struct Genesis {
1308 #[serde(flatten)]
1309 location: Option<GenesisLocation>,
1310
1311 #[serde(skip)]
1312 genesis: once_cell::sync::OnceCell<genesis::Genesis>,
1313}
1314
1315impl Genesis {
1316 pub fn new(genesis: genesis::Genesis) -> Self {
1317 Self {
1318 location: Some(GenesisLocation::InPlace {
1319 genesis: Box::new(genesis),
1320 }),
1321 genesis: Default::default(),
1322 }
1323 }
1324
1325 pub fn new_from_file<P: Into<PathBuf>>(path: P) -> Self {
1326 Self {
1327 location: Some(GenesisLocation::File {
1328 genesis_file_location: path.into(),
1329 }),
1330 genesis: Default::default(),
1331 }
1332 }
1333
1334 pub fn new_empty() -> Self {
1335 Self {
1336 location: None,
1337 genesis: Default::default(),
1338 }
1339 }
1340
1341 pub fn genesis(&self) -> Result<&genesis::Genesis> {
1342 match &self.location {
1343 Some(GenesisLocation::InPlace { genesis }) => Ok(genesis),
1344 Some(GenesisLocation::File {
1345 genesis_file_location,
1346 }) => self
1347 .genesis
1348 .get_or_try_init(|| genesis::Genesis::load(genesis_file_location)),
1349 None => anyhow::bail!("no genesis location set"),
1350 }
1351 }
1352}
1353
1354#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1355#[serde(untagged)]
1356enum GenesisLocation {
1357 InPlace {
1358 genesis: Box<genesis::Genesis>,
1359 },
1360 File {
1361 #[serde(rename = "genesis-file-location")]
1362 genesis_file_location: PathBuf,
1363 },
1364}
1365
1366#[derive(Clone, Debug, Deserialize, Serialize)]
1369pub struct KeyPairWithPath {
1370 #[serde(flatten)]
1371 location: KeyPairLocation,
1372
1373 #[serde(skip)]
1374 keypair: OnceCell<Arc<SimpleKeypair>>,
1375
1376 #[serde(skip)]
1382 ed25519_keypair: OnceCell<Arc<Ed25519KeyPair>>,
1383}
1384
1385impl PartialEq for KeyPairWithPath {
1386 fn eq(&self, other: &Self) -> bool {
1387 self.location == other.location
1388 }
1389}
1390
1391impl Eq for KeyPairWithPath {}
1392
1393#[derive(Debug, Clone, Deserialize, Serialize)]
1394#[serde(untagged)]
1395enum KeyPairLocation {
1396 InPlace {
1397 #[serde(with = "bech32_formatted_keypair")]
1398 value: Arc<SimpleKeypair>,
1399 },
1400 File {
1401 path: PathBuf,
1402 },
1403}
1404
1405impl PartialEq for KeyPairLocation {
1406 fn eq(&self, other: &Self) -> bool {
1407 match (self, other) {
1408 (Self::InPlace { value: a }, Self::InPlace { value: b }) => {
1409 a.to_bytes() == b.to_bytes()
1410 }
1411 (Self::File { path: a }, Self::File { path: b }) => a == b,
1412 _ => false,
1413 }
1414 }
1415}
1416
1417impl Eq for KeyPairLocation {}
1418
1419impl KeyPairWithPath {
1420 pub fn new(kp: SimpleKeypair) -> Self {
1421 let cell: OnceCell<Arc<SimpleKeypair>> = OnceCell::new();
1422 let arc_kp = Arc::new(kp);
1423 cell.set(arc_kp.clone()).expect("failed to set keypair");
1426 Self {
1427 location: KeyPairLocation::InPlace { value: arc_kp },
1428 keypair: cell,
1429 ed25519_keypair: OnceCell::new(),
1430 }
1431 }
1432
1433 pub fn new_from_path(path: PathBuf) -> Self {
1434 let cell: OnceCell<Arc<SimpleKeypair>> = OnceCell::new();
1435 cell.set(Arc::new(read_keypair_from_file(&path).unwrap_or_else(
1438 |e| panic!("invalid keypair file at path {path:?}: {e}"),
1439 )))
1440 .expect("failed to set keypair");
1441 Self {
1442 location: KeyPairLocation::File { path },
1443 keypair: cell,
1444 ed25519_keypair: OnceCell::new(),
1445 }
1446 }
1447
1448 pub fn keypair(&self) -> &SimpleKeypair {
1449 self.keypair
1450 .get_or_init(|| match &self.location {
1451 KeyPairLocation::InPlace { value } => value.clone(),
1452 KeyPairLocation::File { path } => {
1453 Arc::new(
1456 read_keypair_from_file(path).unwrap_or_else(|e| {
1457 panic!("invalid keypair file at path {path:?}: {e}")
1458 }),
1459 )
1460 }
1461 })
1462 .as_ref()
1463 }
1464
1465 pub fn ed25519_keypair(&self) -> &Ed25519KeyPair {
1469 self.ed25519_keypair
1470 .get_or_init(|| {
1471 Arc::new(
1472 simple_to_network_keypair(self.keypair())
1473 .expect("only Ed25519 network keys are allowed"),
1474 )
1475 })
1476 .as_ref()
1477 }
1478}
1479
1480#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
1483pub struct AuthorityKeyPairWithPath {
1484 #[serde(flatten)]
1485 location: AuthorityKeyPairLocation,
1486
1487 #[serde(skip)]
1488 keypair: OnceCell<Arc<AuthorityKeyPair>>,
1489}
1490
1491#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1492#[serde(untagged)]
1493enum AuthorityKeyPairLocation {
1494 InPlace { value: Arc<AuthorityKeyPair> },
1495 File { path: PathBuf },
1496}
1497
1498impl AuthorityKeyPairWithPath {
1499 pub fn new(kp: AuthorityKeyPair) -> Self {
1500 let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1501 let arc_kp = Arc::new(kp);
1502 cell.set(arc_kp.clone())
1505 .expect("failed to set authority keypair");
1506 Self {
1507 location: AuthorityKeyPairLocation::InPlace { value: arc_kp },
1508 keypair: cell,
1509 }
1510 }
1511
1512 pub fn new_from_path(path: PathBuf) -> Self {
1513 let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1514 cell.set(Arc::new(
1517 read_authority_keypair_from_file(&path)
1518 .unwrap_or_else(|_| panic!("invalid authority keypair file at path {path:?}")),
1519 ))
1520 .expect("failed to set authority keypair");
1521 Self {
1522 location: AuthorityKeyPairLocation::File { path },
1523 keypair: cell,
1524 }
1525 }
1526
1527 pub fn authority_keypair(&self) -> &AuthorityKeyPair {
1528 self.keypair
1529 .get_or_init(|| match &self.location {
1530 AuthorityKeyPairLocation::InPlace { value } => value.clone(),
1531 AuthorityKeyPairLocation::File { path } => {
1532 Arc::new(
1535 read_authority_keypair_from_file(path)
1536 .unwrap_or_else(|_| panic!("invalid authority keypair file {path:?}")),
1537 )
1538 }
1539 })
1540 .as_ref()
1541 }
1542}
1543
1544#[derive(Clone, Debug, Deserialize, Serialize, Default)]
1547#[serde(rename_all = "kebab-case")]
1548pub struct StateDebugDumpConfig {
1549 #[serde(skip_serializing_if = "Option::is_none")]
1550 pub dump_file_directory: Option<PathBuf>,
1551}
1552
1553#[cfg(test)]
1554mod tests {
1555 use std::path::PathBuf;
1556
1557 use fastcrypto::traits::KeyPair;
1558 use iota_keys::keypair_file::{write_authority_keypair_to_file, write_keypair_to_file};
1559 use iota_types::crypto::{
1560 AuthorityKeyPair, NetworkKeyPair, get_key_pair_from_rng, network_to_simple_keypair,
1561 };
1562 use rand::{SeedableRng, rngs::StdRng};
1563
1564 use super::Genesis;
1565 use crate::NodeConfig;
1566
1567 #[test]
1568 fn serialize_genesis_from_file() {
1569 let g = Genesis::new_from_file("path/to/file");
1570
1571 let s = serde_yaml::to_string(&g).unwrap();
1572 assert_eq!("---\ngenesis-file-location: path/to/file\n", s);
1573 let loaded_genesis: Genesis = serde_yaml::from_str(&s).unwrap();
1574 assert_eq!(g, loaded_genesis);
1575 }
1576
1577 #[test]
1578 fn fullnode_template() {
1579 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1580
1581 let _template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1582 }
1583
1584 #[test]
1585 fn enable_soft_locking_defaults_to_enabled() {
1586 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1589
1590 let config: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1591 assert!(config.enable_soft_locking);
1592 }
1593
1594 #[test]
1595 fn load_key_pairs_to_node_config() {
1596 let authority_key_pair: AuthorityKeyPair =
1597 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1598 let protocol_key_pair: NetworkKeyPair =
1599 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1600 let network_key_pair: NetworkKeyPair =
1601 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1602
1603 write_authority_keypair_to_file(&authority_key_pair, PathBuf::from("authority.key"))
1604 .unwrap();
1605 write_keypair_to_file(
1606 &network_to_simple_keypair(&protocol_key_pair),
1607 PathBuf::from("protocol.key"),
1608 )
1609 .unwrap();
1610 write_keypair_to_file(
1611 &network_to_simple_keypair(&network_key_pair),
1612 PathBuf::from("network.key"),
1613 )
1614 .unwrap();
1615
1616 const TEMPLATE: &str = include_str!("../data/fullnode-template-with-path.yaml");
1617 let template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1618 assert_eq!(
1619 template.authority_key_pair().public(),
1620 authority_key_pair.public()
1621 );
1622 assert_eq!(
1623 template.network_key_pair().public(),
1624 network_key_pair.public()
1625 );
1626 assert_eq!(
1627 template.protocol_key_pair().public(),
1628 protocol_key_pair.public()
1629 );
1630 }
1631}
1632
1633#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
1637pub enum RunWithRange {
1638 Epoch(EpochId),
1639 Checkpoint(CheckpointSequenceNumber),
1640}
1641
1642impl RunWithRange {
1643 pub fn is_epoch_gt(&self, epoch_id: EpochId) -> bool {
1645 matches!(self, RunWithRange::Epoch(e) if epoch_id > *e)
1646 }
1647
1648 pub fn matches_checkpoint(&self, seq_num: CheckpointSequenceNumber) -> bool {
1649 matches!(self, RunWithRange::Checkpoint(seq) if *seq == seq_num)
1650 }
1651
1652 pub fn into_checkpoint_bound(self) -> Option<CheckpointSequenceNumber> {
1653 match self {
1654 RunWithRange::Epoch(_) => None,
1655 RunWithRange::Checkpoint(seq) => Some(seq),
1656 }
1657 }
1658}
1659
1660mod bech32_formatted_keypair {
1664 use std::ops::Deref;
1665
1666 use fastcrypto::encoding::{Base64, Encoding};
1667 use iota_sdk_crypto::{ToFromBech32, simple::SimpleKeypair};
1668 use serde::{Deserialize, Deserializer, Serializer};
1669
1670 pub fn serialize<S, T>(kp: &T, serializer: S) -> Result<S::Ok, S::Error>
1671 where
1672 S: Serializer,
1673 T: Deref<Target = SimpleKeypair>,
1674 {
1675 use serde::ser::Error;
1676
1677 let s = kp.to_bech32().map_err(Error::custom)?;
1679
1680 serializer.serialize_str(&s)
1681 }
1682
1683 pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
1684 where
1685 D: Deserializer<'de>,
1686 T: From<SimpleKeypair>,
1687 {
1688 use serde::de::Error;
1689
1690 let s = String::deserialize(deserializer)?;
1691
1692 SimpleKeypair::from_bech32(&s)
1694 .map_err(Error::custom)
1695 .or_else(|_: D::Error| {
1696 let bytes = Base64::decode(&s).map_err(Error::custom)?;
1698 SimpleKeypair::from_bytes(&bytes).map_err(Error::custom)
1699 })
1700 .map(Into::into)
1701 }
1702}