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