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 iota_keys::keypair_file::{read_authority_keypair_from_file, read_keypair_from_file};
15use iota_names::config::IotaNamesConfig;
16use iota_sdk_types::Address;
17use iota_types::{
18 committee::EpochId,
19 crypto::{
20 AccountKeyPair, AuthorityKeyPair, AuthorityPublicKeyBytes, IotaKeyPair, KeypairTraits,
21 NetworkKeyPair, get_key_pair_from_rng,
22 },
23 messages_checkpoint::CheckpointSequenceNumber,
24 multiaddr::Multiaddr,
25 supported_protocol_versions::{Chain, SupportedProtocolVersions},
26 traffic_control::{PolicyConfig, RemoteFirewallConfig},
27};
28use once_cell::sync::OnceCell;
29use rand::rngs::OsRng;
30use serde::{Deserialize, Serialize};
31use starfish_config::Parameters as StarfishParameters;
32use tracing::info;
33
34use crate::{
35 Config, certificate_deny_config::CertificateDenyConfig, genesis,
36 migration_tx_data::MigrationTxData, object_storage_config::ObjectStoreConfig, p2p::P2pConfig,
37 transaction_deny_config::TransactionDenyConfig, verifier_signing_config::VerifierSigningConfig,
38};
39
40pub const DEFAULT_GRPC_CONCURRENCY_LIMIT: usize = 20000000000;
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_concurrency_limit")]
115 pub grpc_concurrency_limit: Option<usize>,
116
117 #[serde(default)]
119 pub p2p_config: P2pConfig,
120
121 pub genesis: Genesis,
125
126 pub migration_tx_data_path: Option<PathBuf>,
128
129 #[serde(default = "default_authority_store_pruning_config")]
132 pub authority_store_pruning_config: AuthorityStorePruningConfig,
133
134 #[serde(default = "default_end_of_epoch_broadcast_channel_capacity")]
139 pub end_of_epoch_broadcast_channel_capacity: usize,
140
141 #[serde(default)]
145 pub checkpoint_executor_config: CheckpointExecutorConfig,
146
147 #[serde(skip_serializing_if = "Option::is_none")]
148 pub metrics: Option<MetricsConfig>,
149
150 #[serde(skip)]
155 pub supported_protocol_versions: Option<SupportedProtocolVersions>,
156
157 #[serde(default)]
161 pub db_checkpoint_config: DBCheckpointConfig,
162
163 #[serde(default)]
165 pub expensive_safety_check_config: ExpensiveSafetyCheckConfig,
166
167 #[serde(default)]
171 pub transaction_deny_config: TransactionDenyConfig,
172
173 #[serde(default)]
179 pub certificate_deny_config: CertificateDenyConfig,
180
181 #[serde(default)]
184 pub state_debug_dump_config: StateDebugDumpConfig,
185
186 #[serde(default)]
190 pub state_archive_write_config: StateArchiveConfig,
191
192 #[serde(default)]
193 pub state_archive_read_config: Vec<StateArchiveConfig>,
194
195 #[serde(default)]
197 pub state_snapshot_write_config: StateSnapshotConfig,
198
199 #[serde(default)]
200 pub indexer_max_subscriptions: Option<usize>,
201
202 #[serde(default = "default_transaction_kv_store_config")]
203 pub transaction_kv_store_read_config: TransactionKeyValueStoreReadConfig,
204
205 #[serde(skip_serializing_if = "Option::is_none")]
207 pub transaction_kv_store_write_config: Option<TransactionKeyValueStoreWriteConfig>,
208
209 #[serde(default = "default_authority_overload_config")]
212 pub authority_overload_config: AuthorityOverloadConfig,
213
214 #[serde(skip_serializing_if = "Option::is_none")]
218 pub run_with_range: Option<RunWithRange>,
219
220 #[serde(
222 skip_serializing_if = "Option::is_none",
223 default = "default_traffic_controller_policy_config"
224 )]
225 pub policy_config: Option<PolicyConfig>,
226
227 #[serde(skip_serializing_if = "Option::is_none")]
228 pub firewall_config: Option<RemoteFirewallConfig>,
229
230 #[serde(default)]
231 pub execution_cache_config: ExecutionCacheConfig,
232
233 #[serde(default = "default_full_checkpoint_contents_cache_size_mb")]
244 pub full_checkpoint_contents_cache_size_mb: usize,
245
246 #[serde(default = "bool_true")]
247 pub enable_validator_tx_finalizer: bool,
248
249 #[serde(default = "bool_true")]
255 pub enable_soft_locking: bool,
256
257 #[serde(default)]
258 pub verifier_signing_config: VerifierSigningConfig,
259
260 #[serde(skip_serializing_if = "Option::is_none")]
264 pub enable_db_write_stall: Option<bool>,
265
266 #[serde(default, skip_serializing_if = "Option::is_none")]
267 pub iota_names_config: Option<IotaNamesConfig>,
268
269 #[serde(default)]
271 pub enable_grpc_api: bool,
272 #[serde(
273 default = "default_grpc_api_config",
274 skip_serializing_if = "Option::is_none"
275 )]
276 pub grpc_api_config: Option<GrpcApiConfig>,
277
278 #[serde(skip_serializing_if = "Option::is_none")]
283 pub chain_override_for_testing: Option<Chain>,
284
285 #[serde(default, skip_serializing_if = "Option::is_none")]
288 pub validator_client_monitor_config:
289 Option<crate::validator_client_monitor_config::ValidatorClientMonitorConfig>,
290}
291
292#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
293#[serde(rename_all = "kebab-case")]
294pub struct TlsConfig {
295 cert: String,
297 key: String,
299}
300
301impl TlsConfig {
302 pub fn cert(&self) -> &str {
303 &self.cert
304 }
305
306 pub fn key(&self) -> &str {
307 &self.key
308 }
309}
310
311#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
313#[serde(rename_all = "kebab-case")]
314pub struct GrpcApiConfig {
315 #[serde(default = "default_grpc_api_address")]
317 pub address: SocketAddr,
318
319 #[serde(skip_serializing_if = "Option::is_none")]
323 pub tls: Option<TlsConfig>,
324
325 #[serde(default = "default_grpc_api_max_message_size_bytes")]
327 pub max_message_size_bytes: u32,
328
329 #[serde(default = "default_grpc_api_broadcast_buffer_size")]
331 pub broadcast_buffer_size: u32,
332
333 #[serde(default = "default_grpc_api_max_concurrent_stream_subscribers")]
339 pub max_concurrent_stream_subscribers: u32,
340
341 #[serde(default = "default_grpc_api_max_json_move_value_size")]
344 pub max_json_move_value_size: usize,
345
346 #[serde(default = "default_grpc_api_max_execute_transaction_batch_size")]
349 pub max_execute_transaction_batch_size: u32,
350
351 #[serde(default = "default_grpc_api_max_simulate_transaction_batch_size")]
354 pub max_simulate_transaction_batch_size: u32,
355
356 #[serde(default = "default_grpc_api_max_checkpoint_inclusion_timeout_ms")]
360 pub max_checkpoint_inclusion_timeout_ms: u64,
361}
362
363fn default_grpc_api_address() -> SocketAddr {
364 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 50051)
365}
366
367fn default_grpc_api_broadcast_buffer_size() -> u32 {
368 100
369}
370
371fn default_grpc_api_max_concurrent_stream_subscribers() -> u32 {
372 1024
373}
374
375fn default_grpc_api_max_message_size_bytes() -> u32 {
376 128 * 1024 * 1024 }
378
379fn default_grpc_api_max_json_move_value_size() -> usize {
380 1024 * 1024 }
382
383fn default_grpc_api_max_execute_transaction_batch_size() -> u32 {
384 20
385}
386
387fn default_grpc_api_max_simulate_transaction_batch_size() -> u32 {
388 20
389}
390
391fn default_grpc_api_max_checkpoint_inclusion_timeout_ms() -> u64 {
392 60_000 }
394
395impl Default for GrpcApiConfig {
396 fn default() -> Self {
397 Self {
398 address: default_grpc_api_address(),
399 tls: None,
400 max_message_size_bytes: default_grpc_api_max_message_size_bytes(),
401 broadcast_buffer_size: default_grpc_api_broadcast_buffer_size(),
402 max_concurrent_stream_subscribers: default_grpc_api_max_concurrent_stream_subscribers(),
403 max_json_move_value_size: default_grpc_api_max_json_move_value_size(),
404 max_execute_transaction_batch_size: default_grpc_api_max_execute_transaction_batch_size(
405 ),
406 max_simulate_transaction_batch_size:
407 default_grpc_api_max_simulate_transaction_batch_size(),
408 max_checkpoint_inclusion_timeout_ms:
409 default_grpc_api_max_checkpoint_inclusion_timeout_ms(),
410 }
411 }
412}
413
414impl GrpcApiConfig {
415 const GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE: u32 = 4 * 1024 * 1024; const GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES: u32 =
419 Self::GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE;
420
421 pub fn tls_config(&self) -> Option<&TlsConfig> {
422 self.tls.as_ref()
423 }
424
425 pub fn max_message_size_bytes(&self) -> u32 {
426 self.max_message_size_bytes
428 .max(Self::GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES)
429 }
430
431 pub fn max_message_size_client_bytes(&self, client_max_message_size_bytes: Option<u32>) -> u32 {
435 client_max_message_size_bytes
436 .unwrap_or(Self::GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE)
439 .clamp(
441 Self::GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES,
442 self.max_message_size_bytes(),
443 )
444 }
445}
446
447#[derive(Clone, Debug, Default, Deserialize, Serialize)]
448#[serde(rename_all = "kebab-case")]
449pub struct ExecutionCacheConfig {
450 #[serde(default)]
451 pub writeback_cache: WritebackCacheConfig,
452}
453
454#[derive(Clone, Debug, Default, Deserialize, Serialize)]
455#[serde(rename_all = "kebab-case")]
456pub struct WritebackCacheConfig {
457 #[serde(default, skip_serializing_if = "Option::is_none")]
460 pub max_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
463 pub package_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
466 pub object_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
468 pub marker_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
470 pub object_by_id_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
473 pub transaction_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
475 pub executed_effect_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
477 pub effect_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
480 pub events_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
483 pub transaction_objects_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
488 pub backpressure_threshold: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
494 pub backpressure_threshold_for_rpc: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
504 pub backpressure_soft_limit_pct: Option<u32>,
505}
506
507impl WritebackCacheConfig {
508 pub fn max_cache_size(&self) -> u64 {
509 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_MAX")
510 .ok()
511 .and_then(|s| s.parse().ok())
512 .or(self.max_cache_size)
513 .unwrap_or(100000)
514 }
515
516 pub fn package_cache_size(&self) -> u64 {
517 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_PACKAGE")
518 .ok()
519 .and_then(|s| s.parse().ok())
520 .or(self.package_cache_size)
521 .unwrap_or(1000)
522 }
523
524 pub fn object_cache_size(&self) -> u64 {
525 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_OBJECT")
526 .ok()
527 .and_then(|s| s.parse().ok())
528 .or(self.object_cache_size)
529 .unwrap_or_else(|| self.max_cache_size())
530 }
531
532 pub fn marker_cache_size(&self) -> u64 {
533 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_MARKER")
534 .ok()
535 .and_then(|s| s.parse().ok())
536 .or(self.marker_cache_size)
537 .unwrap_or_else(|| self.object_cache_size())
538 }
539
540 pub fn object_by_id_cache_size(&self) -> u64 {
541 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_OBJECT_BY_ID")
542 .ok()
543 .and_then(|s| s.parse().ok())
544 .or(self.object_by_id_cache_size)
545 .unwrap_or_else(|| self.object_cache_size())
546 }
547
548 pub fn transaction_cache_size(&self) -> u64 {
549 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_TRANSACTION")
550 .ok()
551 .and_then(|s| s.parse().ok())
552 .or(self.transaction_cache_size)
553 .unwrap_or_else(|| self.max_cache_size())
554 }
555
556 pub fn executed_effect_cache_size(&self) -> u64 {
557 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EXECUTED_EFFECT")
558 .ok()
559 .and_then(|s| s.parse().ok())
560 .or(self.executed_effect_cache_size)
561 .unwrap_or_else(|| self.transaction_cache_size())
562 }
563
564 pub fn effect_cache_size(&self) -> u64 {
565 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EFFECT")
566 .ok()
567 .and_then(|s| s.parse().ok())
568 .or(self.effect_cache_size)
569 .unwrap_or_else(|| self.executed_effect_cache_size())
570 }
571
572 pub fn events_cache_size(&self) -> u64 {
573 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EVENTS")
574 .ok()
575 .and_then(|s| s.parse().ok())
576 .or(self.events_cache_size)
577 .unwrap_or_else(|| self.transaction_cache_size())
578 }
579
580 pub fn transaction_objects_cache_size(&self) -> u64 {
581 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_TRANSACTION_OBJECTS")
582 .ok()
583 .and_then(|s| s.parse().ok())
584 .or(self.transaction_objects_cache_size)
585 .unwrap_or(1000)
586 }
587
588 pub fn backpressure_threshold(&self) -> u64 {
589 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_THRESHOLD")
590 .ok()
591 .and_then(|s| s.parse().ok())
592 .or(self.backpressure_threshold)
593 .unwrap_or(100_000)
594 }
595
596 pub fn backpressure_threshold_for_rpc(&self) -> u64 {
597 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_THRESHOLD_FOR_RPC")
598 .ok()
599 .and_then(|s| s.parse().ok())
600 .or(self.backpressure_threshold_for_rpc)
601 .unwrap_or(self.backpressure_threshold())
602 }
603
604 pub fn backpressure_soft_limit_pct(&self) -> u32 {
605 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_SOFT_LIMIT_PCT")
606 .ok()
607 .and_then(|s| s.parse().ok())
608 .or(self.backpressure_soft_limit_pct)
609 .unwrap_or(50)
610 .min(100)
611 }
612}
613
614#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
615#[serde(rename_all = "lowercase")]
616pub enum ServerType {
617 WebSocket,
618 Http,
619 Both,
620}
621
622#[derive(Clone, Debug, Deserialize, Serialize)]
623#[serde(rename_all = "kebab-case")]
624pub struct TransactionKeyValueStoreReadConfig {
625 #[serde(default = "default_base_url")]
626 pub base_url: String,
627
628 #[serde(default = "default_cache_size")]
629 pub cache_size: u64,
630}
631
632impl Default for TransactionKeyValueStoreReadConfig {
633 fn default() -> Self {
634 Self {
635 base_url: default_base_url(),
636 cache_size: default_cache_size(),
637 }
638 }
639}
640
641fn default_base_url() -> String {
642 "".to_string()
643}
644
645fn default_cache_size() -> u64 {
646 100_000
647}
648
649fn default_transaction_kv_store_config() -> TransactionKeyValueStoreReadConfig {
650 TransactionKeyValueStoreReadConfig::default()
651}
652
653fn default_authority_store_pruning_config() -> AuthorityStorePruningConfig {
654 AuthorityStorePruningConfig::default()
655}
656
657pub fn default_enable_index_processing() -> bool {
658 true
659}
660
661fn default_grpc_address() -> Multiaddr {
662 "/ip4/0.0.0.0/tcp/8080".parse().unwrap()
663}
664fn default_authority_key_pair() -> AuthorityKeyPairWithPath {
665 AuthorityKeyPairWithPath::new(get_key_pair_from_rng::<AuthorityKeyPair, _>(&mut OsRng).1)
666}
667
668fn default_key_pair() -> KeyPairWithPath {
669 KeyPairWithPath::new(
670 get_key_pair_from_rng::<AccountKeyPair, _>(&mut OsRng)
671 .1
672 .into(),
673 )
674}
675
676fn default_metrics_address() -> SocketAddr {
677 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9184)
678}
679
680pub fn default_admin_interface_address() -> SocketAddr {
681 SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 1337)
682}
683
684pub fn default_json_rpc_address() -> SocketAddr {
685 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9000)
686}
687
688pub fn default_grpc_api_config() -> Option<GrpcApiConfig> {
689 Some(GrpcApiConfig::default())
690}
691
692pub fn default_concurrency_limit() -> Option<usize> {
693 Some(DEFAULT_GRPC_CONCURRENCY_LIMIT)
694}
695
696pub fn default_end_of_epoch_broadcast_channel_capacity() -> usize {
697 128
698}
699
700pub fn default_full_checkpoint_contents_cache_size_mb() -> usize {
701 DEFAULT_FULL_CHECKPOINT_CONTENTS_CACHE_SIZE_MB
702}
703
704pub fn bool_true() -> bool {
705 true
706}
707
708impl Config for NodeConfig {}
709
710impl NodeConfig {
711 pub fn authority_key_pair(&self) -> &AuthorityKeyPair {
712 self.authority_key_pair.authority_keypair()
713 }
714
715 pub fn protocol_key_pair(&self) -> &NetworkKeyPair {
716 match self.protocol_key_pair.keypair() {
717 IotaKeyPair::Ed25519(kp) => kp,
718 other => {
719 panic!("invalid keypair type: {other:?}, only Ed25519 is allowed for protocol key")
720 }
721 }
722 }
723
724 pub fn network_key_pair(&self) -> &NetworkKeyPair {
725 match self.network_key_pair.keypair() {
726 IotaKeyPair::Ed25519(kp) => kp,
727 other => {
728 panic!("invalid keypair type: {other:?}, only Ed25519 is allowed for network key")
729 }
730 }
731 }
732
733 pub fn authority_public_key(&self) -> AuthorityPublicKeyBytes {
734 self.authority_key_pair().public().into()
735 }
736
737 pub fn db_path(&self) -> PathBuf {
738 self.db_path.join("live")
739 }
740
741 pub fn db_checkpoint_path(&self) -> PathBuf {
742 self.db_path.join("db_checkpoints")
743 }
744
745 pub fn archive_path(&self) -> PathBuf {
746 self.db_path.join("archive")
747 }
748
749 pub fn snapshot_path(&self) -> PathBuf {
750 self.db_path.join("snapshot")
751 }
752
753 pub fn network_address(&self) -> &Multiaddr {
754 &self.network_address
755 }
756
757 pub fn consensus_config(&self) -> Option<&ConsensusConfig> {
758 self.consensus_config.as_ref()
759 }
760
761 pub fn genesis(&self) -> Result<&genesis::Genesis> {
762 self.genesis.genesis()
763 }
764
765 pub fn load_migration_tx_data(&self) -> Result<MigrationTxData> {
766 let Some(location) = &self.migration_tx_data_path else {
767 anyhow::bail!("no file location set");
768 };
769
770 let migration_tx_data = MigrationTxData::load(location)?;
772
773 migration_tx_data.validate_from_genesis(self.genesis.genesis()?)?;
775 Ok(migration_tx_data)
776 }
777
778 pub fn iota_address(&self) -> Address {
779 (&self.account_key_pair.keypair().public()).into()
780 }
781
782 pub fn archive_reader_config(&self) -> Vec<ArchiveReaderConfig> {
783 self.state_archive_read_config
784 .iter()
785 .flat_map(|config| {
786 config
787 .object_store_config
788 .as_ref()
789 .map(|remote_store_config| ArchiveReaderConfig {
790 remote_store_config: remote_store_config.clone(),
791 download_concurrency: NonZeroUsize::new(config.concurrency)
792 .unwrap_or(NonZeroUsize::new(5).unwrap()),
793 use_for_pruning_watermark: config.use_for_pruning_watermark,
794 })
795 })
796 .collect()
797 }
798
799 pub fn jsonrpc_server_type(&self) -> ServerType {
800 self.jsonrpc_server_type.unwrap_or(ServerType::Http)
801 }
802}
803
804#[derive(Debug, Clone, Deserialize, Serialize)]
805#[serde(rename_all = "kebab-case")]
806pub struct ConsensusConfig {
807 pub db_path: PathBuf,
809
810 pub db_retention_epochs: Option<u64>,
814
815 pub db_pruner_period_secs: Option<u64>,
819
820 pub max_pending_transactions: Option<usize>,
831
832 pub max_submit_position: Option<usize>,
838
839 pub submit_delay_step_override_millis: Option<u64>,
845
846 #[serde(skip_serializing_if = "Option::is_none", alias = "starfish_parameters")]
848 pub parameters: Option<StarfishParameters>,
849
850 #[serde(skip_serializing_if = "Option::is_none")]
856 pub graduated_load_shedding_soft_limit_pct: Option<u32>,
857}
858
859impl ConsensusConfig {
860 pub fn db_path(&self) -> &Path {
861 &self.db_path
862 }
863
864 pub fn max_pending_transactions(&self) -> usize {
868 self.max_pending_transactions.unwrap_or(20_000)
869 }
870
871 pub fn graduated_load_shedding_soft_limit_pct(&self) -> u32 {
876 self.graduated_load_shedding_soft_limit_pct
877 .unwrap_or(50)
878 .min(100)
879 }
880
881 pub fn submit_delay_step_override(&self) -> Option<Duration> {
882 self.submit_delay_step_override_millis
883 .map(Duration::from_millis)
884 }
885
886 pub fn db_retention_epochs(&self) -> u64 {
887 self.db_retention_epochs.unwrap_or(0)
888 }
889
890 pub fn db_pruner_period(&self) -> Duration {
891 self.db_pruner_period_secs
893 .map(Duration::from_secs)
894 .unwrap_or(Duration::from_secs(3_600))
895 }
896}
897
898#[derive(Clone, Debug, Deserialize, Serialize)]
899#[serde(rename_all = "kebab-case")]
900pub struct CheckpointExecutorConfig {
901 #[serde(default = "default_checkpoint_execution_max_concurrency")]
906 pub checkpoint_execution_max_concurrency: usize,
907
908 #[serde(default = "default_local_execution_timeout_sec")]
914 pub local_execution_timeout_sec: u64,
915
916 #[serde(default, skip_serializing_if = "Option::is_none")]
921 pub data_ingestion_dir: Option<PathBuf>,
922}
923
924#[derive(Clone, Debug, Default, Deserialize, Serialize)]
925#[serde(rename_all = "kebab-case")]
926pub struct ExpensiveSafetyCheckConfig {
927 #[serde(default)]
932 enable_epoch_iota_conservation_check: bool,
933
934 #[serde(default)]
938 enable_deep_per_tx_iota_conservation_check: bool,
939
940 #[serde(default)]
943 force_disable_epoch_iota_conservation_check: bool,
944
945 #[serde(default)]
948 enable_state_consistency_check: bool,
949
950 #[serde(default)]
952 force_disable_state_consistency_check: bool,
953
954 #[serde(default)]
955 enable_secondary_index_checks: bool,
956 }
958
959impl ExpensiveSafetyCheckConfig {
960 pub fn new_enable_all() -> Self {
961 Self {
962 enable_epoch_iota_conservation_check: true,
963 enable_deep_per_tx_iota_conservation_check: true,
964 force_disable_epoch_iota_conservation_check: false,
965 enable_state_consistency_check: true,
966 force_disable_state_consistency_check: false,
967 enable_secondary_index_checks: false, }
969 }
970
971 pub fn new_disable_all() -> Self {
972 Self {
973 enable_epoch_iota_conservation_check: false,
974 enable_deep_per_tx_iota_conservation_check: false,
975 force_disable_epoch_iota_conservation_check: true,
976 enable_state_consistency_check: false,
977 force_disable_state_consistency_check: true,
978 enable_secondary_index_checks: false,
979 }
980 }
981
982 pub fn force_disable_epoch_iota_conservation_check(&mut self) {
983 self.force_disable_epoch_iota_conservation_check = true;
984 }
985
986 pub fn enable_epoch_iota_conservation_check(&self) -> bool {
987 (self.enable_epoch_iota_conservation_check || cfg!(debug_assertions))
988 && !self.force_disable_epoch_iota_conservation_check
989 }
990
991 pub fn force_disable_state_consistency_check(&mut self) {
992 self.force_disable_state_consistency_check = true;
993 }
994
995 pub fn enable_state_consistency_check(&self) -> bool {
996 (self.enable_state_consistency_check || cfg!(debug_assertions))
997 && !self.force_disable_state_consistency_check
998 }
999
1000 pub fn enable_deep_per_tx_iota_conservation_check(&self) -> bool {
1001 self.enable_deep_per_tx_iota_conservation_check || cfg!(debug_assertions)
1002 }
1003
1004 pub fn enable_secondary_index_checks(&self) -> bool {
1005 self.enable_secondary_index_checks
1006 }
1007}
1008
1009fn default_checkpoint_execution_max_concurrency() -> usize {
1010 4
1011}
1012
1013fn default_local_execution_timeout_sec() -> u64 {
1014 30
1015}
1016
1017impl Default for CheckpointExecutorConfig {
1018 fn default() -> Self {
1019 Self {
1020 checkpoint_execution_max_concurrency: default_checkpoint_execution_max_concurrency(),
1021 local_execution_timeout_sec: default_local_execution_timeout_sec(),
1022 data_ingestion_dir: None,
1023 }
1024 }
1025}
1026
1027#[derive(Debug, Clone, Deserialize, Serialize)]
1028#[serde(rename_all = "kebab-case")]
1029pub struct AuthorityStorePruningConfig {
1030 #[serde(default = "default_num_latest_epoch_dbs_to_retain")]
1032 pub num_latest_epoch_dbs_to_retain: usize,
1033 #[serde(default)]
1038 pub num_epochs_to_retain: u64,
1039 #[serde(
1044 default = "default_periodic_compaction_threshold_days",
1045 skip_serializing_if = "Option::is_none"
1046 )]
1047 pub periodic_compaction_threshold_days: Option<usize>,
1048 #[serde(skip_serializing_if = "Option::is_none")]
1051 pub num_epochs_to_retain_for_checkpoints: Option<u64>,
1052 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1058 pub enable_compaction_filter: bool,
1059 #[serde(skip_serializing_if = "Option::is_none")]
1060 pub num_epochs_to_retain_for_indexes: Option<u64>,
1061}
1062
1063fn default_num_latest_epoch_dbs_to_retain() -> usize {
1064 3
1065}
1066
1067fn default_periodic_compaction_threshold_days() -> Option<usize> {
1068 Some(1)
1069}
1070
1071impl Default for AuthorityStorePruningConfig {
1072 fn default() -> Self {
1073 Self {
1074 num_latest_epoch_dbs_to_retain: default_num_latest_epoch_dbs_to_retain(),
1075 num_epochs_to_retain: 0,
1076 periodic_compaction_threshold_days: None,
1077 num_epochs_to_retain_for_checkpoints: if cfg!(msim) { Some(2) } else { None },
1078 enable_compaction_filter: cfg!(test) || cfg!(msim),
1079 num_epochs_to_retain_for_indexes: None,
1080 }
1081 }
1082}
1083
1084impl AuthorityStorePruningConfig {
1085 pub fn set_num_epochs_to_retain(&mut self, num_epochs_to_retain: u64) {
1086 self.num_epochs_to_retain = num_epochs_to_retain;
1087 }
1088
1089 pub fn set_num_epochs_to_retain_for_checkpoints(&mut self, num_epochs_to_retain: Option<u64>) {
1090 self.num_epochs_to_retain_for_checkpoints = num_epochs_to_retain;
1091 }
1092
1093 pub fn num_epochs_to_retain_for_checkpoints(&self) -> Option<u64> {
1094 self.num_epochs_to_retain_for_checkpoints
1095 .map(|n| {
1097 if n < 2 {
1098 info!("num_epochs_to_retain_for_checkpoints must be at least 2, rounding up from {}", n);
1099 2
1100 } else {
1101 n
1102 }
1103 })
1104 }
1105}
1106
1107#[derive(Debug, Clone, Deserialize, Serialize)]
1108#[serde(rename_all = "kebab-case")]
1109pub struct MetricsConfig {
1110 #[serde(skip_serializing_if = "Option::is_none")]
1111 pub push_interval_seconds: Option<u64>,
1112 #[serde(skip_serializing_if = "Option::is_none")]
1113 pub push_url: Option<String>,
1114}
1115
1116#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1117#[serde(rename_all = "kebab-case")]
1118pub struct DBCheckpointConfig {
1119 #[serde(default)]
1120 pub perform_db_checkpoints_at_epoch_end: bool,
1121 #[serde(skip_serializing_if = "Option::is_none")]
1122 pub checkpoint_path: Option<PathBuf>,
1123 #[serde(skip_serializing_if = "Option::is_none")]
1124 pub object_store_config: Option<ObjectStoreConfig>,
1125 #[serde(skip_serializing_if = "Option::is_none")]
1126 pub perform_index_db_checkpoints_at_epoch_end: Option<bool>,
1127 #[serde(skip_serializing_if = "Option::is_none")]
1128 pub prune_and_compact_before_upload: Option<bool>,
1129}
1130
1131#[derive(Debug, Clone)]
1132pub struct ArchiveReaderConfig {
1133 pub remote_store_config: ObjectStoreConfig,
1134 pub download_concurrency: NonZeroUsize,
1135 pub use_for_pruning_watermark: bool,
1136}
1137
1138#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1139#[serde(rename_all = "kebab-case")]
1140pub struct StateArchiveConfig {
1141 #[serde(skip_serializing_if = "Option::is_none")]
1142 pub object_store_config: Option<ObjectStoreConfig>,
1143 pub concurrency: usize,
1144 pub use_for_pruning_watermark: bool,
1145}
1146
1147#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1155#[serde(rename_all = "kebab-case")]
1156pub struct StateSnapshotConfig {
1157 #[serde(skip_serializing_if = "Option::is_none")]
1158 pub object_store_config: Option<ObjectStoreConfig>,
1159 pub concurrency: usize,
1160}
1161
1162#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1163#[serde(rename_all = "kebab-case")]
1164pub struct TransactionKeyValueStoreWriteConfig {
1165 pub aws_access_key_id: String,
1166 pub aws_secret_access_key: String,
1167 pub aws_region: String,
1168 pub table_name: String,
1169 pub bucket_name: String,
1170 pub concurrency: usize,
1171}
1172
1173#[derive(Clone, Debug, Deserialize, Serialize)]
1178#[serde(rename_all = "kebab-case")]
1179pub struct AuthorityOverloadConfig {
1180 #[serde(default = "default_max_txn_age_in_queue")]
1184 pub max_txn_age_in_queue: Duration,
1185
1186 #[serde(default = "default_overload_monitor_interval")]
1188 pub overload_monitor_interval: Duration,
1189
1190 #[serde(default = "default_execution_queue_latency_soft_limit")]
1192 pub execution_queue_latency_soft_limit: Duration,
1193
1194 #[serde(default = "default_execution_queue_latency_hard_limit")]
1197 pub execution_queue_latency_hard_limit: Duration,
1198
1199 #[serde(default = "default_max_load_shedding_percentage")]
1201 pub max_load_shedding_percentage: u32,
1202
1203 #[serde(default = "default_min_load_shedding_percentage_above_hard_limit")]
1206 pub min_load_shedding_percentage_above_hard_limit: u32,
1207
1208 #[serde(default = "default_safe_transaction_ready_rate")]
1211 pub safe_transaction_ready_rate: u32,
1212
1213 #[serde(default = "default_check_system_overload_at_signing")]
1216 pub check_system_overload_at_signing: bool,
1217
1218 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1221 pub check_system_overload_at_execution: bool,
1222
1223 #[serde(default = "default_max_transaction_manager_queue_length")]
1227 pub max_transaction_manager_queue_length: usize,
1228
1229 #[serde(default = "default_max_transaction_manager_per_object_queue_length")]
1232 pub max_transaction_manager_per_object_queue_length: usize,
1233
1234 #[serde(default = "default_max_transaction_manager_queue_length_soft_limit_pct")]
1238 pub max_transaction_manager_queue_length_soft_limit_pct: u32,
1239}
1240
1241impl AuthorityOverloadConfig {
1242 pub fn max_transaction_manager_queue_length_soft_limit_pct(&self) -> u32 {
1245 self.max_transaction_manager_queue_length_soft_limit_pct
1246 .min(100)
1247 }
1248}
1249
1250fn default_max_txn_age_in_queue() -> Duration {
1251 Duration::from_millis(500)
1252}
1253
1254fn default_overload_monitor_interval() -> Duration {
1255 Duration::from_secs(10)
1256}
1257
1258fn default_execution_queue_latency_soft_limit() -> Duration {
1259 Duration::from_secs(1)
1260}
1261
1262fn default_execution_queue_latency_hard_limit() -> Duration {
1263 Duration::from_secs(10)
1264}
1265
1266fn default_max_load_shedding_percentage() -> u32 {
1267 95
1268}
1269
1270fn default_min_load_shedding_percentage_above_hard_limit() -> u32 {
1271 50
1272}
1273
1274fn default_safe_transaction_ready_rate() -> u32 {
1275 100
1276}
1277
1278fn default_check_system_overload_at_signing() -> bool {
1279 true
1280}
1281
1282fn default_max_transaction_manager_queue_length() -> usize {
1283 100_000
1284}
1285
1286fn default_max_transaction_manager_queue_length_soft_limit_pct() -> u32 {
1287 50
1288}
1289
1290fn default_max_transaction_manager_per_object_queue_length() -> usize {
1291 20
1292}
1293
1294impl Default for AuthorityOverloadConfig {
1295 fn default() -> Self {
1296 Self {
1297 max_txn_age_in_queue: default_max_txn_age_in_queue(),
1298 overload_monitor_interval: default_overload_monitor_interval(),
1299 execution_queue_latency_soft_limit: default_execution_queue_latency_soft_limit(),
1300 execution_queue_latency_hard_limit: default_execution_queue_latency_hard_limit(),
1301 max_load_shedding_percentage: default_max_load_shedding_percentage(),
1302 min_load_shedding_percentage_above_hard_limit:
1303 default_min_load_shedding_percentage_above_hard_limit(),
1304 safe_transaction_ready_rate: default_safe_transaction_ready_rate(),
1305 check_system_overload_at_signing: true,
1306 check_system_overload_at_execution: false,
1307 max_transaction_manager_queue_length: default_max_transaction_manager_queue_length(),
1308 max_transaction_manager_queue_length_soft_limit_pct:
1309 default_max_transaction_manager_queue_length_soft_limit_pct(),
1310 max_transaction_manager_per_object_queue_length:
1311 default_max_transaction_manager_per_object_queue_length(),
1312 }
1313 }
1314}
1315
1316fn default_authority_overload_config() -> AuthorityOverloadConfig {
1317 AuthorityOverloadConfig::default()
1318}
1319
1320fn default_traffic_controller_policy_config() -> Option<PolicyConfig> {
1321 Some(PolicyConfig::default_dos_protection_policy())
1322}
1323
1324#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1325pub struct Genesis {
1326 #[serde(flatten)]
1327 location: Option<GenesisLocation>,
1328
1329 #[serde(skip)]
1330 genesis: once_cell::sync::OnceCell<genesis::Genesis>,
1331}
1332
1333impl Genesis {
1334 pub fn new(genesis: genesis::Genesis) -> Self {
1335 Self {
1336 location: Some(GenesisLocation::InPlace {
1337 genesis: Box::new(genesis),
1338 }),
1339 genesis: Default::default(),
1340 }
1341 }
1342
1343 pub fn new_from_file<P: Into<PathBuf>>(path: P) -> Self {
1344 Self {
1345 location: Some(GenesisLocation::File {
1346 genesis_file_location: path.into(),
1347 }),
1348 genesis: Default::default(),
1349 }
1350 }
1351
1352 pub fn new_empty() -> Self {
1353 Self {
1354 location: None,
1355 genesis: Default::default(),
1356 }
1357 }
1358
1359 pub fn genesis(&self) -> Result<&genesis::Genesis> {
1360 match &self.location {
1361 Some(GenesisLocation::InPlace { genesis }) => Ok(genesis),
1362 Some(GenesisLocation::File {
1363 genesis_file_location,
1364 }) => self
1365 .genesis
1366 .get_or_try_init(|| genesis::Genesis::load(genesis_file_location)),
1367 None => anyhow::bail!("no genesis location set"),
1368 }
1369 }
1370}
1371
1372#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1373#[serde(untagged)]
1374enum GenesisLocation {
1375 InPlace {
1376 genesis: Box<genesis::Genesis>,
1377 },
1378 File {
1379 #[serde(rename = "genesis-file-location")]
1380 genesis_file_location: PathBuf,
1381 },
1382}
1383
1384#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
1387pub struct KeyPairWithPath {
1388 #[serde(flatten)]
1389 location: KeyPairLocation,
1390
1391 #[serde(skip)]
1392 keypair: OnceCell<Arc<IotaKeyPair>>,
1393}
1394
1395#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1396#[serde(untagged)]
1397enum KeyPairLocation {
1398 InPlace {
1399 #[serde(with = "bech32_formatted_keypair")]
1400 value: Arc<IotaKeyPair>,
1401 },
1402 File {
1403 path: PathBuf,
1404 },
1405}
1406
1407impl KeyPairWithPath {
1408 pub fn new(kp: IotaKeyPair) -> Self {
1409 let cell: OnceCell<Arc<IotaKeyPair>> = OnceCell::new();
1410 let arc_kp = Arc::new(kp);
1411 cell.set(arc_kp.clone()).expect("failed to set keypair");
1414 Self {
1415 location: KeyPairLocation::InPlace { value: arc_kp },
1416 keypair: cell,
1417 }
1418 }
1419
1420 pub fn new_from_path(path: PathBuf) -> Self {
1421 let cell: OnceCell<Arc<IotaKeyPair>> = OnceCell::new();
1422 cell.set(Arc::new(read_keypair_from_file(&path).unwrap_or_else(
1425 |e| panic!("invalid keypair file at path {:?}: {e}", &path),
1426 )))
1427 .expect("failed to set keypair");
1428 Self {
1429 location: KeyPairLocation::File { path },
1430 keypair: cell,
1431 }
1432 }
1433
1434 pub fn keypair(&self) -> &IotaKeyPair {
1435 self.keypair
1436 .get_or_init(|| match &self.location {
1437 KeyPairLocation::InPlace { value } => value.clone(),
1438 KeyPairLocation::File { path } => {
1439 Arc::new(
1442 read_keypair_from_file(path).unwrap_or_else(|e| {
1443 panic!("invalid keypair file at path {path:?}: {e}")
1444 }),
1445 )
1446 }
1447 })
1448 .as_ref()
1449 }
1450}
1451
1452#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
1455pub struct AuthorityKeyPairWithPath {
1456 #[serde(flatten)]
1457 location: AuthorityKeyPairLocation,
1458
1459 #[serde(skip)]
1460 keypair: OnceCell<Arc<AuthorityKeyPair>>,
1461}
1462
1463#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1464#[serde(untagged)]
1465enum AuthorityKeyPairLocation {
1466 InPlace { value: Arc<AuthorityKeyPair> },
1467 File { path: PathBuf },
1468}
1469
1470impl AuthorityKeyPairWithPath {
1471 pub fn new(kp: AuthorityKeyPair) -> Self {
1472 let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1473 let arc_kp = Arc::new(kp);
1474 cell.set(arc_kp.clone())
1477 .expect("failed to set authority keypair");
1478 Self {
1479 location: AuthorityKeyPairLocation::InPlace { value: arc_kp },
1480 keypair: cell,
1481 }
1482 }
1483
1484 pub fn new_from_path(path: PathBuf) -> Self {
1485 let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1486 cell.set(Arc::new(
1489 read_authority_keypair_from_file(&path)
1490 .unwrap_or_else(|_| panic!("invalid authority keypair file at path {:?}", &path)),
1491 ))
1492 .expect("failed to set authority keypair");
1493 Self {
1494 location: AuthorityKeyPairLocation::File { path },
1495 keypair: cell,
1496 }
1497 }
1498
1499 pub fn authority_keypair(&self) -> &AuthorityKeyPair {
1500 self.keypair
1501 .get_or_init(|| match &self.location {
1502 AuthorityKeyPairLocation::InPlace { value } => value.clone(),
1503 AuthorityKeyPairLocation::File { path } => {
1504 Arc::new(
1507 read_authority_keypair_from_file(path).unwrap_or_else(|_| {
1508 panic!("invalid authority keypair file {:?}", &path)
1509 }),
1510 )
1511 }
1512 })
1513 .as_ref()
1514 }
1515}
1516
1517#[derive(Clone, Debug, Deserialize, Serialize, Default)]
1520#[serde(rename_all = "kebab-case")]
1521pub struct StateDebugDumpConfig {
1522 #[serde(skip_serializing_if = "Option::is_none")]
1523 pub dump_file_directory: Option<PathBuf>,
1524}
1525
1526#[cfg(test)]
1527mod tests {
1528 use std::path::PathBuf;
1529
1530 use fastcrypto::traits::KeyPair;
1531 use iota_keys::keypair_file::{write_authority_keypair_to_file, write_keypair_to_file};
1532 use iota_types::crypto::{
1533 AuthorityKeyPair, IotaKeyPair, NetworkKeyPair, get_key_pair_from_rng,
1534 };
1535 use rand::{SeedableRng, rngs::StdRng};
1536
1537 use super::Genesis;
1538 use crate::NodeConfig;
1539
1540 #[test]
1541 fn serialize_genesis_from_file() {
1542 let g = Genesis::new_from_file("path/to/file");
1543
1544 let s = serde_yaml::to_string(&g).unwrap();
1545 assert_eq!("---\ngenesis-file-location: path/to/file\n", s);
1546 let loaded_genesis: Genesis = serde_yaml::from_str(&s).unwrap();
1547 assert_eq!(g, loaded_genesis);
1548 }
1549
1550 #[test]
1551 fn fullnode_template() {
1552 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1553
1554 let _template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1555 }
1556
1557 #[test]
1558 fn enable_soft_locking_defaults_to_enabled() {
1559 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1562
1563 let config: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1564 assert!(config.enable_soft_locking);
1565 }
1566
1567 #[test]
1568 fn load_key_pairs_to_node_config() {
1569 let authority_key_pair: AuthorityKeyPair =
1570 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1571 let protocol_key_pair: NetworkKeyPair =
1572 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1573 let network_key_pair: NetworkKeyPair =
1574 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1575
1576 write_authority_keypair_to_file(&authority_key_pair, PathBuf::from("authority.key"))
1577 .unwrap();
1578 write_keypair_to_file(
1579 &IotaKeyPair::Ed25519(protocol_key_pair.copy()),
1580 PathBuf::from("protocol.key"),
1581 )
1582 .unwrap();
1583 write_keypair_to_file(
1584 &IotaKeyPair::Ed25519(network_key_pair.copy()),
1585 PathBuf::from("network.key"),
1586 )
1587 .unwrap();
1588
1589 const TEMPLATE: &str = include_str!("../data/fullnode-template-with-path.yaml");
1590 let template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1591 assert_eq!(
1592 template.authority_key_pair().public(),
1593 authority_key_pair.public()
1594 );
1595 assert_eq!(
1596 template.network_key_pair().public(),
1597 network_key_pair.public()
1598 );
1599 assert_eq!(
1600 template.protocol_key_pair().public(),
1601 protocol_key_pair.public()
1602 );
1603 }
1604}
1605
1606#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
1610pub enum RunWithRange {
1611 Epoch(EpochId),
1612 Checkpoint(CheckpointSequenceNumber),
1613}
1614
1615impl RunWithRange {
1616 pub fn is_epoch_gt(&self, epoch_id: EpochId) -> bool {
1618 matches!(self, RunWithRange::Epoch(e) if epoch_id > *e)
1619 }
1620
1621 pub fn matches_checkpoint(&self, seq_num: CheckpointSequenceNumber) -> bool {
1622 matches!(self, RunWithRange::Checkpoint(seq) if *seq == seq_num)
1623 }
1624
1625 pub fn into_checkpoint_bound(self) -> Option<CheckpointSequenceNumber> {
1626 match self {
1627 RunWithRange::Epoch(_) => None,
1628 RunWithRange::Checkpoint(seq) => Some(seq),
1629 }
1630 }
1631}
1632
1633mod bech32_formatted_keypair {
1637 use std::ops::Deref;
1638
1639 use iota_types::crypto::{EncodeDecodeBase64, IotaKeyPair};
1640 use serde::{Deserialize, Deserializer, Serializer};
1641
1642 pub fn serialize<S, T>(kp: &T, serializer: S) -> Result<S::Ok, S::Error>
1643 where
1644 S: Serializer,
1645 T: Deref<Target = IotaKeyPair>,
1646 {
1647 use serde::ser::Error;
1648
1649 let s = kp.encode().map_err(Error::custom)?;
1651
1652 serializer.serialize_str(&s)
1653 }
1654
1655 pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
1656 where
1657 D: Deserializer<'de>,
1658 T: From<IotaKeyPair>,
1659 {
1660 use serde::de::Error;
1661
1662 let s = String::deserialize(deserializer)?;
1663
1664 IotaKeyPair::decode(&s)
1666 .or_else(|_| {
1667 IotaKeyPair::decode_base64(&s)
1669 })
1670 .map(Into::into)
1671 .map_err(Error::custom)
1672 }
1673}