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
49#[derive(Clone, Debug, Deserialize, Serialize)]
50#[serde(rename_all = "kebab-case")]
51pub struct NodeConfig {
52 #[serde(default = "default_authority_key_pair")]
55 pub authority_key_pair: AuthorityKeyPairWithPath,
56 #[serde(default = "default_key_pair")]
59 pub protocol_key_pair: KeyPairWithPath,
60 #[serde(default = "default_key_pair")]
61 pub account_key_pair: KeyPairWithPath,
62 #[serde(default = "default_key_pair")]
65 pub network_key_pair: KeyPairWithPath,
66 pub db_path: PathBuf,
67
68 #[serde(default = "default_grpc_address")]
72 pub network_address: Multiaddr,
73 #[serde(default = "default_json_rpc_address")]
74 pub json_rpc_address: SocketAddr,
75
76 #[serde(default = "default_metrics_address")]
78 pub metrics_address: SocketAddr,
79
80 #[serde(default = "default_admin_interface_address")]
84 pub admin_interface_address: SocketAddr,
85
86 #[serde(skip_serializing_if = "Option::is_none")]
88 pub consensus_config: Option<ConsensusConfig>,
89
90 #[serde(default = "default_enable_index_processing")]
95 pub enable_index_processing: bool,
96
97 #[serde(default)]
99 pub jsonrpc_server_type: Option<ServerType>,
104
105 #[serde(default)]
109 pub grpc_load_shed: Option<bool>,
110
111 #[serde(default = "default_concurrency_limit")]
112 pub grpc_concurrency_limit: Option<usize>,
113
114 #[serde(default)]
116 pub p2p_config: P2pConfig,
117
118 pub genesis: Genesis,
122
123 pub migration_tx_data_path: Option<PathBuf>,
125
126 #[serde(default = "default_authority_store_pruning_config")]
129 pub authority_store_pruning_config: AuthorityStorePruningConfig,
130
131 #[serde(default = "default_end_of_epoch_broadcast_channel_capacity")]
136 pub end_of_epoch_broadcast_channel_capacity: usize,
137
138 #[serde(default)]
142 pub checkpoint_executor_config: CheckpointExecutorConfig,
143
144 #[serde(skip_serializing_if = "Option::is_none")]
145 pub metrics: Option<MetricsConfig>,
146
147 #[serde(skip)]
152 pub supported_protocol_versions: Option<SupportedProtocolVersions>,
153
154 #[serde(default)]
158 pub db_checkpoint_config: DBCheckpointConfig,
159
160 #[serde(default)]
162 pub expensive_safety_check_config: ExpensiveSafetyCheckConfig,
163
164 #[serde(default)]
168 pub transaction_deny_config: TransactionDenyConfig,
169
170 #[serde(default)]
176 pub certificate_deny_config: CertificateDenyConfig,
177
178 #[serde(default)]
181 pub state_debug_dump_config: StateDebugDumpConfig,
182
183 #[serde(default)]
187 pub state_archive_write_config: StateArchiveConfig,
188
189 #[serde(default)]
190 pub state_archive_read_config: Vec<StateArchiveConfig>,
191
192 #[serde(default)]
194 pub state_snapshot_write_config: StateSnapshotConfig,
195
196 #[serde(default)]
197 pub indexer_max_subscriptions: Option<usize>,
198
199 #[serde(default = "default_transaction_kv_store_config")]
200 pub transaction_kv_store_read_config: TransactionKeyValueStoreReadConfig,
201
202 #[serde(skip_serializing_if = "Option::is_none")]
204 pub transaction_kv_store_write_config: Option<TransactionKeyValueStoreWriteConfig>,
205
206 #[serde(default = "default_authority_overload_config")]
209 pub authority_overload_config: AuthorityOverloadConfig,
210
211 #[serde(skip_serializing_if = "Option::is_none")]
215 pub run_with_range: Option<RunWithRange>,
216
217 #[serde(
219 skip_serializing_if = "Option::is_none",
220 default = "default_traffic_controller_policy_config"
221 )]
222 pub policy_config: Option<PolicyConfig>,
223
224 #[serde(skip_serializing_if = "Option::is_none")]
225 pub firewall_config: Option<RemoteFirewallConfig>,
226
227 #[serde(default)]
228 pub execution_cache_config: ExecutionCacheConfig,
229
230 #[serde(default = "bool_true")]
231 pub enable_validator_tx_finalizer: bool,
232
233 #[serde(default = "bool_true")]
239 pub enable_soft_locking: bool,
240
241 #[serde(default)]
242 pub verifier_signing_config: VerifierSigningConfig,
243
244 #[serde(skip_serializing_if = "Option::is_none")]
248 pub enable_db_write_stall: Option<bool>,
249
250 #[serde(default, skip_serializing_if = "Option::is_none")]
251 pub iota_names_config: Option<IotaNamesConfig>,
252
253 #[serde(default)]
255 pub enable_grpc_api: bool,
256 #[serde(
257 default = "default_grpc_api_config",
258 skip_serializing_if = "Option::is_none"
259 )]
260 pub grpc_api_config: Option<GrpcApiConfig>,
261
262 #[serde(skip_serializing_if = "Option::is_none")]
267 pub chain_override_for_testing: Option<Chain>,
268
269 #[serde(default, skip_serializing_if = "Option::is_none")]
272 pub validator_client_monitor_config:
273 Option<crate::validator_client_monitor_config::ValidatorClientMonitorConfig>,
274}
275
276#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
277#[serde(rename_all = "kebab-case")]
278pub struct TlsConfig {
279 cert: String,
281 key: String,
283}
284
285impl TlsConfig {
286 pub fn cert(&self) -> &str {
287 &self.cert
288 }
289
290 pub fn key(&self) -> &str {
291 &self.key
292 }
293}
294
295#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
297#[serde(rename_all = "kebab-case")]
298pub struct GrpcApiConfig {
299 #[serde(default = "default_grpc_api_address")]
301 pub address: SocketAddr,
302
303 #[serde(skip_serializing_if = "Option::is_none")]
307 pub tls: Option<TlsConfig>,
308
309 #[serde(default = "default_grpc_api_max_message_size_bytes")]
311 pub max_message_size_bytes: u32,
312
313 #[serde(default = "default_grpc_api_broadcast_buffer_size")]
315 pub broadcast_buffer_size: u32,
316
317 #[serde(default = "default_grpc_api_max_concurrent_stream_subscribers")]
323 pub max_concurrent_stream_subscribers: u32,
324
325 #[serde(default = "default_grpc_api_max_json_move_value_size")]
328 pub max_json_move_value_size: usize,
329
330 #[serde(default = "default_grpc_api_max_execute_transaction_batch_size")]
333 pub max_execute_transaction_batch_size: u32,
334
335 #[serde(default = "default_grpc_api_max_simulate_transaction_batch_size")]
338 pub max_simulate_transaction_batch_size: u32,
339
340 #[serde(default = "default_grpc_api_max_checkpoint_inclusion_timeout_ms")]
344 pub max_checkpoint_inclusion_timeout_ms: u64,
345}
346
347fn default_grpc_api_address() -> SocketAddr {
348 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 50051)
349}
350
351fn default_grpc_api_broadcast_buffer_size() -> u32 {
352 100
353}
354
355fn default_grpc_api_max_concurrent_stream_subscribers() -> u32 {
356 1024
357}
358
359fn default_grpc_api_max_message_size_bytes() -> u32 {
360 128 * 1024 * 1024 }
362
363fn default_grpc_api_max_json_move_value_size() -> usize {
364 1024 * 1024 }
366
367fn default_grpc_api_max_execute_transaction_batch_size() -> u32 {
368 20
369}
370
371fn default_grpc_api_max_simulate_transaction_batch_size() -> u32 {
372 20
373}
374
375fn default_grpc_api_max_checkpoint_inclusion_timeout_ms() -> u64 {
376 60_000 }
378
379impl Default for GrpcApiConfig {
380 fn default() -> Self {
381 Self {
382 address: default_grpc_api_address(),
383 tls: None,
384 max_message_size_bytes: default_grpc_api_max_message_size_bytes(),
385 broadcast_buffer_size: default_grpc_api_broadcast_buffer_size(),
386 max_concurrent_stream_subscribers: default_grpc_api_max_concurrent_stream_subscribers(),
387 max_json_move_value_size: default_grpc_api_max_json_move_value_size(),
388 max_execute_transaction_batch_size: default_grpc_api_max_execute_transaction_batch_size(
389 ),
390 max_simulate_transaction_batch_size:
391 default_grpc_api_max_simulate_transaction_batch_size(),
392 max_checkpoint_inclusion_timeout_ms:
393 default_grpc_api_max_checkpoint_inclusion_timeout_ms(),
394 }
395 }
396}
397
398impl GrpcApiConfig {
399 const GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE: u32 = 4 * 1024 * 1024; const GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES: u32 =
403 Self::GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE;
404
405 pub fn tls_config(&self) -> Option<&TlsConfig> {
406 self.tls.as_ref()
407 }
408
409 pub fn max_message_size_bytes(&self) -> u32 {
410 self.max_message_size_bytes
412 .max(Self::GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES)
413 }
414
415 pub fn max_message_size_client_bytes(&self, client_max_message_size_bytes: Option<u32>) -> u32 {
419 client_max_message_size_bytes
420 .unwrap_or(Self::GRPC_TONIC_DEFAULT_MAX_RECV_MESSAGE_SIZE)
423 .clamp(
425 Self::GRPC_MIN_CLIENT_MAX_MESSAGE_SIZE_BYTES,
426 self.max_message_size_bytes(),
427 )
428 }
429}
430
431#[derive(Clone, Debug, Default, Deserialize, Serialize)]
432#[serde(rename_all = "kebab-case")]
433pub struct ExecutionCacheConfig {
434 #[serde(default)]
435 pub writeback_cache: WritebackCacheConfig,
436}
437
438#[derive(Clone, Debug, Default, Deserialize, Serialize)]
439#[serde(rename_all = "kebab-case")]
440pub struct WritebackCacheConfig {
441 #[serde(default, skip_serializing_if = "Option::is_none")]
444 pub max_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
447 pub package_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
450 pub object_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
452 pub marker_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
454 pub object_by_id_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
457 pub transaction_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
459 pub executed_effect_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
461 pub effect_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
464 pub events_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
467 pub transaction_objects_cache_size: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
472 pub backpressure_threshold: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
478 pub backpressure_threshold_for_rpc: Option<u64>, #[serde(default, skip_serializing_if = "Option::is_none")]
488 pub backpressure_soft_limit_pct: Option<u32>,
489}
490
491impl WritebackCacheConfig {
492 pub fn max_cache_size(&self) -> u64 {
493 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_MAX")
494 .ok()
495 .and_then(|s| s.parse().ok())
496 .or(self.max_cache_size)
497 .unwrap_or(100000)
498 }
499
500 pub fn package_cache_size(&self) -> u64 {
501 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_PACKAGE")
502 .ok()
503 .and_then(|s| s.parse().ok())
504 .or(self.package_cache_size)
505 .unwrap_or(1000)
506 }
507
508 pub fn object_cache_size(&self) -> u64 {
509 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_OBJECT")
510 .ok()
511 .and_then(|s| s.parse().ok())
512 .or(self.object_cache_size)
513 .unwrap_or_else(|| self.max_cache_size())
514 }
515
516 pub fn marker_cache_size(&self) -> u64 {
517 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_MARKER")
518 .ok()
519 .and_then(|s| s.parse().ok())
520 .or(self.marker_cache_size)
521 .unwrap_or_else(|| self.object_cache_size())
522 }
523
524 pub fn object_by_id_cache_size(&self) -> u64 {
525 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_OBJECT_BY_ID")
526 .ok()
527 .and_then(|s| s.parse().ok())
528 .or(self.object_by_id_cache_size)
529 .unwrap_or_else(|| self.object_cache_size())
530 }
531
532 pub fn transaction_cache_size(&self) -> u64 {
533 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_TRANSACTION")
534 .ok()
535 .and_then(|s| s.parse().ok())
536 .or(self.transaction_cache_size)
537 .unwrap_or_else(|| self.max_cache_size())
538 }
539
540 pub fn executed_effect_cache_size(&self) -> u64 {
541 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EXECUTED_EFFECT")
542 .ok()
543 .and_then(|s| s.parse().ok())
544 .or(self.executed_effect_cache_size)
545 .unwrap_or_else(|| self.transaction_cache_size())
546 }
547
548 pub fn effect_cache_size(&self) -> u64 {
549 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EFFECT")
550 .ok()
551 .and_then(|s| s.parse().ok())
552 .or(self.effect_cache_size)
553 .unwrap_or_else(|| self.executed_effect_cache_size())
554 }
555
556 pub fn events_cache_size(&self) -> u64 {
557 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_EVENTS")
558 .ok()
559 .and_then(|s| s.parse().ok())
560 .or(self.events_cache_size)
561 .unwrap_or_else(|| self.transaction_cache_size())
562 }
563
564 pub fn transaction_objects_cache_size(&self) -> u64 {
565 std::env::var("IOTA_CACHE_WRITEBACK_SIZE_TRANSACTION_OBJECTS")
566 .ok()
567 .and_then(|s| s.parse().ok())
568 .or(self.transaction_objects_cache_size)
569 .unwrap_or(1000)
570 }
571
572 pub fn backpressure_threshold(&self) -> u64 {
573 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_THRESHOLD")
574 .ok()
575 .and_then(|s| s.parse().ok())
576 .or(self.backpressure_threshold)
577 .unwrap_or(100_000)
578 }
579
580 pub fn backpressure_threshold_for_rpc(&self) -> u64 {
581 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_THRESHOLD_FOR_RPC")
582 .ok()
583 .and_then(|s| s.parse().ok())
584 .or(self.backpressure_threshold_for_rpc)
585 .unwrap_or(self.backpressure_threshold())
586 }
587
588 pub fn backpressure_soft_limit_pct(&self) -> u32 {
589 std::env::var("IOTA_CACHE_WRITEBACK_BACKPRESSURE_SOFT_LIMIT_PCT")
590 .ok()
591 .and_then(|s| s.parse().ok())
592 .or(self.backpressure_soft_limit_pct)
593 .unwrap_or(50)
594 .min(100)
595 }
596}
597
598#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
599#[serde(rename_all = "lowercase")]
600pub enum ServerType {
601 WebSocket,
602 Http,
603 Both,
604}
605
606#[derive(Clone, Debug, Deserialize, Serialize)]
607#[serde(rename_all = "kebab-case")]
608pub struct TransactionKeyValueStoreReadConfig {
609 #[serde(default = "default_base_url")]
610 pub base_url: String,
611
612 #[serde(default = "default_cache_size")]
613 pub cache_size: u64,
614}
615
616impl Default for TransactionKeyValueStoreReadConfig {
617 fn default() -> Self {
618 Self {
619 base_url: default_base_url(),
620 cache_size: default_cache_size(),
621 }
622 }
623}
624
625fn default_base_url() -> String {
626 "".to_string()
627}
628
629fn default_cache_size() -> u64 {
630 100_000
631}
632
633fn default_transaction_kv_store_config() -> TransactionKeyValueStoreReadConfig {
634 TransactionKeyValueStoreReadConfig::default()
635}
636
637fn default_authority_store_pruning_config() -> AuthorityStorePruningConfig {
638 AuthorityStorePruningConfig::default()
639}
640
641pub fn default_enable_index_processing() -> bool {
642 true
643}
644
645fn default_grpc_address() -> Multiaddr {
646 "/ip4/0.0.0.0/tcp/8080".parse().unwrap()
647}
648fn default_authority_key_pair() -> AuthorityKeyPairWithPath {
649 AuthorityKeyPairWithPath::new(get_key_pair_from_rng::<AuthorityKeyPair, _>(&mut OsRng).1)
650}
651
652fn default_key_pair() -> KeyPairWithPath {
653 KeyPairWithPath::new(
654 get_key_pair_from_rng::<AccountKeyPair, _>(&mut OsRng)
655 .1
656 .into(),
657 )
658}
659
660fn default_metrics_address() -> SocketAddr {
661 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9184)
662}
663
664pub fn default_admin_interface_address() -> SocketAddr {
665 SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 1337)
666}
667
668pub fn default_json_rpc_address() -> SocketAddr {
669 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9000)
670}
671
672pub fn default_grpc_api_config() -> Option<GrpcApiConfig> {
673 Some(GrpcApiConfig::default())
674}
675
676pub fn default_concurrency_limit() -> Option<usize> {
677 Some(DEFAULT_GRPC_CONCURRENCY_LIMIT)
678}
679
680pub fn default_end_of_epoch_broadcast_channel_capacity() -> usize {
681 128
682}
683
684pub fn bool_true() -> bool {
685 true
686}
687
688impl Config for NodeConfig {}
689
690impl NodeConfig {
691 pub fn authority_key_pair(&self) -> &AuthorityKeyPair {
692 self.authority_key_pair.authority_keypair()
693 }
694
695 pub fn protocol_key_pair(&self) -> &NetworkKeyPair {
696 match self.protocol_key_pair.keypair() {
697 IotaKeyPair::Ed25519(kp) => kp,
698 other => {
699 panic!("invalid keypair type: {other:?}, only Ed25519 is allowed for protocol key")
700 }
701 }
702 }
703
704 pub fn network_key_pair(&self) -> &NetworkKeyPair {
705 match self.network_key_pair.keypair() {
706 IotaKeyPair::Ed25519(kp) => kp,
707 other => {
708 panic!("invalid keypair type: {other:?}, only Ed25519 is allowed for network key")
709 }
710 }
711 }
712
713 pub fn authority_public_key(&self) -> AuthorityPublicKeyBytes {
714 self.authority_key_pair().public().into()
715 }
716
717 pub fn db_path(&self) -> PathBuf {
718 self.db_path.join("live")
719 }
720
721 pub fn db_checkpoint_path(&self) -> PathBuf {
722 self.db_path.join("db_checkpoints")
723 }
724
725 pub fn archive_path(&self) -> PathBuf {
726 self.db_path.join("archive")
727 }
728
729 pub fn snapshot_path(&self) -> PathBuf {
730 self.db_path.join("snapshot")
731 }
732
733 pub fn network_address(&self) -> &Multiaddr {
734 &self.network_address
735 }
736
737 pub fn consensus_config(&self) -> Option<&ConsensusConfig> {
738 self.consensus_config.as_ref()
739 }
740
741 pub fn genesis(&self) -> Result<&genesis::Genesis> {
742 self.genesis.genesis()
743 }
744
745 pub fn load_migration_tx_data(&self) -> Result<MigrationTxData> {
746 let Some(location) = &self.migration_tx_data_path else {
747 anyhow::bail!("no file location set");
748 };
749
750 let migration_tx_data = MigrationTxData::load(location)?;
752
753 migration_tx_data.validate_from_genesis(self.genesis.genesis()?)?;
755 Ok(migration_tx_data)
756 }
757
758 pub fn iota_address(&self) -> Address {
759 (&self.account_key_pair.keypair().public()).into()
760 }
761
762 pub fn archive_reader_config(&self) -> Vec<ArchiveReaderConfig> {
763 self.state_archive_read_config
764 .iter()
765 .flat_map(|config| {
766 config
767 .object_store_config
768 .as_ref()
769 .map(|remote_store_config| ArchiveReaderConfig {
770 remote_store_config: remote_store_config.clone(),
771 download_concurrency: NonZeroUsize::new(config.concurrency)
772 .unwrap_or(NonZeroUsize::new(5).unwrap()),
773 use_for_pruning_watermark: config.use_for_pruning_watermark,
774 })
775 })
776 .collect()
777 }
778
779 pub fn jsonrpc_server_type(&self) -> ServerType {
780 self.jsonrpc_server_type.unwrap_or(ServerType::Http)
781 }
782}
783
784#[derive(Debug, Clone, Deserialize, Serialize)]
785#[serde(rename_all = "kebab-case")]
786pub struct ConsensusConfig {
787 pub db_path: PathBuf,
789
790 pub db_retention_epochs: Option<u64>,
794
795 pub db_pruner_period_secs: Option<u64>,
799
800 pub max_pending_transactions: Option<usize>,
811
812 pub max_submit_position: Option<usize>,
818
819 pub submit_delay_step_override_millis: Option<u64>,
825
826 #[serde(skip_serializing_if = "Option::is_none", alias = "starfish_parameters")]
828 pub parameters: Option<StarfishParameters>,
829
830 #[serde(skip_serializing_if = "Option::is_none")]
836 pub graduated_load_shedding_soft_limit_pct: Option<u32>,
837}
838
839impl ConsensusConfig {
840 pub fn db_path(&self) -> &Path {
841 &self.db_path
842 }
843
844 pub fn max_pending_transactions(&self) -> usize {
848 self.max_pending_transactions.unwrap_or(20_000)
849 }
850
851 pub fn graduated_load_shedding_soft_limit_pct(&self) -> u32 {
856 self.graduated_load_shedding_soft_limit_pct
857 .unwrap_or(50)
858 .min(100)
859 }
860
861 pub fn submit_delay_step_override(&self) -> Option<Duration> {
862 self.submit_delay_step_override_millis
863 .map(Duration::from_millis)
864 }
865
866 pub fn db_retention_epochs(&self) -> u64 {
867 self.db_retention_epochs.unwrap_or(0)
868 }
869
870 pub fn db_pruner_period(&self) -> Duration {
871 self.db_pruner_period_secs
873 .map(Duration::from_secs)
874 .unwrap_or(Duration::from_secs(3_600))
875 }
876}
877
878#[derive(Clone, Debug, Deserialize, Serialize)]
879#[serde(rename_all = "kebab-case")]
880pub struct CheckpointExecutorConfig {
881 #[serde(default = "default_checkpoint_execution_max_concurrency")]
886 pub checkpoint_execution_max_concurrency: usize,
887
888 #[serde(default = "default_local_execution_timeout_sec")]
894 pub local_execution_timeout_sec: u64,
895
896 #[serde(default, skip_serializing_if = "Option::is_none")]
901 pub data_ingestion_dir: Option<PathBuf>,
902}
903
904#[derive(Clone, Debug, Default, Deserialize, Serialize)]
905#[serde(rename_all = "kebab-case")]
906pub struct ExpensiveSafetyCheckConfig {
907 #[serde(default)]
912 enable_epoch_iota_conservation_check: bool,
913
914 #[serde(default)]
918 enable_deep_per_tx_iota_conservation_check: bool,
919
920 #[serde(default)]
923 force_disable_epoch_iota_conservation_check: bool,
924
925 #[serde(default)]
928 enable_state_consistency_check: bool,
929
930 #[serde(default)]
932 force_disable_state_consistency_check: bool,
933
934 #[serde(default)]
935 enable_secondary_index_checks: bool,
936 }
938
939impl ExpensiveSafetyCheckConfig {
940 pub fn new_enable_all() -> Self {
941 Self {
942 enable_epoch_iota_conservation_check: true,
943 enable_deep_per_tx_iota_conservation_check: true,
944 force_disable_epoch_iota_conservation_check: false,
945 enable_state_consistency_check: true,
946 force_disable_state_consistency_check: false,
947 enable_secondary_index_checks: false, }
949 }
950
951 pub fn new_disable_all() -> Self {
952 Self {
953 enable_epoch_iota_conservation_check: false,
954 enable_deep_per_tx_iota_conservation_check: false,
955 force_disable_epoch_iota_conservation_check: true,
956 enable_state_consistency_check: false,
957 force_disable_state_consistency_check: true,
958 enable_secondary_index_checks: false,
959 }
960 }
961
962 pub fn force_disable_epoch_iota_conservation_check(&mut self) {
963 self.force_disable_epoch_iota_conservation_check = true;
964 }
965
966 pub fn enable_epoch_iota_conservation_check(&self) -> bool {
967 (self.enable_epoch_iota_conservation_check || cfg!(debug_assertions))
968 && !self.force_disable_epoch_iota_conservation_check
969 }
970
971 pub fn force_disable_state_consistency_check(&mut self) {
972 self.force_disable_state_consistency_check = true;
973 }
974
975 pub fn enable_state_consistency_check(&self) -> bool {
976 (self.enable_state_consistency_check || cfg!(debug_assertions))
977 && !self.force_disable_state_consistency_check
978 }
979
980 pub fn enable_deep_per_tx_iota_conservation_check(&self) -> bool {
981 self.enable_deep_per_tx_iota_conservation_check || cfg!(debug_assertions)
982 }
983
984 pub fn enable_secondary_index_checks(&self) -> bool {
985 self.enable_secondary_index_checks
986 }
987}
988
989fn default_checkpoint_execution_max_concurrency() -> usize {
990 4
991}
992
993fn default_local_execution_timeout_sec() -> u64 {
994 30
995}
996
997impl Default for CheckpointExecutorConfig {
998 fn default() -> Self {
999 Self {
1000 checkpoint_execution_max_concurrency: default_checkpoint_execution_max_concurrency(),
1001 local_execution_timeout_sec: default_local_execution_timeout_sec(),
1002 data_ingestion_dir: None,
1003 }
1004 }
1005}
1006
1007#[derive(Debug, Clone, Deserialize, Serialize)]
1008#[serde(rename_all = "kebab-case")]
1009pub struct AuthorityStorePruningConfig {
1010 #[serde(default = "default_num_latest_epoch_dbs_to_retain")]
1012 pub num_latest_epoch_dbs_to_retain: usize,
1013 #[serde(default)]
1018 pub num_epochs_to_retain: u64,
1019 #[serde(skip_serializing_if = "Option::is_none")]
1021 pub pruning_run_delay_seconds: Option<u64>,
1022 #[serde(default = "default_max_checkpoints_in_batch")]
1025 pub max_checkpoints_in_batch: usize,
1026 #[serde(default = "default_max_transactions_in_batch")]
1028 pub max_transactions_in_batch: usize,
1029 #[serde(
1034 default = "default_periodic_compaction_threshold_days",
1035 skip_serializing_if = "Option::is_none"
1036 )]
1037 pub periodic_compaction_threshold_days: Option<usize>,
1038 #[serde(skip_serializing_if = "Option::is_none")]
1041 pub num_epochs_to_retain_for_checkpoints: Option<u64>,
1042 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1048 pub enable_compaction_filter: bool,
1049 #[serde(skip_serializing_if = "Option::is_none")]
1050 pub num_epochs_to_retain_for_indexes: Option<u64>,
1051}
1052
1053fn default_num_latest_epoch_dbs_to_retain() -> usize {
1054 3
1055}
1056
1057fn default_max_transactions_in_batch() -> usize {
1058 1000
1059}
1060
1061fn default_max_checkpoints_in_batch() -> usize {
1062 10
1063}
1064
1065fn default_periodic_compaction_threshold_days() -> Option<usize> {
1066 Some(1)
1067}
1068
1069impl Default for AuthorityStorePruningConfig {
1070 fn default() -> Self {
1071 Self {
1072 num_latest_epoch_dbs_to_retain: default_num_latest_epoch_dbs_to_retain(),
1073 num_epochs_to_retain: 0,
1074 pruning_run_delay_seconds: if cfg!(msim) { Some(2) } else { None },
1075 max_checkpoints_in_batch: default_max_checkpoints_in_batch(),
1076 max_transactions_in_batch: default_max_transactions_in_batch(),
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}
1116
1117#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1118#[serde(rename_all = "kebab-case")]
1119pub struct DBCheckpointConfig {
1120 #[serde(default)]
1121 pub perform_db_checkpoints_at_epoch_end: bool,
1122 #[serde(skip_serializing_if = "Option::is_none")]
1123 pub checkpoint_path: Option<PathBuf>,
1124 #[serde(skip_serializing_if = "Option::is_none")]
1125 pub object_store_config: Option<ObjectStoreConfig>,
1126 #[serde(skip_serializing_if = "Option::is_none")]
1127 pub perform_index_db_checkpoints_at_epoch_end: Option<bool>,
1128 #[serde(skip_serializing_if = "Option::is_none")]
1129 pub prune_and_compact_before_upload: Option<bool>,
1130}
1131
1132#[derive(Debug, Clone)]
1133pub struct ArchiveReaderConfig {
1134 pub remote_store_config: ObjectStoreConfig,
1135 pub download_concurrency: NonZeroUsize,
1136 pub use_for_pruning_watermark: bool,
1137}
1138
1139#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1140#[serde(rename_all = "kebab-case")]
1141pub struct StateArchiveConfig {
1142 #[serde(skip_serializing_if = "Option::is_none")]
1143 pub object_store_config: Option<ObjectStoreConfig>,
1144 pub concurrency: usize,
1145 pub use_for_pruning_watermark: bool,
1146}
1147
1148#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1156#[serde(rename_all = "kebab-case")]
1157pub struct StateSnapshotConfig {
1158 #[serde(skip_serializing_if = "Option::is_none")]
1159 pub object_store_config: Option<ObjectStoreConfig>,
1160 pub concurrency: usize,
1161}
1162
1163#[derive(Default, Debug, Clone, Deserialize, Serialize)]
1164#[serde(rename_all = "kebab-case")]
1165pub struct TransactionKeyValueStoreWriteConfig {
1166 pub aws_access_key_id: String,
1167 pub aws_secret_access_key: String,
1168 pub aws_region: String,
1169 pub table_name: String,
1170 pub bucket_name: String,
1171 pub concurrency: usize,
1172}
1173
1174#[derive(Clone, Debug, Deserialize, Serialize)]
1179#[serde(rename_all = "kebab-case")]
1180pub struct AuthorityOverloadConfig {
1181 #[serde(default = "default_max_txn_age_in_queue")]
1185 pub max_txn_age_in_queue: Duration,
1186
1187 #[serde(default = "default_overload_monitor_interval")]
1189 pub overload_monitor_interval: Duration,
1190
1191 #[serde(default = "default_execution_queue_latency_soft_limit")]
1193 pub execution_queue_latency_soft_limit: Duration,
1194
1195 #[serde(default = "default_execution_queue_latency_hard_limit")]
1198 pub execution_queue_latency_hard_limit: Duration,
1199
1200 #[serde(default = "default_max_load_shedding_percentage")]
1202 pub max_load_shedding_percentage: u32,
1203
1204 #[serde(default = "default_min_load_shedding_percentage_above_hard_limit")]
1207 pub min_load_shedding_percentage_above_hard_limit: u32,
1208
1209 #[serde(default = "default_safe_transaction_ready_rate")]
1212 pub safe_transaction_ready_rate: u32,
1213
1214 #[serde(default = "default_check_system_overload_at_signing")]
1217 pub check_system_overload_at_signing: bool,
1218
1219 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1222 pub check_system_overload_at_execution: bool,
1223
1224 #[serde(default = "default_max_transaction_manager_queue_length")]
1228 pub max_transaction_manager_queue_length: usize,
1229
1230 #[serde(default = "default_max_transaction_manager_per_object_queue_length")]
1233 pub max_transaction_manager_per_object_queue_length: usize,
1234
1235 #[serde(default = "default_max_transaction_manager_queue_length_soft_limit_pct")]
1239 pub max_transaction_manager_queue_length_soft_limit_pct: u32,
1240}
1241
1242impl AuthorityOverloadConfig {
1243 pub fn max_transaction_manager_queue_length_soft_limit_pct(&self) -> u32 {
1246 self.max_transaction_manager_queue_length_soft_limit_pct
1247 .min(100)
1248 }
1249}
1250
1251fn default_max_txn_age_in_queue() -> Duration {
1252 Duration::from_millis(500)
1253}
1254
1255fn default_overload_monitor_interval() -> Duration {
1256 Duration::from_secs(10)
1257}
1258
1259fn default_execution_queue_latency_soft_limit() -> Duration {
1260 Duration::from_secs(1)
1261}
1262
1263fn default_execution_queue_latency_hard_limit() -> Duration {
1264 Duration::from_secs(10)
1265}
1266
1267fn default_max_load_shedding_percentage() -> u32 {
1268 95
1269}
1270
1271fn default_min_load_shedding_percentage_above_hard_limit() -> u32 {
1272 50
1273}
1274
1275fn default_safe_transaction_ready_rate() -> u32 {
1276 100
1277}
1278
1279fn default_check_system_overload_at_signing() -> bool {
1280 true
1281}
1282
1283fn default_max_transaction_manager_queue_length() -> usize {
1284 100_000
1285}
1286
1287fn default_max_transaction_manager_queue_length_soft_limit_pct() -> u32 {
1288 50
1289}
1290
1291fn default_max_transaction_manager_per_object_queue_length() -> usize {
1292 20
1293}
1294
1295impl Default for AuthorityOverloadConfig {
1296 fn default() -> Self {
1297 Self {
1298 max_txn_age_in_queue: default_max_txn_age_in_queue(),
1299 overload_monitor_interval: default_overload_monitor_interval(),
1300 execution_queue_latency_soft_limit: default_execution_queue_latency_soft_limit(),
1301 execution_queue_latency_hard_limit: default_execution_queue_latency_hard_limit(),
1302 max_load_shedding_percentage: default_max_load_shedding_percentage(),
1303 min_load_shedding_percentage_above_hard_limit:
1304 default_min_load_shedding_percentage_above_hard_limit(),
1305 safe_transaction_ready_rate: default_safe_transaction_ready_rate(),
1306 check_system_overload_at_signing: true,
1307 check_system_overload_at_execution: false,
1308 max_transaction_manager_queue_length: default_max_transaction_manager_queue_length(),
1309 max_transaction_manager_queue_length_soft_limit_pct:
1310 default_max_transaction_manager_queue_length_soft_limit_pct(),
1311 max_transaction_manager_per_object_queue_length:
1312 default_max_transaction_manager_per_object_queue_length(),
1313 }
1314 }
1315}
1316
1317fn default_authority_overload_config() -> AuthorityOverloadConfig {
1318 AuthorityOverloadConfig::default()
1319}
1320
1321fn default_traffic_controller_policy_config() -> Option<PolicyConfig> {
1322 Some(PolicyConfig::default_dos_protection_policy())
1323}
1324
1325#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1326pub struct Genesis {
1327 #[serde(flatten)]
1328 location: Option<GenesisLocation>,
1329
1330 #[serde(skip)]
1331 genesis: once_cell::sync::OnceCell<genesis::Genesis>,
1332}
1333
1334impl Genesis {
1335 pub fn new(genesis: genesis::Genesis) -> Self {
1336 Self {
1337 location: Some(GenesisLocation::InPlace {
1338 genesis: Box::new(genesis),
1339 }),
1340 genesis: Default::default(),
1341 }
1342 }
1343
1344 pub fn new_from_file<P: Into<PathBuf>>(path: P) -> Self {
1345 Self {
1346 location: Some(GenesisLocation::File {
1347 genesis_file_location: path.into(),
1348 }),
1349 genesis: Default::default(),
1350 }
1351 }
1352
1353 pub fn new_empty() -> Self {
1354 Self {
1355 location: None,
1356 genesis: Default::default(),
1357 }
1358 }
1359
1360 pub fn genesis(&self) -> Result<&genesis::Genesis> {
1361 match &self.location {
1362 Some(GenesisLocation::InPlace { genesis }) => Ok(genesis),
1363 Some(GenesisLocation::File {
1364 genesis_file_location,
1365 }) => self
1366 .genesis
1367 .get_or_try_init(|| genesis::Genesis::load(genesis_file_location)),
1368 None => anyhow::bail!("no genesis location set"),
1369 }
1370 }
1371}
1372
1373#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1374#[serde(untagged)]
1375enum GenesisLocation {
1376 InPlace {
1377 genesis: Box<genesis::Genesis>,
1378 },
1379 File {
1380 #[serde(rename = "genesis-file-location")]
1381 genesis_file_location: PathBuf,
1382 },
1383}
1384
1385#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
1388pub struct KeyPairWithPath {
1389 #[serde(flatten)]
1390 location: KeyPairLocation,
1391
1392 #[serde(skip)]
1393 keypair: OnceCell<Arc<IotaKeyPair>>,
1394}
1395
1396#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1397#[serde(untagged)]
1398enum KeyPairLocation {
1399 InPlace {
1400 #[serde(with = "bech32_formatted_keypair")]
1401 value: Arc<IotaKeyPair>,
1402 },
1403 File {
1404 path: PathBuf,
1405 },
1406}
1407
1408impl KeyPairWithPath {
1409 pub fn new(kp: IotaKeyPair) -> Self {
1410 let cell: OnceCell<Arc<IotaKeyPair>> = OnceCell::new();
1411 let arc_kp = Arc::new(kp);
1412 cell.set(arc_kp.clone()).expect("failed to set keypair");
1415 Self {
1416 location: KeyPairLocation::InPlace { value: arc_kp },
1417 keypair: cell,
1418 }
1419 }
1420
1421 pub fn new_from_path(path: PathBuf) -> Self {
1422 let cell: OnceCell<Arc<IotaKeyPair>> = OnceCell::new();
1423 cell.set(Arc::new(read_keypair_from_file(&path).unwrap_or_else(
1426 |e| panic!("invalid keypair file at path {:?}: {e}", &path),
1427 )))
1428 .expect("failed to set keypair");
1429 Self {
1430 location: KeyPairLocation::File { path },
1431 keypair: cell,
1432 }
1433 }
1434
1435 pub fn keypair(&self) -> &IotaKeyPair {
1436 self.keypair
1437 .get_or_init(|| match &self.location {
1438 KeyPairLocation::InPlace { value } => value.clone(),
1439 KeyPairLocation::File { path } => {
1440 Arc::new(
1443 read_keypair_from_file(path).unwrap_or_else(|e| {
1444 panic!("invalid keypair file at path {path:?}: {e}")
1445 }),
1446 )
1447 }
1448 })
1449 .as_ref()
1450 }
1451}
1452
1453#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
1456pub struct AuthorityKeyPairWithPath {
1457 #[serde(flatten)]
1458 location: AuthorityKeyPairLocation,
1459
1460 #[serde(skip)]
1461 keypair: OnceCell<Arc<AuthorityKeyPair>>,
1462}
1463
1464#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq)]
1465#[serde(untagged)]
1466enum AuthorityKeyPairLocation {
1467 InPlace { value: Arc<AuthorityKeyPair> },
1468 File { path: PathBuf },
1469}
1470
1471impl AuthorityKeyPairWithPath {
1472 pub fn new(kp: AuthorityKeyPair) -> Self {
1473 let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1474 let arc_kp = Arc::new(kp);
1475 cell.set(arc_kp.clone())
1478 .expect("failed to set authority keypair");
1479 Self {
1480 location: AuthorityKeyPairLocation::InPlace { value: arc_kp },
1481 keypair: cell,
1482 }
1483 }
1484
1485 pub fn new_from_path(path: PathBuf) -> Self {
1486 let cell: OnceCell<Arc<AuthorityKeyPair>> = OnceCell::new();
1487 cell.set(Arc::new(
1490 read_authority_keypair_from_file(&path)
1491 .unwrap_or_else(|_| panic!("invalid authority keypair file at path {:?}", &path)),
1492 ))
1493 .expect("failed to set authority keypair");
1494 Self {
1495 location: AuthorityKeyPairLocation::File { path },
1496 keypair: cell,
1497 }
1498 }
1499
1500 pub fn authority_keypair(&self) -> &AuthorityKeyPair {
1501 self.keypair
1502 .get_or_init(|| match &self.location {
1503 AuthorityKeyPairLocation::InPlace { value } => value.clone(),
1504 AuthorityKeyPairLocation::File { path } => {
1505 Arc::new(
1508 read_authority_keypair_from_file(path).unwrap_or_else(|_| {
1509 panic!("invalid authority keypair file {:?}", &path)
1510 }),
1511 )
1512 }
1513 })
1514 .as_ref()
1515 }
1516}
1517
1518#[derive(Clone, Debug, Deserialize, Serialize, Default)]
1521#[serde(rename_all = "kebab-case")]
1522pub struct StateDebugDumpConfig {
1523 #[serde(skip_serializing_if = "Option::is_none")]
1524 pub dump_file_directory: Option<PathBuf>,
1525}
1526
1527#[cfg(test)]
1528mod tests {
1529 use std::path::PathBuf;
1530
1531 use fastcrypto::traits::KeyPair;
1532 use iota_keys::keypair_file::{write_authority_keypair_to_file, write_keypair_to_file};
1533 use iota_types::crypto::{
1534 AuthorityKeyPair, IotaKeyPair, NetworkKeyPair, get_key_pair_from_rng,
1535 };
1536 use rand::{SeedableRng, rngs::StdRng};
1537
1538 use super::Genesis;
1539 use crate::NodeConfig;
1540
1541 #[test]
1542 fn serialize_genesis_from_file() {
1543 let g = Genesis::new_from_file("path/to/file");
1544
1545 let s = serde_yaml::to_string(&g).unwrap();
1546 assert_eq!("---\ngenesis-file-location: path/to/file\n", s);
1547 let loaded_genesis: Genesis = serde_yaml::from_str(&s).unwrap();
1548 assert_eq!(g, loaded_genesis);
1549 }
1550
1551 #[test]
1552 fn fullnode_template() {
1553 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1554
1555 let _template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1556 }
1557
1558 #[test]
1559 fn enable_soft_locking_defaults_to_enabled() {
1560 const TEMPLATE: &str = include_str!("../data/fullnode-template.yaml");
1563
1564 let config: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1565 assert!(config.enable_soft_locking);
1566 }
1567
1568 #[test]
1569 fn load_key_pairs_to_node_config() {
1570 let authority_key_pair: AuthorityKeyPair =
1571 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1572 let protocol_key_pair: NetworkKeyPair =
1573 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1574 let network_key_pair: NetworkKeyPair =
1575 get_key_pair_from_rng(&mut StdRng::from_seed([0; 32])).1;
1576
1577 write_authority_keypair_to_file(&authority_key_pair, PathBuf::from("authority.key"))
1578 .unwrap();
1579 write_keypair_to_file(
1580 &IotaKeyPair::Ed25519(protocol_key_pair.copy()),
1581 PathBuf::from("protocol.key"),
1582 )
1583 .unwrap();
1584 write_keypair_to_file(
1585 &IotaKeyPair::Ed25519(network_key_pair.copy()),
1586 PathBuf::from("network.key"),
1587 )
1588 .unwrap();
1589
1590 const TEMPLATE: &str = include_str!("../data/fullnode-template-with-path.yaml");
1591 let template: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
1592 assert_eq!(
1593 template.authority_key_pair().public(),
1594 authority_key_pair.public()
1595 );
1596 assert_eq!(
1597 template.network_key_pair().public(),
1598 network_key_pair.public()
1599 );
1600 assert_eq!(
1601 template.protocol_key_pair().public(),
1602 protocol_key_pair.public()
1603 );
1604 }
1605}
1606
1607#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
1611pub enum RunWithRange {
1612 Epoch(EpochId),
1613 Checkpoint(CheckpointSequenceNumber),
1614}
1615
1616impl RunWithRange {
1617 pub fn is_epoch_gt(&self, epoch_id: EpochId) -> bool {
1619 matches!(self, RunWithRange::Epoch(e) if epoch_id > *e)
1620 }
1621
1622 pub fn matches_checkpoint(&self, seq_num: CheckpointSequenceNumber) -> bool {
1623 matches!(self, RunWithRange::Checkpoint(seq) if *seq == seq_num)
1624 }
1625
1626 pub fn into_checkpoint_bound(self) -> Option<CheckpointSequenceNumber> {
1627 match self {
1628 RunWithRange::Epoch(_) => None,
1629 RunWithRange::Checkpoint(seq) => Some(seq),
1630 }
1631 }
1632}
1633
1634mod bech32_formatted_keypair {
1638 use std::ops::Deref;
1639
1640 use iota_types::crypto::{EncodeDecodeBase64, IotaKeyPair};
1641 use serde::{Deserialize, Deserializer, Serializer};
1642
1643 pub fn serialize<S, T>(kp: &T, serializer: S) -> Result<S::Ok, S::Error>
1644 where
1645 S: Serializer,
1646 T: Deref<Target = IotaKeyPair>,
1647 {
1648 use serde::ser::Error;
1649
1650 let s = kp.encode().map_err(Error::custom)?;
1652
1653 serializer.serialize_str(&s)
1654 }
1655
1656 pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
1657 where
1658 D: Deserializer<'de>,
1659 T: From<IotaKeyPair>,
1660 {
1661 use serde::de::Error;
1662
1663 let s = String::deserialize(deserializer)?;
1664
1665 IotaKeyPair::decode(&s)
1667 .or_else(|_| {
1668 IotaKeyPair::decode_base64(&s)
1670 })
1671 .map(Into::into)
1672 .map_err(Error::custom)
1673 }
1674}