1use std::{
6 net::{Ipv4Addr, SocketAddr},
7 num::NonZeroUsize,
8 path::PathBuf,
9};
10
11use anyhow::anyhow;
12use fastcrypto::{
13 encoding::{Encoding, Hex},
14 traits::KeyPair,
15};
16use iota_config::{
17 AUTHORITIES_DB_NAME, CONSENSUS_DB_NAME, ConsensusConfig, FULL_NODE_DB_PATH,
18 IOTA_GENESIS_MIGRATION_TX_DATA_FILENAME, NodeConfig, local_ip_utils,
19 node::{
20 AuthorityKeyPairWithPath, AuthorityOverloadConfig, AuthorityStorePruningConfig,
21 CheckpointExecutorConfig, ExecutionCacheConfig, ExpensiveSafetyCheckConfig, Genesis,
22 GrpcApiConfig, KeyPairWithPath, RunWithRange, StateSnapshotConfig,
23 default_enable_jsonrpc_api, default_end_of_epoch_broadcast_channel_capacity,
24 default_full_checkpoint_contents_cache_size_mb,
25 },
26 p2p::{DiscoveryConfig, P2pConfig, SeedPeer, StateSyncConfig},
27 transaction_deny_config::TransactionDenyConfig,
28 verifier_signing_config::VerifierSigningConfig,
29};
30use iota_multiaddr::Multiaddr;
31use iota_names::config::IotaNamesConfig;
32use iota_protocol_config::Chain;
33use iota_types::{
34 crypto::{AuthorityKeyPair, AuthorityPublicKeyBytes, NetworkPrivateKey},
35 supported_protocol_versions::SupportedProtocolVersions,
36 traffic_control::PolicyConfig,
37};
38
39use crate::{
40 genesis_config::{ValidatorGenesisConfig, ValidatorGenesisConfigBuilder},
41 network_config::NetworkConfig,
42};
43
44#[derive(Clone, Default)]
48pub struct ValidatorConfigBuilder {
49 config_directory: Option<PathBuf>,
50 supported_protocol_versions: Option<SupportedProtocolVersions>,
51 force_unpruned_checkpoints: bool,
52 authority_overload_config: Option<AuthorityOverloadConfig>,
53 transaction_deny_config: Option<TransactionDenyConfig>,
54 execution_cache_config: Option<ExecutionCacheConfig>,
55 data_ingestion_dir: Option<PathBuf>,
56 policy_config: Option<PolicyConfig>,
57 max_submit_position: Option<usize>,
58 submit_delay_step_override_millis: Option<u64>,
59 discovery_config: Option<DiscoveryConfig>,
60 chain_override: Option<Chain>,
61}
62
63impl ValidatorConfigBuilder {
64 pub fn new() -> Self {
65 Self {
66 ..Default::default()
67 }
68 }
69
70 pub fn with_chain_override(mut self, chain: Chain) -> Self {
71 assert!(self.chain_override.is_none(), "Chain override already set");
72 self.chain_override = Some(chain);
73 self
74 }
75
76 pub fn with_config_directory(mut self, config_directory: PathBuf) -> Self {
77 assert!(self.config_directory.is_none());
78 self.config_directory = Some(config_directory);
79 self
80 }
81
82 pub fn with_supported_protocol_versions(
83 mut self,
84 supported_protocol_versions: SupportedProtocolVersions,
85 ) -> Self {
86 assert!(self.supported_protocol_versions.is_none());
87 self.supported_protocol_versions = Some(supported_protocol_versions);
88 self
89 }
90
91 pub fn with_unpruned_checkpoints(mut self) -> Self {
92 self.force_unpruned_checkpoints = true;
93 self
94 }
95
96 pub fn with_authority_overload_config(mut self, config: AuthorityOverloadConfig) -> Self {
97 self.authority_overload_config = Some(config);
98 self
99 }
100
101 pub fn with_transaction_deny_config(mut self, config: TransactionDenyConfig) -> Self {
102 self.transaction_deny_config = Some(config);
103 self
104 }
105
106 pub fn with_execution_cache_config(mut self, config: ExecutionCacheConfig) -> Self {
107 self.execution_cache_config = Some(config);
108 self
109 }
110
111 pub fn with_data_ingestion_dir(mut self, path: PathBuf) -> Self {
112 self.data_ingestion_dir = Some(path);
113 self
114 }
115
116 pub fn with_policy_config(mut self, config: Option<PolicyConfig>) -> Self {
117 self.policy_config = config;
118 self
119 }
120
121 pub fn with_max_submit_position(mut self, max_submit_position: usize) -> Self {
122 self.max_submit_position = Some(max_submit_position);
123 self
124 }
125
126 pub fn with_submit_delay_step_override_millis(
127 mut self,
128 submit_delay_step_override_millis: u64,
129 ) -> Self {
130 self.submit_delay_step_override_millis = Some(submit_delay_step_override_millis);
131 self
132 }
133
134 pub fn with_discovery_config(mut self, discovery_config: DiscoveryConfig) -> Self {
135 self.discovery_config = Some(discovery_config);
136 self
137 }
138
139 pub fn build_without_genesis(self, validator: ValidatorGenesisConfig) -> NodeConfig {
140 let key_path = get_key_path(&validator.authority_key_pair);
141 let config_directory = self
142 .config_directory
143 .unwrap_or_else(|| iota_common::tempdir().keep());
144 let migration_tx_data_path =
145 Some(config_directory.join(IOTA_GENESIS_MIGRATION_TX_DATA_FILENAME));
146 let db_path = config_directory
147 .join(AUTHORITIES_DB_NAME)
148 .join(key_path.clone());
149 let network_address = validator.network_address;
150 let consensus_db_path = config_directory.join(CONSENSUS_DB_NAME).join(key_path);
151 let consensus_config = ConsensusConfig {
152 db_path: consensus_db_path,
153 db_retention_epochs: None,
154 db_pruner_period_secs: None,
155 max_pending_transactions: None,
156 max_submit_position: self.max_submit_position,
157 submit_delay_step_override_millis: self.submit_delay_step_override_millis,
158 parameters: Default::default(),
159 graduated_load_shedding_soft_limit_pct: Default::default(),
160 };
161
162 let p2p_config = P2pConfig {
163 listen_address: validator.p2p_listen_address.unwrap_or_else(|| {
164 validator
165 .p2p_address
166 .udp_multiaddr_to_listen_address()
167 .unwrap()
168 }),
169 external_address: Some(validator.p2p_address),
170 state_sync: Some(StateSyncConfig {
173 checkpoint_content_timeout_ms: Some(10_000),
174 ..Default::default()
175 }),
176 discovery: self.discovery_config,
178 ..Default::default()
179 };
180
181 let mut pruning_config = local_network_pruning_config();
182 if self.force_unpruned_checkpoints {
183 pruning_config.set_num_epochs_to_retain_for_checkpoints(Some(u64::MAX));
184 }
185 let pruning_config = pruning_config;
186 let checkpoint_executor_config = CheckpointExecutorConfig {
187 data_ingestion_dir: self.data_ingestion_dir,
188 ..Default::default()
189 };
190
191 NodeConfig {
192 authority_key_pair: AuthorityKeyPairWithPath::new(validator.authority_key_pair),
193 network_key_pair: KeyPairWithPath::new(validator.network_key_pair.into()),
194 account_key_pair: KeyPairWithPath::new(validator.account_key_pair),
195 protocol_key_pair: KeyPairWithPath::new(validator.protocol_key_pair.into()),
196 json_rpc_address: SocketAddr::new(
199 network_address
200 .to_socket_addr()
201 .map(|address| address.ip())
202 .unwrap_or_else(|_| Ipv4Addr::LOCALHOST.into()),
203 network_address.port().unwrap_or_default().saturating_add(5),
204 ),
205 db_path,
206 network_address,
207 metrics_address: validator.metrics_address,
208 admin_interface_address: validator.admin_interface_address,
209 consensus_config: Some(consensus_config),
210 enable_jsonrpc_api: default_enable_jsonrpc_api(),
211 genesis: Genesis::new_empty(),
212 migration_tx_data_path,
213 grpc_load_shed: None,
214 grpc_concurrency_limit_per_core: NonZeroUsize::new(500_000_000).unwrap(),
217 p2p_config,
218 authority_store_pruning_config: pruning_config,
219 end_of_epoch_broadcast_channel_capacity:
220 default_end_of_epoch_broadcast_channel_capacity(),
221 checkpoint_executor_config,
222 metrics: None,
223 supported_protocol_versions: self.supported_protocol_versions,
224 expensive_safety_check_config: ExpensiveSafetyCheckConfig::default(),
227 transaction_deny_config: self.transaction_deny_config.unwrap_or_default(),
228 certificate_deny_config: Default::default(),
229 state_debug_dump_config: Default::default(),
230 checkpoint_archive_config: None,
231 state_snapshot_write_config: StateSnapshotConfig::default(),
232 transaction_kv_store_read_config: Default::default(),
233 transaction_kv_store_write_config: None,
234 authority_overload_config: self.authority_overload_config.unwrap_or_default(),
235 execution_cache_config: self.execution_cache_config.unwrap_or_default(),
236 full_checkpoint_contents_cache_size_mb: default_full_checkpoint_contents_cache_size_mb(
237 ),
238 run_with_range: None,
239 policy_config: self.policy_config,
240 enable_validator_tx_finalizer: true,
241 enable_soft_locking: true,
242 verifier_signing_config: VerifierSigningConfig::default(),
243 post_consensus_validation_readers: None,
244 enable_db_write_stall: None,
245 iota_names_config: None,
246 enable_grpc_api: false,
247 grpc_api_config: None,
248 chain_override_for_testing: self.chain_override,
249 validator_client_monitor_config: None,
250 validator_grpc_listener_limits: Default::default(),
251 json_rpc_listener_limits: Default::default(),
252 grpc_api_listener_limits: Default::default(),
253 }
254 }
255
256 pub fn build(
257 self,
258 validator: ValidatorGenesisConfig,
259 genesis: iota_config::genesis::Genesis,
260 ) -> NodeConfig {
261 let mut config = self.build_without_genesis(validator);
262 config.genesis = iota_config::node::Genesis::new(genesis);
263 config
264 }
265
266 pub fn build_new_validator<R: rand::CryptoRng>(
267 self,
268 rng: &mut R,
269 network_config: &NetworkConfig,
270 ) -> NodeConfig {
271 let validator_config = ValidatorGenesisConfigBuilder::new().build(rng);
272 self.build(validator_config, network_config.genesis.clone())
273 }
274}
275
276#[derive(Clone, Debug, Default)]
277pub struct FullnodeConfigBuilder {
278 config_directory: Option<PathBuf>,
279 rpc_port: Option<u16>,
281 rpc_addr: Option<SocketAddr>,
282 supported_protocol_versions: Option<SupportedProtocolVersions>,
283 expensive_safety_check_config: Option<ExpensiveSafetyCheckConfig>,
284 db_path: Option<PathBuf>,
285 network_address: Option<Multiaddr>,
286 json_rpc_address: Option<SocketAddr>,
287 metrics_address: Option<SocketAddr>,
288 admin_interface_address: Option<SocketAddr>,
289 genesis: Option<Genesis>,
290 p2p_external_address: Option<Multiaddr>,
291 p2p_listen_address: Option<SocketAddr>,
292 network_key_pair: Option<KeyPairWithPath>,
293 run_with_range: Option<RunWithRange>,
294 policy_config: Option<PolicyConfig>,
295 data_ingestion_dir: Option<PathBuf>,
296 disable_pruning: bool,
297 num_epochs_to_retain_for_indexes: Option<u64>,
298 iota_names_config: Option<IotaNamesConfig>,
299 enable_jsonrpc_api: Option<bool>,
301 enable_grpc_api: bool,
302 grpc_api_config: Option<GrpcApiConfig>,
303 discovery_config: Option<DiscoveryConfig>,
304 chain_override: Option<Chain>,
305 state_snapshot_write_config: Option<StateSnapshotConfig>,
306}
307
308impl FullnodeConfigBuilder {
309 pub fn new() -> Self {
310 Self::default()
311 }
312
313 pub fn with_state_snapshot_config(mut self, config: StateSnapshotConfig) -> Self {
315 self.state_snapshot_write_config = Some(config);
316 self
317 }
318
319 pub fn with_chain_override(mut self, chain: Chain) -> Self {
320 assert!(self.chain_override.is_none(), "Chain override already set");
321 self.chain_override = Some(chain);
322 self
323 }
324
325 pub fn with_config_directory(mut self, config_directory: PathBuf) -> Self {
326 self.config_directory = Some(config_directory);
327 self
328 }
329
330 pub fn with_rpc_port(mut self, port: u16) -> Self {
331 assert!(self.rpc_addr.is_none() && self.rpc_port.is_none());
332 self.rpc_port = Some(port);
333 self
334 }
335
336 pub fn with_rpc_addr(mut self, addr: impl Into<SocketAddr>) -> Self {
337 assert!(self.rpc_addr.is_none() && self.rpc_port.is_none());
338 self.rpc_addr = Some(addr.into());
339 self
340 }
341
342 pub fn with_supported_protocol_versions(mut self, versions: SupportedProtocolVersions) -> Self {
343 self.supported_protocol_versions = Some(versions);
344 self
345 }
346
347 pub fn with_disable_pruning(mut self, disable_pruning: bool) -> Self {
348 self.disable_pruning = disable_pruning;
349 self
350 }
351
352 pub fn with_expensive_safety_check_config(
353 mut self,
354 expensive_safety_check_config: ExpensiveSafetyCheckConfig,
355 ) -> Self {
356 self.expensive_safety_check_config = Some(expensive_safety_check_config);
357 self
358 }
359
360 pub fn with_db_path(mut self, db_path: PathBuf) -> Self {
361 self.db_path = Some(db_path);
362 self
363 }
364
365 pub fn with_network_address(mut self, network_address: Multiaddr) -> Self {
366 self.network_address = Some(network_address);
367 self
368 }
369
370 pub fn with_json_rpc_address(mut self, json_rpc_address: impl Into<SocketAddr>) -> Self {
371 self.json_rpc_address = Some(json_rpc_address.into());
372 self
373 }
374
375 pub fn with_metrics_address(mut self, metrics_address: impl Into<SocketAddr>) -> Self {
376 self.metrics_address = Some(metrics_address.into());
377 self
378 }
379
380 pub fn with_admin_interface_address(
381 mut self,
382 admin_interface_address: Option<impl Into<SocketAddr>>,
383 ) -> Self {
384 self.admin_interface_address = admin_interface_address.map(|addr| addr.into());
385 self
386 }
387
388 pub fn with_genesis(mut self, genesis: Genesis) -> Self {
389 self.genesis = Some(genesis);
390 self
391 }
392
393 pub fn with_p2p_external_address(mut self, p2p_external_address: Multiaddr) -> Self {
394 self.p2p_external_address = Some(p2p_external_address);
395 self
396 }
397
398 pub fn with_p2p_listen_address(mut self, p2p_listen_address: impl Into<SocketAddr>) -> Self {
399 self.p2p_listen_address = Some(p2p_listen_address.into());
400 self
401 }
402
403 pub fn with_network_private_key(
404 mut self,
405 network_private_key: Option<NetworkPrivateKey>,
406 ) -> Self {
407 if let Some(network_private_key) = network_private_key {
408 self.network_key_pair = Some(KeyPairWithPath::new(network_private_key.into()));
409 }
410 self
411 }
412
413 pub fn with_num_epochs_to_retain_for_indexes(mut self, epochs: Option<u64>) -> Self {
414 self.num_epochs_to_retain_for_indexes = epochs;
415 self
416 }
417
418 pub fn with_run_with_range(mut self, run_with_range: Option<RunWithRange>) -> Self {
419 if let Some(run_with_range) = run_with_range {
420 self.run_with_range = Some(run_with_range);
421 }
422 self
423 }
424
425 pub fn with_policy_config(mut self, config: Option<PolicyConfig>) -> Self {
426 self.policy_config = config;
427 self
428 }
429
430 pub fn with_data_ingestion_dir(mut self, path: Option<PathBuf>) -> Self {
431 self.data_ingestion_dir = path;
432 self
433 }
434
435 pub fn with_iota_names_config(mut self, config: Option<IotaNamesConfig>) -> Self {
436 self.iota_names_config = config;
437 self
438 }
439
440 pub fn with_enable_jsonrpc_api(mut self, enable_jsonrpc_api: bool) -> Self {
443 self.enable_jsonrpc_api = Some(enable_jsonrpc_api);
444 self
445 }
446
447 pub fn with_enable_grpc_api(mut self, enable_grpc_api: bool) -> Self {
448 self.enable_grpc_api = enable_grpc_api;
449 self
450 }
451
452 pub fn with_grpc_api_config(mut self, config: GrpcApiConfig) -> Self {
453 self.grpc_api_config = Some(config);
454 self
455 }
456
457 pub fn with_discovery_config(mut self, discovery_config: DiscoveryConfig) -> Self {
458 self.discovery_config = Some(discovery_config);
459 self
460 }
461
462 pub fn build_from_parts<R: rand::CryptoRng>(
468 self,
469 rng: &mut R,
470 validator_configs: &[NodeConfig],
471 genesis: iota_config::node::Genesis,
472 ) -> NodeConfig {
473 self.try_build_from_parts(rng, validator_configs, genesis)
474 .unwrap_or_else(|err| panic!("{err:#}"))
475 }
476
477 pub fn try_build_from_parts<R: rand::CryptoRng>(
482 self,
483 rng: &mut R,
484 validator_configs: &[NodeConfig],
485 genesis: iota_config::node::Genesis,
486 ) -> anyhow::Result<NodeConfig> {
487 let genesis_config = ValidatorGenesisConfigBuilder::new().build(rng);
490 self.try_build_from_genesis_config(genesis_config, validator_configs, genesis)
491 }
492
493 pub fn try_build_from_genesis_config(
509 self,
510 genesis_config: ValidatorGenesisConfig,
511 validator_configs: &[NodeConfig],
512 genesis: iota_config::node::Genesis,
513 ) -> anyhow::Result<NodeConfig> {
514 let ip = genesis_config
515 .network_address
516 .to_socket_addr()
517 .unwrap()
518 .ip()
519 .to_string();
520
521 let key_path = get_key_path(&genesis_config.authority_key_pair);
522 let config_directory = self
523 .config_directory
524 .unwrap_or_else(|| iota_common::tempdir().keep());
525
526 let migration_tx_data_path =
527 Some(config_directory.join(IOTA_GENESIS_MIGRATION_TX_DATA_FILENAME));
528
529 let p2p_config = {
530 let seed_peers = validator_configs
531 .iter()
532 .enumerate()
533 .map(|(index, config)| {
534 let address = config.p2p_config.external_address.clone().ok_or_else(|| {
535 anyhow!(
536 "validator {index} has no `p2p-config.external-address`, which the \
537 fullnode needs to derive its seed peers: either its config never set \
538 one or it was cleared"
539 )
540 })?;
541 Ok(SeedPeer {
542 peer_id: Some(anemo::PeerId(
543 config.network_private_key().public_key().into_bytes(),
544 )),
545 address,
546 })
547 })
548 .collect::<anyhow::Result<Vec<_>>>()?;
549
550 P2pConfig {
551 listen_address: self.p2p_listen_address.unwrap_or_else(|| {
552 genesis_config.p2p_listen_address.unwrap_or_else(|| {
553 genesis_config
554 .p2p_address
555 .udp_multiaddr_to_listen_address()
556 .unwrap()
557 })
558 }),
559 external_address: self
560 .p2p_external_address
561 .or(Some(genesis_config.p2p_address.clone())),
562 seed_peers,
563 state_sync: Some(StateSyncConfig {
566 checkpoint_content_timeout_ms: Some(10_000),
567 ..Default::default()
568 }),
569 discovery: self.discovery_config,
571 ..Default::default()
572 }
573 };
574
575 let json_rpc_address = self.json_rpc_address.unwrap_or_else(|| {
576 self.rpc_addr.unwrap_or_else(|| {
577 let rpc_port = self
578 .rpc_port
579 .unwrap_or_else(|| local_ip_utils::get_available_port(&ip));
580 format!("{ip}:{rpc_port}").parse().unwrap()
581 })
582 });
583
584 let grpc_api_config = self.grpc_api_config.or_else(|| {
585 if self.enable_grpc_api {
586 Some(GrpcApiConfig {
587 address: format!("{ip}:{}", local_ip_utils::get_available_port(&ip))
588 .parse()
589 .unwrap(),
590 ..Default::default()
591 })
592 } else {
593 Some(GrpcApiConfig::default())
597 }
598 });
599
600 let checkpoint_executor_config = CheckpointExecutorConfig {
601 data_ingestion_dir: self.data_ingestion_dir,
602 ..Default::default()
603 };
604
605 let mut pruning_config = local_network_pruning_config();
606 if let Some(epochs) = self.num_epochs_to_retain_for_indexes {
607 pruning_config.num_epochs_to_retain_for_indexes = Some(epochs);
608 }
609 if self.disable_pruning {
610 pruning_config.set_num_epochs_to_retain_for_checkpoints(Some(u64::MAX));
611 pruning_config.set_num_epochs_to_retain(u64::MAX);
612 };
613
614 Ok(NodeConfig {
615 authority_key_pair: AuthorityKeyPairWithPath::new(genesis_config.authority_key_pair),
616 account_key_pair: KeyPairWithPath::new(genesis_config.account_key_pair),
617 protocol_key_pair: KeyPairWithPath::new(genesis_config.protocol_key_pair.into()),
618 network_key_pair: self
619 .network_key_pair
620 .unwrap_or(KeyPairWithPath::new(genesis_config.network_key_pair.into())),
621 db_path: self
622 .db_path
623 .unwrap_or(config_directory.join(FULL_NODE_DB_PATH).join(key_path)),
624 network_address: self
625 .network_address
626 .unwrap_or(genesis_config.network_address),
627 metrics_address: self
628 .metrics_address
629 .unwrap_or(genesis_config.metrics_address),
630 admin_interface_address: self
631 .admin_interface_address
632 .unwrap_or(genesis_config.admin_interface_address),
633 json_rpc_address,
634 consensus_config: None,
635 enable_jsonrpc_api: self
636 .enable_jsonrpc_api
637 .unwrap_or_else(default_enable_jsonrpc_api),
638 genesis,
639 migration_tx_data_path,
640 grpc_load_shed: None,
641 grpc_concurrency_limit_per_core: NonZeroUsize::new(500_000_000).unwrap(),
644 p2p_config,
645 authority_store_pruning_config: pruning_config,
646 end_of_epoch_broadcast_channel_capacity:
647 default_end_of_epoch_broadcast_channel_capacity(),
648 checkpoint_executor_config,
649 metrics: None,
650 supported_protocol_versions: self.supported_protocol_versions,
651 expensive_safety_check_config: self
652 .expensive_safety_check_config
653 .unwrap_or_else(ExpensiveSafetyCheckConfig::new_enable_all),
654 transaction_deny_config: Default::default(),
655 certificate_deny_config: Default::default(),
656 state_debug_dump_config: Default::default(),
657 checkpoint_archive_config: None,
658 state_snapshot_write_config: self.state_snapshot_write_config.unwrap_or_default(),
659 transaction_kv_store_read_config: Default::default(),
660 transaction_kv_store_write_config: Default::default(),
661 authority_overload_config: Default::default(),
662 run_with_range: self.run_with_range,
663 policy_config: self.policy_config,
664 execution_cache_config: ExecutionCacheConfig::default(),
665 full_checkpoint_contents_cache_size_mb: default_full_checkpoint_contents_cache_size_mb(
666 ),
667 enable_validator_tx_finalizer: false,
669 enable_soft_locking: true,
672 verifier_signing_config: VerifierSigningConfig::default(),
673 post_consensus_validation_readers: None,
674 enable_db_write_stall: None,
675 iota_names_config: self.iota_names_config,
676 enable_grpc_api: self.enable_grpc_api,
677 grpc_api_config,
678 chain_override_for_testing: self.chain_override,
679 validator_client_monitor_config: None,
680 validator_grpc_listener_limits: Default::default(),
681 json_rpc_listener_limits: Default::default(),
682 grpc_api_listener_limits: Default::default(),
683 })
684 }
685
686 pub fn build<R: rand::CryptoRng>(
692 self,
693 rng: &mut R,
694 network_config: &NetworkConfig,
695 ) -> NodeConfig {
696 self.try_build(rng, network_config)
697 .unwrap_or_else(|err| panic!("{err:#}"))
698 }
699
700 pub fn try_build<R: rand::CryptoRng>(
704 self,
705 rng: &mut R,
706 network_config: &NetworkConfig,
707 ) -> anyhow::Result<NodeConfig> {
708 let genesis = self.genesis_for(network_config);
709 self.try_build_from_parts(rng, network_config.validator_configs(), genesis)
710 }
711
712 pub fn try_build_with_genesis_config(
717 self,
718 genesis_config: ValidatorGenesisConfig,
719 network_config: &NetworkConfig,
720 ) -> anyhow::Result<NodeConfig> {
721 let genesis = self.genesis_for(network_config);
722 self.try_build_from_genesis_config(
723 genesis_config,
724 network_config.validator_configs(),
725 genesis,
726 )
727 }
728
729 fn genesis_for(&self, network_config: &NetworkConfig) -> Genesis {
730 self.genesis
731 .as_ref()
732 .or_else(|| network_config.get_validator_genesis())
733 .cloned()
734 .unwrap_or_else(|| Genesis::new(network_config.genesis.clone()))
735 }
736}
737
738fn get_key_path(key_pair: &AuthorityKeyPair) -> String {
741 let public_key: AuthorityPublicKeyBytes = key_pair.public().into();
742 let mut key_path = Hex::encode(public_key);
743 key_path.truncate(12);
746 key_path
747}
748
749fn local_network_pruning_config() -> AuthorityStorePruningConfig {
754 let mut pruning_config = AuthorityStorePruningConfig::default();
755 if !cfg!(msim) {
756 pruning_config.set_num_epochs_to_retain_for_checkpoints(Some(u64::MAX));
757 }
758 pruning_config
759}
760
761#[cfg(test)]
762mod tests {
763 use rand::{rand_core::UnwrapErr, rngs::SysRng};
764
765 use super::{FullnodeConfigBuilder, Genesis, ValidatorGenesisConfigBuilder};
766
767 #[test]
770 fn a_fullnode_takes_its_addresses_from_its_genesis_config() {
771 let dir = tempfile::TempDir::new().unwrap();
772 let mut genesis_config = ValidatorGenesisConfigBuilder::new()
773 .with_ip("127.0.0.1".to_owned())
774 .build(&mut UnwrapErr(SysRng));
775 genesis_config.metrics_address = ([127, 0, 0, 1], 9184).into();
776 genesis_config.admin_interface_address = ([127, 0, 0, 1], 9185).into();
777 genesis_config.p2p_address = "/ip4/127.0.0.1/udp/9186/http".parse().unwrap();
778
779 let config = FullnodeConfigBuilder::new()
780 .with_config_directory(dir.path().to_path_buf())
781 .try_build_from_genesis_config(
782 genesis_config.copy_with_private_keys(),
783 &[],
784 Genesis::new_empty(),
785 )
786 .unwrap();
787
788 assert_eq!(config.metrics_address.to_string(), "127.0.0.1:9184");
789 assert_eq!(config.admin_interface_address.to_string(), "127.0.0.1:9185");
790 assert_eq!(
791 config.p2p_config.external_address.as_ref().unwrap(),
792 &genesis_config.p2p_address
793 );
794 assert_eq!(
795 config.p2p_config.listen_address.to_string(),
796 "127.0.0.1:9186"
797 );
798
799 let same = FullnodeConfigBuilder::new()
801 .with_config_directory(dir.path().to_path_buf())
802 .try_build_from_genesis_config(genesis_config, &[], Genesis::new_empty())
803 .unwrap();
804 assert_eq!(config.db_path, same.db_path);
805 assert_eq!(
806 config.authority_public_key(),
807 same.authority_public_key(),
808 "the fullnode's identity is not the one its genesis config gives it"
809 );
810 }
811
812 #[test]
813 fn an_address_set_on_the_builder_wins_over_the_genesis_config() {
814 let mut genesis_config = ValidatorGenesisConfigBuilder::new()
815 .with_ip("127.0.0.1".to_owned())
816 .build(&mut UnwrapErr(SysRng));
817 genesis_config.metrics_address = ([127, 0, 0, 1], 9184).into();
818 genesis_config.admin_interface_address = ([127, 0, 0, 1], 9185).into();
819
820 let config = FullnodeConfigBuilder::new()
821 .with_admin_interface_address(Some(([127, 0, 0, 1], 1337)))
822 .try_build_from_genesis_config(genesis_config, &[], Genesis::new_empty())
823 .unwrap();
824
825 assert_eq!(config.admin_interface_address.to_string(), "127.0.0.1:1337");
826 assert_eq!(config.metrics_address.to_string(), "127.0.0.1:9184");
827 }
828 #[test]
831 fn every_builder_constructor_serves_json_rpc_unless_told_otherwise() {
832 let build = |builder: FullnodeConfigBuilder| {
833 let genesis_config = ValidatorGenesisConfigBuilder::new()
834 .with_ip("127.0.0.1".to_owned())
835 .build(&mut UnwrapErr(SysRng));
836 builder
837 .try_build_from_genesis_config(genesis_config, &[], Genesis::new_empty())
838 .unwrap()
839 .enable_jsonrpc_api
840 };
841 assert!(build(FullnodeConfigBuilder::default()));
842 assert!(build(FullnodeConfigBuilder::new()));
843 assert!(!build(
844 FullnodeConfigBuilder::new().with_enable_jsonrpc_api(false)
845 ));
846 }
847}