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, traits::ToFromBytes};
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::ToFromBytes as _;
19use iota_sdk_types::Address;
20use iota_types::{
21 committee::EpochId,
22 crypto::{
23 AccountKeyPair, AuthorityKeyPair, AuthorityPublicKeyBytes, IotaKeyPair, KeypairTraits,
24 NetworkKeyPair, get_key_pair_from_rng,
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)]
177 pub db_checkpoint_config: DBCheckpointConfig,
178
179 #[serde(default)]
181 pub expensive_safety_check_config: ExpensiveSafetyCheckConfig,
182
183 #[serde(default)]
187 pub transaction_deny_config: TransactionDenyConfig,
188
189 #[serde(default)]
195 pub certificate_deny_config: CertificateDenyConfig,
196
197 #[serde(default)]
200 pub state_debug_dump_config: StateDebugDumpConfig,
201
202 #[serde(default)]
203 pub checkpoint_archive_config: Option<CheckpointArchiveConfig>,
204
205 #[serde(default)]
207 pub state_snapshot_write_config: StateSnapshotConfig,
208
209 #[serde(default)]
210 pub indexer_max_subscriptions: Option<usize>,
211
212 #[serde(default = "default_transaction_kv_store_config")]
213 pub transaction_kv_store_read_config: TransactionKeyValueStoreReadConfig,
214
215 #[serde(skip_serializing_if = "Option::is_none")]
217 pub transaction_kv_store_write_config: Option<TransactionKeyValueStoreWriteConfig>,
218
219 #[serde(default = "default_authority_overload_config")]
222 pub authority_overload_config: AuthorityOverloadConfig,
223
224 #[serde(skip_serializing_if = "Option::is_none")]
228 pub run_with_range: Option<RunWithRange>,
229
230 #[serde(
232 skip_serializing_if = "Option::is_none",
233 default = "default_traffic_controller_policy_config"
234 )]
235 pub policy_config: Option<PolicyConfig>,
236
237 #[serde(skip_serializing_if = "Option::is_none")]
238 pub firewall_config: Option<RemoteFirewallConfig>,
239
240 #[serde(default)]
241 pub execution_cache_config: ExecutionCacheConfig,
242
243 #[serde(default = "default_full_checkpoint_contents_cache_size_mb")]
254 pub full_checkpoint_contents_cache_size_mb: usize,
255
256 #[serde(default = "bool_true")]
257 pub enable_validator_tx_finalizer: bool,
258
259 #[serde(default = "bool_true")]
265 pub enable_soft_locking: bool,
266
267 #[serde(default)]
268 pub verifier_signing_config: VerifierSigningConfig,
269
270 #[serde(skip_serializing_if = "Option::is_none")]
274 pub enable_db_write_stall: Option<bool>,
275
276 #[serde(default, skip_serializing_if = "Option::is_none")]
277 pub iota_names_config: Option<IotaNamesConfig>,
278
279 #[serde(default)]
281 pub enable_grpc_api: bool,
282 #[serde(
283 default = "default_grpc_api_config",
284 skip_serializing_if = "Option::is_none"
285 )]
286 pub grpc_api_config: Option<GrpcApiConfig>,
287
288 #[serde(skip_serializing_if = "Option::is_none")]
293 pub chain_override_for_testing: Option<Chain>,
294
295 #[serde(default, skip_serializing_if = "Option::is_none")]
298 pub validator_client_monitor_config:
299 Option<crate::validator_client_monitor_config::ValidatorClientMonitorConfig>,
300}
301
302#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
303#[serde(rename_all = "kebab-case")]
304pub struct TlsConfig {
305 cert: String,
307 key: String,
309}
310
311impl TlsConfig {
312 pub fn cert(&self) -> &str {
313 &self.cert
314 }
315
316 pub fn key(&self) -> &str {
317 &self.key
318 }
319}
320
321#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
323#[serde(rename_all = "kebab-case")]
324pub struct GrpcApiConfig {
325 #[serde(default = "default_grpc_api_address")]
327 pub address: SocketAddr,
328
329 #[serde(skip_serializing_if = "Option::is_none")]
333 pub tls: Option<TlsConfig>,
334
335 #[serde(default = "default_grpc_api_max_message_size_bytes")]
337 pub max_message_size_bytes: u32,
338
339 #[serde(default = "default_grpc_api_broadcast_buffer_size")]
341 pub broadcast_buffer_size: u32,
342
343 #[serde(default = "default_grpc_api_max_concurrent_stream_subscribers")]
349 pub max_concurrent_stream_subscribers: u32,
350
351 #[serde(default = "default_grpc_api_max_json_move_value_size")]
354 pub max_json_move_value_size: usize,
355
356 #[serde(default = "default_grpc_api_max_execute_transaction_batch_size")]
359 pub max_execute_transaction_batch_size: u32,
360
361 #[serde(default = "default_grpc_api_max_simulate_transaction_batch_size")]
364 pub max_simulate_transaction_batch_size: u32,
365
366 #[serde(default = "default_grpc_api_max_get_objects_batch_size")]
368 pub max_get_objects_batch_size: u32,
369
370 #[serde(default = "default_grpc_api_max_get_transactions_batch_size")]
373 pub max_get_transactions_batch_size: u32,
374
375 #[serde(default = "default_grpc_api_max_checkpoint_inclusion_timeout_ms")]
379 pub max_checkpoint_inclusion_timeout_ms: u64,
380}
381
382fn default_grpc_api_address() -> SocketAddr {
383 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 50051)
384}
385
386fn default_grpc_api_broadcast_buffer_size() -> u32 {
387 100
388}
389
390fn default_grpc_api_max_concurrent_stream_subscribers() -> u32 {
391 1024
392}
393
394fn default_grpc_api_max_message_size_bytes() -> u32 {
395 128 * 1024 * 1024 }
397
398fn default_grpc_api_max_json_move_value_size() -> usize {
399 1024 * 1024 }
401
402fn default_grpc_api_max_execute_transaction_batch_size() -> u32 {
403 20
404}
405
406fn default_grpc_api_max_simulate_transaction_batch_size() -> u32 {
407 20
408}
409
410fn default_grpc_api_max_get_objects_batch_size() -> u32 {
411 1000
412}
413
414fn default_grpc_api_max_get_transactions_batch_size() -> u32 {
415 1000
416}
417
418fn default_grpc_api_max_checkpoint_inclusion_timeout_ms() -> u64 {
419 60_000 }
421
422impl Default for GrpcApiConfig {
423 fn default() -> Self {
424 Self {
425 address: default_grpc_api_address(),
426 tls: None,
427 max_message_size_bytes: default_grpc_api_max_message_size_bytes(),
428 broadcast_buffer_size: default_grpc_api_broadcast_buffer_size(),
429 max_concurrent_stream_subscribers: default_grpc_api_max_concurrent_stream_subscribers(),
430 max_json_move_value_size: default_grpc_api_max_json_move_value_size(),
431 max_execute_transaction_batch_size: default_grpc_api_max_execute_transaction_batch_size(
432 ),
433 max_simulate_transaction_batch_size:
434 default_grpc_api_max_simulate_transaction_batch_size(),
435 max_get_objects_batch_size: default_grpc_api_max_get_objects_batch_size(),
436 max_get_transactions_batch_size: default_grpc_api_max_get_transactions_batch_size(),
437 max_checkpoint_inclusion_timeout_ms:
438 default_grpc_api_max_checkpoint_inclusion_timeout_ms(),
439 }
440 }
441}
442
443impl GrpcApiConfig {
444 const GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE: u32 = 4 * 1024 * 1024; const GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES: u32 =
448 Self::GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE;
449
450 pub fn tls_config(&self) -> Option<&TlsConfig> {
451 self.tls.as_ref()
452 }
453
454 pub fn max_message_size_bytes(&self) -> u32 {
455 self.max_message_size_bytes
457 .max(Self::GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES)
458 }
459
460 pub fn max_message_size_client_bytes(&self, client_max_message_size_bytes: Option<u32>) -> u32 {
464 client_max_message_size_bytes
465 .unwrap_or(Self::GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE)
468 .clamp(
470 Self::GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES,
471 self.max_message_size_bytes(),
472 )
473 }
474}
475
476#[derive(Clone, Debug, Default, Deserialize, Serialize)]
477#[serde(rename_all = "kebab-case")]
478pub struct ExecutionCacheConfig {
479 #[serde(default)]
480 pub writeback_cache: WritebackCacheConfig,
481}
482
483#[derive(Clone, Debug, Default, Deserialize, Serialize)]
484#[serde(rename_all = "kebab-case")]
485pub struct WritebackCacheConfig {
486 #[serde(default, skip_serializing_if = "Option::is_none")]
489 pub max_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
492 pub package_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
495 pub object_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
497 pub marker_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
499 pub object_by_id_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
502 pub transaction_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
504 pub executed_effect_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
506 pub effect_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
509 pub events_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
512 pub transaction_objects_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
517 pub backpressure_threshold: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
523 pub backpressure_threshold_for_rpc: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
533 pub backpressure_soft_limit_pct: Option<u32>,
534}
535
536impl WritebackCacheConfig {
537 pub fn max_cache_size(&self) -> u64 {
538 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_MAX")
539 .ok()
540 .and_then(|s| s.parse().ok())
541 .or(self.max_cache_size)
542 .unwrap_or(100000)
543 }
544
545 pub fn package_cache_size(&self) -> u64 {
546 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_PACKAGE")
547 .ok()
548 .and_then(|s| s.parse().ok())
549 .or(self.package_cache_size)
550 .unwrap_or(1000)
551 }
552
553 pub fn object_cache_size(&self) -> u64 {
554 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_OBJECT")
555 .ok()
556 .and_then(|s| s.parse().ok())
557 .or(self.object_cache_size)
558 .unwrap_or_else(|| self.max_cache_size())
559 }
560
561 pub fn marker_cache_size(&self) -> u64 {
562 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_MARKER")
563 .ok()
564 .and_then(|s| s.parse().ok())
565 .or(self.marker_cache_size)
566 .unwrap_or_else(|| self.object_cache_size())
567 }
568
569 pub fn object_by_id_cache_size(&self) -> u64 {
570 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_OBJECT_BY_ID")
571 .ok()
572 .and_then(|s| s.parse().ok())
573 .or(self.object_by_id_cache_size)
574 .unwrap_or_else(|| self.object_cache_size())
575 }
576
577 pub fn transaction_cache_size(&self) -> u64 {
578 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_TRANSACTION")
579 .ok()
580 .and_then(|s| s.parse().ok())
581 .or(self.transaction_cache_size)
582 .unwrap_or_else(|| self.max_cache_size())
583 }
584
585 pub fn executed_effect_cache_size(&self) -> u64 {
586 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EXECUTED_EFFECT")
587 .ok()
588 .and_then(|s| s.parse().ok())
589 .or(self.executed_effect_cache_size)
590 .unwrap_or_else(|| self.transaction_cache_size())
591 }
592
593 pub fn effect_cache_size(&self) -> u64 {
594 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EFFECT")
595 .ok()
596 .and_then(|s| s.parse().ok())
597 .or(self.effect_cache_size)
598 .unwrap_or_else(|| self.executed_effect_cache_size())
599 }
600
601 pub fn events_cache_size(&self) -> u64 {
602 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EVENTS")
603 .ok()
604 .and_then(|s| s.parse().ok())
605 .or(self.events_cache_size)
606 .unwrap_or_else(|| self.transaction_cache_size())
607 }
608
609 pub fn transaction_objects_cache_size(&self) -> u64 {
610 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_TRANSACTION_OBJECTS")
611 .ok()
612 .and_then(|s| s.parse().ok())
613 .or(self.transaction_objects_cache_size)
614 .unwrap_or(1000)
615 }
616
617 pub fn backpressure_threshold(&self) -> u64 {
618 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_THRESHOLD")
619 .ok()
620 .and_then(|s| s.parse().ok())
621 .or(self.backpressure_threshold)
622 .unwrap_or(100_000)
623 }
624
625 pub fn backpressure_threshold_for_rpc(&self) -> u64 {
626 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_THRESHOLD_FOR_RPC")
627 .ok()
628 .and_then(|s| s.parse().ok())
629 .or(self.backpressure_threshold_for_rpc)
630 .unwrap_or(self.backpressure_threshold())
631 }
632
633 pub fn backpressure_soft_limit_pct(&self) -> u32 {
634 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_SOFT_LIMIT_PCT")
635 .ok()
636 .and_then(|s| s.parse().ok())
637 .or(self.backpressure_soft_limit_pct)
638 .unwrap_or(50)
639 .min(100)
640 }
641}
642
643#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
644#[serde(rename_all = "lowercase")]
645pub enum ServerType {
646 WebSocket,
647 Http,
648 Both,
649}
650
651#[derive(Clone, Debug, Deserialize, Serialize)]
652#[serde(rename_all = "kebab-case")]
653pub struct TransactionKeyValueStoreReadConfig {
654 #[serde(default = "default_base_url")]
655 pub base_url: String,
656
657 #[serde(default = "default_cache_size")]
658 pub cache_size: u64,
659}
660
661impl Default for TransactionKeyValueStoreReadConfig {
662 fn default() -> Self {
663 Self {
664 base_url: default_base_url(),
665 cache_size: default_cache_size(),
666 }
667 }
668}
669
670fn default_base_url() -> String {
671 "".to_string()
672}
673
674fn default_cache_size() -> u64 {
675 100_000
676}
677
678fn default_transaction_kv_store_config() -> TransactionKeyValueStoreReadConfig {
679 TransactionKeyValueStoreReadConfig::default()
680}
681
682fn default_authority_store_pruning_config() -> AuthorityStorePruningConfig {
683 AuthorityStorePruningConfig::default()
684}
685
686pub fn default_enable_index_processing() -> bool {
687 true
688}
689
690fn default_grpc_address() -> Multiaddr {
691 "/ip4/0.0.0.0/tcp/8080".parse().unwrap()
692}
693fn default_authority_key_pair() -> AuthorityKeyPairWithPath {
694 AuthorityKeyPairWithPath::new(get_key_pair_from_rng::<AuthorityKeyPair, _>(&mut OsRng).1)
695}
696
697fn default_key_pair() -> KeyPairWithPath {
698 KeyPairWithPath::new(
699 get_key_pair_from_rng::<AccountKeyPair, _>(&mut OsRng)
700 .1
701 .into(),
702 )
703}
704
705fn default_metrics_address() -> SocketAddr {
706 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9184)
707}
708
709pub fn default_admin_interface_address() -> SocketAddr {
710 SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 1337)
711}
712
713pub fn default_json_rpc_address() -> SocketAddr {
714 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9000)
715}
716
717pub fn default_grpc_api_config() -> Option<GrpcApiConfig> {
718 Some(GrpcApiConfig::default())
719}
720
721pub fn default_grpc_concurrency_limit_per_core() -> NonZeroUsize {
722 NonZeroUsize::new(1000).unwrap()
723}
724
725pub fn default_end_of_epoch_broadcast_channel_capacity() -> usize {
726 128
727}
728
729pub fn default_full_checkpoint_contents_cache_size_mb() -> usize {
730 DEFAULT_FULL_CHECKPOINT_CONTENTS_CACHE_SIZE_MB
731}
732
733pub fn bool_true() -> bool {
734 true
735}
736
737impl Config for NodeConfig {}
738
739impl NodeConfig {
740 pub fn authority_key_pair(&self) -> &AuthorityKeyPair {
741 self.authority_key_pair.authority_keypair()
742 }
743
744 pub fn protocol_key_pair(&self) -> &NetworkKeyPair {
745 self.protocol_key_pair.ed25519_keypair()
746 }
747
748 pub fn network_key_pair(&self) -> &NetworkKeyPair {
749 self.network_key_pair.ed25519_keypair()
750 }
751
752 pub fn authority_public_key(&self) -> AuthorityPublicKeyBytes {
753 self.authority_key_pair().public().into()
754 }
755
756 pub fn db_path(&self) -> PathBuf {
757 self.db_path.join("live")
758 }
759
760 pub fn db_checkpoint_path(&self) -> PathBuf {
761 self.db_path.join("db_checkpoints")
762 }
763
764 pub fn snapshot_path(&self) -> PathBuf {
765 self.db_path.join("snapshot")
766 }
767
768 pub fn network_address(&self) -> &Multiaddr {
769 &self.network_address
770 }
771
772 pub fn consensus_config(&self) -> Option<&ConsensusConfig> {
773 self.consensus_config.as_ref()
774 }
775
776 pub fn genesis(&self) -> Result<&genesis::Genesis> {
777 self.genesis.genesis()
778 }
779
780 pub fn load_migration_tx_data(&self) -> Result<MigrationTxData> {
781 let Some(location) = &self.migration_tx_data_path else {
782 anyhow::bail!("no file location set");
783 };
784
785 let migration_tx_data = MigrationTxData::load(location)?;
787
788 migration_tx_data.validate_from_genesis(self.genesis.genesis()?)?;
790 Ok(migration_tx_data)
791 }
792
793 pub fn iota_address(&self) -> Address {
794 (&self.account_key_pair.keypair().public()).into()
795 }
796
797 pub fn checkpoint_archive_config(&self) -> Option<&CheckpointArchiveConfig> {
798 self.checkpoint_archive_config.as_ref()
799 }
800
801 pub fn jsonrpc_server_type(&self) -> ServerType {
802 self.jsonrpc_server_type.unwrap_or(ServerType::Http)
803 }
804}
805
806#[derive(Debug, Clone, Deserialize, Serialize)]
807#[serde(rename_all = "kebab-case")]
808pub struct ConsensusConfig {
809 pub db_path: PathBuf,
811
812 pub db_retention_epochs: Option<u64>,
816
817 pub db_pruner_period_secs: Option<u64>,
821
822 pub max_pending_transactions: Option<usize>,
833
834 pub max_submit_position: Option<usize>,
840
841 pub submit_delay_step_override_millis: Option<u64>,
847
848 #[serde(skip_serializing_if = "Option::is_none", alias = "starfish_parameters")]
850 pub parameters: Option<StarfishParameters>,
851
852 #[serde(skip_serializing_if = "Option::is_none")]
858 pub graduated_load_shedding_soft_limit_pct: Option<u32>,
859}
860
861impl ConsensusConfig {
862 pub fn db_path(&self) -> &Path {
863 &self.db_path
864 }
865
866 pub fn max_pending_transactions(&self) -> usize {
870 self.max_pending_transactions.unwrap_or(20_000)
871 }
872
873 pub fn graduated_load_shedding_soft_limit_pct(&self) -> u32 {
878 self.graduated_load_shedding_soft_limit_pct
879 .unwrap_or(50)
880 .min(100)
881 }
882
883 pub fn submit_delay_step_override(&self) -> Option<Duration> {
884 self.submit_delay_step_override_millis
885 .map(Duration::from_millis)
886 }
887
888 pub fn db_retention_epochs(&self) -> u64 {
889 self.db_retention_epochs.unwrap_or(0)
890 }
891
892 pub fn db_pruner_period(&self) -> Duration {
893 self.db_pruner_period_secs
895 .map(Duration::from_secs)
896 .unwrap_or(Duration::from_secs(3_600))
897 }
898}
899
900#[derive(Clone, Debug, Deserialize, Serialize)]
901#[serde(rename_all = "kebab-case")]
902pub struct CheckpointExecutorConfig {
903 #[serde(default = "default_checkpoint_execution_max_concurrency")]
908 pub checkpoint_execution_max_concurrency: usize,
909
910 #[serde(default = "default_local_execution_timeout_sec")]
916 pub local_execution_timeout_sec: u64,
917
918 #[serde(default, skip_serializing_if = "Option::is_none")]
923 pub data_ingestion_dir: Option<PathBuf>,
924}
925
926#[derive(Clone, Debug, Default, Deserialize, Serialize)]
927#[serde(rename_all = "kebab-case")]
928pub struct ExpensiveSafetyCheckConfig {
929 #[serde(default)]
934 enable_epoch_iota_conservation_check: bool,
935
936 #[serde(default)]
940 enable_deep_per_tx_iota_conservation_check: bool,
941
942 #[serde(default)]
945 force_disable_epoch_iota_conservation_check: bool,
946
947 #[serde(default)]
950 enable_state_consistency_check: bool,
951
952 #[serde(default)]
954 force_disable_state_consistency_check: bool,
955
956 #[serde(default)]
957 enable_secondary_index_checks: bool,
958 }
960
961impl ExpensiveSafetyCheckConfig {
962 pub fn new_enable_all() -> Self {
963 Self {
964 enable_epoch_iota_conservation_check: true,
965 enable_deep_per_tx_iota_conservation_check: true,
966 force_disable_epoch_iota_conservation_check: false,
967 enable_state_consistency_check: true,
968 force_disable_state_consistency_check: false,
969 enable_secondary_index_checks: false, }
971 }
972
973 pub fn new_disable_all() -> Self {
974 Self {
975 enable_epoch_iota_conservation_check: false,
976 enable_deep_per_tx_iota_conservation_check: false,
977 force_disable_epoch_iota_conservation_check: true,
978 enable_state_consistency_check: false,
979 force_disable_state_consistency_check: true,
980 enable_secondary_index_checks: false,
981 }
982 }
983
984 pub fn force_disable_epoch_iota_conservation_check(&mut self) {
985 self.force_disable_epoch_iota_conservation_check = true;
986 }
987
988 pub fn enable_epoch_iota_conservation_check(&self) -> bool {
989 (self.enable_epoch_iota_conservation_check || cfg!(debug_assertions))
990 && !self.force_disable_epoch_iota_conservation_check
991 }
992
993 pub fn force_disable_state_consistency_check(&mut self) {
994 self.force_disable_state_consistency_check = true;
995 }
996
997 pub fn enable_state_consistency_check(&self) -> bool {
998 (self.enable_state_consistency_check || cfg!(debug_assertions))
999 && !self.force_disable_state_consistency_check
1000 }
1001
1002 pub fn enable_deep_per_tx_iota_conservation_check(&self) -> bool {
1003 self.enable_deep_per_tx_iota_conservation_check || cfg!(debug_assertions)
1004 }
1005
1006 pub fn enable_secondary_index_checks(&self) -> bool {
1007 self.enable_secondary_index_checks
1008 }
1009}
1010
1011fn default_checkpoint_execution_max_concurrency() -> usize {
1012 4
1013}
1014
1015fn default_local_execution_timeout_sec() -> u64 {
1016 30
1017}
1018
1019impl Default for CheckpointExecutorConfig {
1020 fn default() -> Self {
1021 Self {
1022 checkpoint_execution_max_concurrency: default_checkpoint_execution_max_concurrency(),
1023 local_execution_timeout_sec: default_local_execution_timeout_sec(),
1024 data_ingestion_dir: None,
1025 }
1026 }
1027}
1028
1029#[derive(Debug, Clone, Deserialize, Serialize)]
1030#[serde(rename_all = "kebab-case")]
1031pub struct AuthorityStorePruningConfig {
1032 #[serde(default = "default_num_latest_epoch_dbs_to_retain")]
1034 pub num_latest_epoch_dbs_to_retain: usize,
1035 #[serde(default)]
1040 pub num_epochs_to_retain: u64,
1041 #[serde(
1046 default = "default_periodic_compaction_threshold_days",
1047 skip_serializing_if = "Option::is_none"
1048 )]
1049 pub periodic_compaction_threshold_days: Option<usize>,
1050 #[serde(skip_serializing_if = "Option::is_none")]
1053 pub num_epochs_to_retain_for_checkpoints: Option<u64>,
1054 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1060 pub enable_compaction_filter: bool,
1061 #[serde(skip_serializing_if = "Option::is_none")]
1062 pub num_epochs_to_retain_for_indexes: Option<u64>,
1063}
1064
1065fn default_num_latest_epoch_dbs_to_retain() -> usize {
1066 3
1067}
1068
1069fn default_periodic_compaction_threshold_days() -> Option<usize> {
1070 Some(1)
1071}
1072
1073impl Default for AuthorityStorePruningConfig {
1074 fn default() -> Self {
1075 Self {
1076 num_latest_epoch_dbs_to_retain: default_num_latest_epoch_dbs_to_retain(),
1077 num_epochs_to_retain: 0,
1078 periodic_compaction_threshold_days: None,
1079 num_epochs_to_retain_for_checkpoints: if cfg!(msim) { Some(2) } else { None },
1080 enable_compaction_filter: cfg!(test) || cfg!(msim),
1081 num_epochs_to_retain_for_indexes: None,
1082 }
1083 }
1084}
1085
1086impl AuthorityStorePruningConfig {
1087 pub fn set_num_epochs_to_retain(&mut self, num_epochs_to_retain: u64) {
1088 self.num_epochs_to_retain = num_epochs_to_retain;
1089 }
1090
1091 pub fn set_num_epochs_to_retain_for_checkpoints(&mut self, num_epochs_to_retain: Option<u64>) {
1092 self.num_epochs_to_retain_for_checkpoints = num_epochs_to_retain;
1093 }
1094
1095 pub fn num_epochs_to_retain_for_checkpoints(&self) -> Option<u64> {
1096 self.num_epochs_to_retain_for_checkpoints
1097 .map(|n| {
1099 if n < 2 {
1100 info!("num_epochs_to_retain_for_checkpoints must be at least 2, rounding up from {}", n);
1101 2
1102 } else {
1103 n
1104 }
1105 })
1106 }
1107}
1108
1109#[derive(Debug, Clone, Deserialize, Serialize)]
1110#[serde(rename_all = "kebab-case")]
1111pub struct MetricsConfig {
1112 #[serde(skip_serializing_if = "Option::is_none")]
1113 pub push_interval_seconds: Option<u64>,
1114 #[serde(skip_serializing_if = "Option::is_none")]
1115 pub push_url: Option<String>,
1116 #[serde(skip_serializing_if = "Option::is_none")]
1117 pub groups: Option<MetricGroups>,
1118}
1119
1120#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1121#[serde(rename_all = "kebab-case")]
1122pub struct DBCheckpointConfig {
1123 #[serde(default)]
1124 pub perform_db_checkpoints_at_epoch_end: bool,
1125 #[serde(skip_serializing_if = "Option::is_none")]
1126 pub checkpoint_path: Option<PathBuf>,
1127 #[serde(skip_serializing_if = "Option::is_none")]
1128 pub object_store_config: Option<ObjectStoreConfig>,
1129 #[serde(skip_serializing_if = "Option::is_none")]
1130 pub perform_index_db_checkpoints_at_epoch_end: Option<bool>,
1131 #[serde(skip_serializing_if = "Option::is_none")]
1132 pub prune_and_compact_before_upload: Option<bool>,
1133}
1134
1135fn default_checkpoint_archive_download_concurrency() -> usize {
1136 10
1137}
1138
1139#[derive(Debug, Clone, Deserialize, Serialize)]
1142#[serde(rename_all = "kebab-case")]
1143pub struct CheckpointArchiveConfig {
1144 pub url: String,
1146 #[serde(default = "default_checkpoint_archive_download_concurrency")]
1148 pub download_concurrency: usize,
1149}
1150
1151#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1159#[serde(rename_all = "kebab-case")]
1160pub struct StateSnapshotConfig {
1161 #[serde(skip_serializing_if = "Option::is_none")]
1162 pub object_store_config: Option<ObjectStoreConfig>,
1163 pub concurrency: usize,
1164}
1165
1166#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1167#[serde(rename_all = "kebab-case")]
1168pub struct TransactionKeyValueStoreWriteConfig {
1169 pub aws_access_key_id: String,
1170 pub aws_secret_access_key: String,
1171 pub aws_region: String,
1172 pub table_name: String,
1173 pub bucket_name: String,
1174 pub concurrency: usize,
1175}
1176
1177#[derive(Clone, Debug, Deserialize, Serialize)]
1182#[serde(rename_all = "kebab-case")]
1183pub struct AuthorityOverloadConfig {
1184 #[serde(default = "default_max_txn_age_in_queue")]
1188 pub max_txn_age_in_queue: Duration,
1189
1190 #[serde(default = "default_overload_monitor_interval")]
1192 pub overload_monitor_interval: Duration,
1193
1194 #[serde(default = "default_execution_queue_latency_soft_limit")]
1196 pub execution_queue_latency_soft_limit: Duration,
1197
1198 #[serde(default = "default_execution_queue_latency_hard_limit")]
1201 pub execution_queue_latency_hard_limit: Duration,
1202
1203 #[serde(default = "default_max_load_shedding_percentage")]
1205 pub max_load_shedding_percentage: u32,
1206
1207 #[serde(default = "default_min_load_shedding_percentage_above_hard_limit")]
1210 pub min_load_shedding_percentage_above_hard_limit: u32,
1211
1212 #[serde(default = "default_safe_transaction_ready_rate")]
1215 pub safe_transaction_ready_rate: u32,
1216
1217 #[serde(default = "default_check_system_overload_at_signing")]
1220 pub check_system_overload_at_signing: bool,
1221
1222 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1225 pub check_system_overload_at_execution: bool,
1226
1227 #[serde(default = "default_max_transaction_manager_queue_length")]
1231 pub max_transaction_manager_queue_length: usize,
1232
1233 #[serde(default = "default_max_transaction_manager_per_object_queue_length")]
1236 pub max_transaction_manager_per_object_queue_length: usize,
1237
1238 #[serde(default = "default_max_transaction_manager_queue_length_soft_limit_pct")]
1242 pub max_transaction_manager_queue_length_soft_limit_pct: u32,
1243}
1244
1245impl AuthorityOverloadConfig {
1246 pub fn max_transaction_manager_queue_length_soft_limit_pct(&self) -> u32 {
1249 self.max_transaction_manager_queue_length_soft_limit_pct
1250 .min(100)
1251 }
1252}
1253
1254fn default_max_txn_age_in_queue() -> Duration {
1255 Duration::from_millis(500)
1256}
1257
1258fn default_overload_monitor_interval() -> Duration {
1259 Duration::from_secs(10)
1260}
1261
1262fn default_execution_queue_latency_soft_limit() -> Duration {
1263 Duration::from_secs(1)
1264}
1265
1266fn default_execution_queue_latency_hard_limit() -> Duration {
1267 Duration::from_secs(10)
1268}
1269
1270fn default_max_load_shedding_percentage() -> u32 {
1271 95
1272}
1273
1274fn default_min_load_shedding_percentage_above_hard_limit() -> u32 {
1275 50
1276}
1277
1278fn default_safe_transaction_ready_rate() -> u32 {
1279 100
1280}
1281
1282fn default_check_system_overload_at_signing() -> bool {
1283 true
1284}
1285
1286fn default_max_transaction_manager_queue_length() -> usize {
1287 100_000
1288}
1289
1290fn default_max_transaction_manager_queue_length_soft_limit_pct() -> u32 {
1291 50
1292}
1293
1294fn default_max_transaction_manager_per_object_queue_length() -> usize {
1295 20
1296}
1297
1298impl Default for AuthorityOverloadConfig {
1299 fn default() -> Self {
1300 Self {
1301 max_txn_age_in_queue: default_max_txn_age_in_queue(),
1302 overload_monitor_interval: default_overload_monitor_interval(),
1303 execution_queue_latency_soft_limit: default_execution_queue_latency_soft_limit(),
1304 execution_queue_latency_hard_limit: default_execution_queue_latency_hard_limit(),
1305 max_load_shedding_percentage: default_max_load_shedding_percentage(),
1306 min_load_shedding_percentage_above_hard_limit:
1307 default_min_load_shedding_percentage_above_hard_limit(),
1308 safe_transaction_ready_rate: default_safe_transaction_ready_rate(),
1309 check_system_overload_at_signing: true,
1310 check_system_overload_at_execution: false,
1311 max_transaction_manager_queue_length: default_max_transaction_manager_queue_length(),
1312 max_transaction_manager_queue_length_soft_limit_pct:
1313 default_max_transaction_manager_queue_length_soft_limit_pct(),
1314 max_transaction_manager_per_object_queue_length:
1315 default_max_transaction_manager_per_object_queue_length(),
1316 }
1317 }
1318}
1319
1320fn default_authority_overload_config() -> AuthorityOverloadConfig {
1321 AuthorityOverloadConfig::default()
1322}
1323
1324fn default_traffic_controller_policy_config() -> Option<PolicyConfig> {
1325 Some(PolicyConfig::default_dos_protection_policy())
1326}
1327
1328#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1329pub struct Genesis {
1330 #[serde(flatten)]
1331 location: Option<GenesisLocation>,
1332
1333 #[serde(skip)]
1334 genesis: once_cell::sync::OnceCell<genesis::Genesis>,
1335}
1336
1337impl Genesis {
1338 pub fn new(genesis: genesis::Genesis) -> Self {
1339 Self {
1340 location: Some(GenesisLocation::InPlace {
1341 genesis: Box::new(genesis),
1342 }),
1343 genesis: Default::default(),
1344 }
1345 }
1346
1347 pub fn new_from_file<P: Into<PathBuf>>(path: P) -> Self {
1348 Self {
1349 location: Some(GenesisLocation::File {
1350 genesis_file_location: path.into(),
1351 }),
1352 genesis: Default::default(),
1353 }
1354 }
1355
1356 pub fn new_empty() -> Self {
1357 Self {
1358 location: None,
1359 genesis: Default::default(),
1360 }
1361 }
1362
1363 pub fn genesis(&self) -> Result<&genesis::Genesis> {
1364 match &self.location {
1365 Some(GenesisLocation::InPlace { genesis }) => Ok(genesis),
1366 Some(GenesisLocation::File {
1367 genesis_file_location,
1368 }) => self
1369 .genesis
1370 .get_or_try_init(|| genesis::Genesis::load(genesis_file_location)),
1371 None => anyhow::bail!("no genesis location set"),
1372 }
1373 }
1374}
1375
1376#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1377#[serde(untagged)]
1378enum GenesisLocation {
1379 InPlace {
1380 genesis: Box<genesis::Genesis>,
1381 },
1382 File {
1383 #[serde(rename = "genesis-file-location")]
1384 genesis_file_location: PathBuf,
1385 },
1386}
1387
1388#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
1391pub struct KeyPairWithPath {
1392 #[serde(flatten)]
1393 location: KeyPairLocation,
1394
1395 #[serde(skip)]
1396 keypair: OnceCell<Arc<IotaKeyPair>>,
1397
1398 #[serde(skip)]
1404 ed25519_keypair: OnceCell<Arc<Ed25519KeyPair>>,
1405}
1406
1407#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1408#[serde(untagged)]
1409enum KeyPairLocation {
1410 InPlace {
1411 #[serde(with = "bech32_formatted_keypair")]
1412 value: Arc<IotaKeyPair>,
1413 },
1414 File {
1415 path: PathBuf,
1416 },
1417}
1418
1419impl KeyPairWithPath {
1420 pub fn new(kp: IotaKeyPair) -> Self {
1421 let cell: OnceCell<Arc<IotaKeyPair>> = 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<IotaKeyPair>> = 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) -> &IotaKeyPair {
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(|| match self.keypair() {
1471 IotaKeyPair::Ed25519(kp) => Arc::new(
1472 Ed25519KeyPair::from_bytes(&kp.to_bytes())
1473 .expect("valid ed25519 private key bytes"),
1474 ),
1475 other => {
1476 panic!("invalid keypair type: {other:?}, only Ed25519 is allowed")
1477 }
1478 })
1479 .as_ref()
1480 }
1481}
1482
1483#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
1486pub struct AuthorityKeyPairWithPath {
1487 #[serde(flatten)]
1488 location: AuthorityKeyPairLocation,
1489
1490 #[serde(skip)]
1491 keypair: OnceCell<Arc<AuthorityKeyPair>>,
1492}
1493
1494#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1495#[serde(untagged)]
1496enum AuthorityKeyPairLocation {
1497 InPlace { value: Arc<AuthorityKeyPair> },
1498 File { path: PathBuf },
1499}
1500
1501impl AuthorityKeyPairWithPath {
1502 pub fn new(kp: AuthorityKeyPair) -> Self {
1503 let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1504 let arc_kp = Arc::new(kp);
1505 cell.set(arc_kp.clone())
1508 .expect("failed to set authority keypair");
1509 Self {
1510 location: AuthorityKeyPairLocation::InPlace { value: arc_kp },
1511 keypair: cell,
1512 }
1513 }
1514
1515 pub fn new_from_path(path: PathBuf) -> Self {
1516 let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1517 cell.set(Arc::new(
1520 read_authority_keypair_from_file(&path)
1521 .unwrap_or_else(|_| panic!("invalid authority keypair file at path {path:?}")),
1522 ))
1523 .expect("failed to set authority keypair");
1524 Self {
1525 location: AuthorityKeyPairLocation::File { path },
1526 keypair: cell,
1527 }
1528 }
1529
1530 pub fn authority_keypair(&self) -> &AuthorityKeyPair {
1531 self.keypair
1532 .get_or_init(|| match &self.location {
1533 AuthorityKeyPairLocation::InPlace { value } => value.clone(),
1534 AuthorityKeyPairLocation::File { path } => {
1535 Arc::new(
1538 read_authority_keypair_from_file(path)
1539 .unwrap_or_else(|_| panic!("invalid authority keypair file {path:?}")),
1540 )
1541 }
1542 })
1543 .as_ref()
1544 }
1545}
1546
1547#[derive(Clone, Debug, Deserialize, Serialize, Default)]
1550#[serde(rename_all = "kebab-case")]
1551pub struct StateDebugDumpConfig {
1552 #[serde(skip_serializing_if = "Option::is_none")]
1553 pub dump_file_directory: Option<PathBuf>,
1554}
1555
1556#[cfg(test)]
1557mod tests {
1558 use std::path::PathBuf;
1559
1560 use fastcrypto::traits::KeyPair;
1561 use iota_keys::keypair_file::{write_authority_keypair_to_file, write_keypair_to_file};
1562 use iota_types::crypto::{AuthorityKeyPair, NetworkKeyPair, get_key_pair_from_rng};
1563 use rand::{SeedableRng, rngs::StdRng};
1564
1565 use super::Genesis;
1566 use crate::NodeConfig;
1567
1568 #[test]
1569 fn serialize_genesis_from_file() {
1570 let g = Genesis::new_from_file("path/to/file");
1571
1572 let s = serde_yaml::to_string(&g).unwrap();
1573 assert_eq!("---\ngenesis-file-location: path/to/file\n", s);
1574 let loaded_genesis: Genesis = serde_yaml::from_str(&s).unwrap();
1575 assert_eq!(g, loaded_genesis);
1576 }
1577
1578 #[test]
1579 fn fullnode_template() {
1580 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1581
1582 let _template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1583 }
1584
1585 #[test]
1586 fn enable_soft_locking_defaults_to_enabled() {
1587 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1590
1591 let config: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1592 assert!(config.enable_soft_locking);
1593 }
1594
1595 #[test]
1596 fn load_key_pairs_to_node_config() {
1597 let authority_key_pair: AuthorityKeyPair =
1598 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1599 let protocol_key_pair: NetworkKeyPair =
1600 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1601 let network_key_pair: NetworkKeyPair =
1602 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1603
1604 write_authority_keypair_to_file(&authority_key_pair, PathBuf::from("authority.key"))
1605 .unwrap();
1606 write_keypair_to_file(
1607 &protocol_key_pair.copy().into(),
1608 PathBuf::from("protocol.key"),
1609 )
1610 .unwrap();
1611 write_keypair_to_file(
1612 &network_key_pair.copy().into(),
1613 PathBuf::from("network.key"),
1614 )
1615 .unwrap();
1616
1617 const TEMPLATE: &str = include_str!("../data/fullnode-template-with-path.yaml");
1618 let template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1619 assert_eq!(
1620 template.authority_key_pair().public(),
1621 authority_key_pair.public()
1622 );
1623 assert_eq!(
1624 template.network_key_pair().public(),
1625 network_key_pair.public()
1626 );
1627 assert_eq!(
1628 template.protocol_key_pair().public(),
1629 protocol_key_pair.public()
1630 );
1631 }
1632}
1633
1634#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
1638pub enum RunWithRange {
1639 Epoch(EpochId),
1640 Checkpoint(CheckpointSequenceNumber),
1641}
1642
1643impl RunWithRange {
1644 pub fn is_epoch_gt(&self, epoch_id: EpochId) -> bool {
1646 matches!(self, RunWithRange::Epoch(e) if epoch_id > *e)
1647 }
1648
1649 pub fn matches_checkpoint(&self, seq_num: CheckpointSequenceNumber) -> bool {
1650 matches!(self, RunWithRange::Checkpoint(seq) if *seq == seq_num)
1651 }
1652
1653 pub fn into_checkpoint_bound(self) -> Option<CheckpointSequenceNumber> {
1654 match self {
1655 RunWithRange::Epoch(_) => None,
1656 RunWithRange::Checkpoint(seq) => Some(seq),
1657 }
1658 }
1659}
1660
1661mod bech32_formatted_keypair {
1665 use std::ops::Deref;
1666
1667 use iota_types::crypto::{EncodeDecodeBase64, IotaKeyPair};
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 = IotaKeyPair>,
1674 {
1675 use serde::ser::Error;
1676
1677 let s = kp.encode().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<IotaKeyPair>,
1687 {
1688 use serde::de::Error;
1689
1690 let s = String::deserialize(deserializer)?;
1691
1692 IotaKeyPair::decode(&s)
1694 .or_else(|_| {
1695 IotaKeyPair::decode_base64(&s)
1697 })
1698 .map(Into::into)
1699 .map_err(Error::custom)
1700 }
1701}