1use std::{net::SocketAddr, path::PathBuf, time::Duration};
6
7use fastcrypto::{
8 encoding::{Encoding, Hex},
9 traits::KeyPair,
10};
11use iota_config::{
12 AUTHORITIES_DB_NAME, CONSENSUS_DB_NAME, ConsensusConfig, FULL_NODE_DB_PATH,
13 IOTA_GENESIS_MIGRATION_TX_DATA_FILENAME, NodeConfig, local_ip_utils,
14 node::{
15 AuthorityKeyPairWithPath, AuthorityOverloadConfig, AuthorityStorePruningConfig,
16 CheckpointExecutorConfig, DBCheckpointConfig, DEFAULT_GRPC_CONCURRENCY_LIMIT,
17 ExecutionCacheConfig, ExecutionCacheType, ExpensiveSafetyCheckConfig, Genesis,
18 GrpcApiConfig, KeyPairWithPath, RunWithRange, StateArchiveConfig, StateSnapshotConfig,
19 default_enable_index_processing, default_end_of_epoch_broadcast_channel_capacity,
20 default_zklogin_oauth_providers,
21 },
22 p2p::{DiscoveryConfig, P2pConfig, SeedPeer, StateSyncConfig},
23 verifier_signing_config::VerifierSigningConfig,
24};
25use iota_names::config::IotaNamesConfig;
26use iota_protocol_config::Chain;
27use iota_types::{
28 crypto::{AuthorityKeyPair, AuthorityPublicKeyBytes, IotaKeyPair, NetworkKeyPair},
29 multiaddr::Multiaddr,
30 supported_protocol_versions::SupportedProtocolVersions,
31 traffic_control::{PolicyConfig, RemoteFirewallConfig},
32};
33
34use crate::{
35 genesis_config::{ValidatorGenesisConfig, ValidatorGenesisConfigBuilder},
36 network_config::NetworkConfig,
37};
38
39#[derive(Clone, Default)]
43pub struct ValidatorConfigBuilder {
44 config_directory: Option<PathBuf>,
45 supported_protocol_versions: Option<SupportedProtocolVersions>,
46 force_unpruned_checkpoints: bool,
47 jwk_fetch_interval: Option<Duration>,
48 authority_overload_config: Option<AuthorityOverloadConfig>,
49 execution_cache_type: Option<ExecutionCacheType>,
50 execution_cache_config: Option<ExecutionCacheConfig>,
51 data_ingestion_dir: Option<PathBuf>,
52 policy_config: Option<PolicyConfig>,
53 firewall_config: Option<RemoteFirewallConfig>,
54 max_submit_position: Option<usize>,
55 submit_delay_step_override_millis: Option<u64>,
56 discovery_config: Option<DiscoveryConfig>,
57 chain_override: Option<Chain>,
58}
59
60impl ValidatorConfigBuilder {
61 pub fn new() -> Self {
62 Self {
63 ..Default::default()
64 }
65 }
66
67 pub fn with_chain_override(mut self, chain: Chain) -> Self {
68 assert!(self.chain_override.is_none(), "Chain override already set");
69 self.chain_override = Some(chain);
70 self
71 }
72
73 pub fn with_config_directory(mut self, config_directory: PathBuf) -> Self {
74 assert!(self.config_directory.is_none());
75 self.config_directory = Some(config_directory);
76 self
77 }
78
79 pub fn with_supported_protocol_versions(
80 mut self,
81 supported_protocol_versions: SupportedProtocolVersions,
82 ) -> Self {
83 assert!(self.supported_protocol_versions.is_none());
84 self.supported_protocol_versions = Some(supported_protocol_versions);
85 self
86 }
87
88 pub fn with_unpruned_checkpoints(mut self) -> Self {
89 self.force_unpruned_checkpoints = true;
90 self
91 }
92
93 pub fn with_jwk_fetch_interval(mut self, i: Duration) -> Self {
94 self.jwk_fetch_interval = Some(i);
95 self
96 }
97
98 pub fn with_authority_overload_config(mut self, config: AuthorityOverloadConfig) -> Self {
99 self.authority_overload_config = Some(config);
100 self
101 }
102
103 pub fn with_execution_cache_type(mut self, execution_cache_type: ExecutionCacheType) -> Self {
104 self.execution_cache_type = Some(execution_cache_type);
105 self
106 }
107
108 pub fn with_execution_cache_config(mut self, config: ExecutionCacheConfig) -> Self {
109 self.execution_cache_config = Some(config);
110 self
111 }
112
113 pub fn with_data_ingestion_dir(mut self, path: PathBuf) -> Self {
114 self.data_ingestion_dir = Some(path);
115 self
116 }
117
118 pub fn with_policy_config(mut self, config: Option<PolicyConfig>) -> Self {
119 self.policy_config = config;
120 self
121 }
122
123 pub fn with_firewall_config(mut self, config: Option<RemoteFirewallConfig>) -> Self {
124 self.firewall_config = config;
125 self
126 }
127
128 pub fn with_max_submit_position(mut self, max_submit_position: usize) -> Self {
129 self.max_submit_position = Some(max_submit_position);
130 self
131 }
132
133 pub fn with_submit_delay_step_override_millis(
134 mut self,
135 submit_delay_step_override_millis: u64,
136 ) -> Self {
137 self.submit_delay_step_override_millis = Some(submit_delay_step_override_millis);
138 self
139 }
140
141 pub fn with_discovery_config(mut self, discovery_config: DiscoveryConfig) -> Self {
142 self.discovery_config = Some(discovery_config);
143 self
144 }
145
146 pub fn build_without_genesis(self, validator: ValidatorGenesisConfig) -> NodeConfig {
147 let key_path = get_key_path(&validator.authority_key_pair);
148 let config_directory = self
149 .config_directory
150 .unwrap_or_else(|| tempfile::tempdir().unwrap().keep());
151 let migration_tx_data_path =
152 Some(config_directory.join(IOTA_GENESIS_MIGRATION_TX_DATA_FILENAME));
153 let db_path = config_directory
154 .join(AUTHORITIES_DB_NAME)
155 .join(key_path.clone());
156 let network_address = validator.network_address;
157 let consensus_db_path = config_directory.join(CONSENSUS_DB_NAME).join(key_path);
158 let localhost = local_ip_utils::localhost_for_testing();
159 let consensus_config = ConsensusConfig {
160 db_path: consensus_db_path,
161 db_retention_epochs: None,
162 db_pruner_period_secs: None,
163 max_pending_transactions: None,
164 max_submit_position: self.max_submit_position,
165 submit_delay_step_override_millis: self.submit_delay_step_override_millis,
166 parameters: Default::default(),
167 starfish_parameters: Default::default(),
168 };
169
170 let p2p_config = P2pConfig {
171 listen_address: validator.p2p_listen_address.unwrap_or_else(|| {
172 validator
173 .p2p_address
174 .udp_multiaddr_to_listen_address()
175 .unwrap()
176 }),
177 external_address: Some(validator.p2p_address),
178 state_sync: Some(StateSyncConfig {
181 checkpoint_content_timeout_ms: Some(10_000),
182 ..Default::default()
183 }),
184 discovery: self.discovery_config,
186 ..Default::default()
187 };
188
189 let mut pruning_config = AuthorityStorePruningConfig::default();
190 if self.force_unpruned_checkpoints {
191 pruning_config.set_num_epochs_to_retain_for_checkpoints(None);
192 }
193 let pruning_config = pruning_config;
194 let checkpoint_executor_config = CheckpointExecutorConfig {
195 data_ingestion_dir: self.data_ingestion_dir,
196 ..Default::default()
197 };
198
199 NodeConfig {
200 authority_key_pair: AuthorityKeyPairWithPath::new(validator.authority_key_pair),
201 network_key_pair: KeyPairWithPath::new(IotaKeyPair::Ed25519(
202 validator.network_key_pair,
203 )),
204 account_key_pair: KeyPairWithPath::new(validator.account_key_pair),
205 protocol_key_pair: KeyPairWithPath::new(IotaKeyPair::Ed25519(
206 validator.protocol_key_pair,
207 )),
208 db_path,
209 network_address,
210 metrics_address: validator.metrics_address,
211 admin_interface_address: validator.admin_interface_address,
212 json_rpc_address: local_ip_utils::new_tcp_address_for_testing(&localhost)
213 .to_socket_addr()
214 .unwrap(),
215 consensus_config: Some(consensus_config),
216 remove_deprecated_tables: false,
217 enable_index_processing: default_enable_index_processing(),
218 genesis: Genesis::new_empty(),
219 migration_tx_data_path,
220 grpc_load_shed: None,
221 grpc_concurrency_limit: Some(DEFAULT_GRPC_CONCURRENCY_LIMIT),
222 p2p_config,
223 authority_store_pruning_config: pruning_config,
224 end_of_epoch_broadcast_channel_capacity:
225 default_end_of_epoch_broadcast_channel_capacity(),
226 checkpoint_executor_config,
227 metrics: None,
228 supported_protocol_versions: self.supported_protocol_versions,
229 db_checkpoint_config: Default::default(),
230 expensive_safety_check_config: ExpensiveSafetyCheckConfig::default(),
233 transaction_deny_config: Default::default(),
234 certificate_deny_config: Default::default(),
235 state_debug_dump_config: Default::default(),
236 state_archive_write_config: StateArchiveConfig::default(),
237 state_archive_read_config: vec![],
238 state_snapshot_write_config: StateSnapshotConfig::default(),
239 indexer_max_subscriptions: Default::default(),
240 transaction_kv_store_read_config: Default::default(),
241 transaction_kv_store_write_config: None,
242 enable_rest_api: true,
243 rest: Some(iota_rest_api::Config {
244 enable_unstable_apis: Some(true),
245 ..Default::default()
246 }),
247 jwk_fetch_interval_seconds: self
248 .jwk_fetch_interval
249 .map(|i| i.as_secs())
250 .unwrap_or(3600),
251 zklogin_oauth_providers: default_zklogin_oauth_providers(),
252 authority_overload_config: self.authority_overload_config.unwrap_or_default(),
253 execution_cache: self.execution_cache_type.unwrap_or_default(),
254 execution_cache_config: self.execution_cache_config.unwrap_or_default(),
255 run_with_range: None,
256 jsonrpc_server_type: None,
257 policy_config: self.policy_config,
258 firewall_config: self.firewall_config,
259 enable_validator_tx_finalizer: true,
260 verifier_signing_config: VerifierSigningConfig::default(),
261 enable_db_write_stall: None,
262 iota_names_config: None,
263 enable_grpc_api: false,
264 grpc_api_config: None,
265 chain_override_for_testing: self.chain_override,
266 }
267 }
268
269 pub fn build(
270 self,
271 validator: ValidatorGenesisConfig,
272 genesis: iota_config::genesis::Genesis,
273 ) -> NodeConfig {
274 let mut config = self.build_without_genesis(validator);
275 config.genesis = iota_config::node::Genesis::new(genesis);
276 config
277 }
278
279 pub fn build_new_validator<R: rand::RngCore + rand::CryptoRng>(
280 self,
281 rng: &mut R,
282 network_config: &NetworkConfig,
283 ) -> NodeConfig {
284 let validator_config = ValidatorGenesisConfigBuilder::new().build(rng);
285 self.build(validator_config, network_config.genesis.clone())
286 }
287}
288
289#[derive(Clone, Debug, Default)]
290pub struct FullnodeConfigBuilder {
291 config_directory: Option<PathBuf>,
292 rpc_port: Option<u16>,
294 rpc_addr: Option<SocketAddr>,
295 supported_protocol_versions: Option<SupportedProtocolVersions>,
296 db_checkpoint_config: Option<DBCheckpointConfig>,
297 expensive_safety_check_config: Option<ExpensiveSafetyCheckConfig>,
298 db_path: Option<PathBuf>,
299 network_address: Option<Multiaddr>,
300 json_rpc_address: Option<SocketAddr>,
301 metrics_address: Option<SocketAddr>,
302 admin_interface_address: Option<SocketAddr>,
303 genesis: Option<Genesis>,
304 p2p_external_address: Option<Multiaddr>,
305 p2p_listen_address: Option<SocketAddr>,
306 network_key_pair: Option<KeyPairWithPath>,
307 run_with_range: Option<RunWithRange>,
308 policy_config: Option<PolicyConfig>,
309 fw_config: Option<RemoteFirewallConfig>,
310 data_ingestion_dir: Option<PathBuf>,
311 disable_pruning: bool,
312 iota_names_config: Option<IotaNamesConfig>,
313 grpc_api_config: Option<GrpcApiConfig>,
314 discovery_config: Option<DiscoveryConfig>,
315 chain_override: Option<Chain>,
316}
317
318impl FullnodeConfigBuilder {
319 pub fn new() -> Self {
320 Self::default()
321 }
322
323 pub fn with_chain_override(mut self, chain: Chain) -> Self {
324 assert!(self.chain_override.is_none(), "Chain override already set");
325 self.chain_override = Some(chain);
326 self
327 }
328
329 pub fn with_config_directory(mut self, config_directory: PathBuf) -> Self {
330 self.config_directory = Some(config_directory);
331 self
332 }
333
334 pub fn with_rpc_port(mut self, port: u16) -> Self {
335 assert!(self.rpc_addr.is_none() && self.rpc_port.is_none());
336 self.rpc_port = Some(port);
337 self
338 }
339
340 pub fn with_rpc_addr(mut self, addr: impl Into<SocketAddr>) -> Self {
341 assert!(self.rpc_addr.is_none() && self.rpc_port.is_none());
342 self.rpc_addr = Some(addr.into());
343 self
344 }
345
346 pub fn with_supported_protocol_versions(mut self, versions: SupportedProtocolVersions) -> Self {
347 self.supported_protocol_versions = Some(versions);
348 self
349 }
350
351 pub fn with_db_checkpoint_config(mut self, db_checkpoint_config: DBCheckpointConfig) -> Self {
352 self.db_checkpoint_config = Some(db_checkpoint_config);
353 self
354 }
355
356 pub fn with_disable_pruning(mut self, disable_pruning: bool) -> Self {
357 self.disable_pruning = disable_pruning;
358 self
359 }
360
361 pub fn with_expensive_safety_check_config(
362 mut self,
363 expensive_safety_check_config: ExpensiveSafetyCheckConfig,
364 ) -> Self {
365 self.expensive_safety_check_config = Some(expensive_safety_check_config);
366 self
367 }
368
369 pub fn with_db_path(mut self, db_path: PathBuf) -> Self {
370 self.db_path = Some(db_path);
371 self
372 }
373
374 pub fn with_network_address(mut self, network_address: Multiaddr) -> Self {
375 self.network_address = Some(network_address);
376 self
377 }
378
379 pub fn with_json_rpc_address(mut self, json_rpc_address: impl Into<SocketAddr>) -> Self {
380 self.json_rpc_address = Some(json_rpc_address.into());
381 self
382 }
383
384 pub fn with_metrics_address(mut self, metrics_address: impl Into<SocketAddr>) -> Self {
385 self.metrics_address = Some(metrics_address.into());
386 self
387 }
388
389 pub fn with_admin_interface_address(
390 mut self,
391 admin_interface_address: Option<impl Into<SocketAddr>>,
392 ) -> Self {
393 self.admin_interface_address = admin_interface_address.map(|addr| addr.into());
394 self
395 }
396
397 pub fn with_genesis(mut self, genesis: Genesis) -> Self {
398 self.genesis = Some(genesis);
399 self
400 }
401
402 pub fn with_p2p_external_address(mut self, p2p_external_address: Multiaddr) -> Self {
403 self.p2p_external_address = Some(p2p_external_address);
404 self
405 }
406
407 pub fn with_p2p_listen_address(mut self, p2p_listen_address: impl Into<SocketAddr>) -> Self {
408 self.p2p_listen_address = Some(p2p_listen_address.into());
409 self
410 }
411
412 pub fn with_network_key_pair(mut self, network_key_pair: Option<NetworkKeyPair>) -> Self {
413 if let Some(network_key_pair) = network_key_pair {
414 self.network_key_pair =
415 Some(KeyPairWithPath::new(IotaKeyPair::Ed25519(network_key_pair)));
416 }
417 self
418 }
419
420 pub fn with_run_with_range(mut self, run_with_range: Option<RunWithRange>) -> Self {
421 if let Some(run_with_range) = run_with_range {
422 self.run_with_range = Some(run_with_range);
423 }
424 self
425 }
426
427 pub fn with_policy_config(mut self, config: Option<PolicyConfig>) -> Self {
428 self.policy_config = config;
429 self
430 }
431
432 pub fn with_fw_config(mut self, config: Option<RemoteFirewallConfig>) -> Self {
433 self.fw_config = config;
434 self
435 }
436
437 pub fn with_data_ingestion_dir(mut self, path: Option<PathBuf>) -> Self {
438 self.data_ingestion_dir = path;
439 self
440 }
441
442 pub fn with_iota_names_config(mut self, config: Option<IotaNamesConfig>) -> Self {
443 self.iota_names_config = config;
444 self
445 }
446
447 pub fn with_grpc_api_config(mut self, config: GrpcApiConfig) -> Self {
448 self.grpc_api_config = Some(config);
449 self
450 }
451
452 pub fn with_discovery_config(mut self, discovery_config: DiscoveryConfig) -> Self {
453 self.discovery_config = Some(discovery_config);
454 self
455 }
456
457 pub fn build_from_parts<R: rand::RngCore + rand::CryptoRng>(
458 self,
459 rng: &mut R,
460 validator_configs: &[NodeConfig],
461 genesis: iota_config::node::Genesis,
462 ) -> NodeConfig {
463 let validator_config = ValidatorGenesisConfigBuilder::new().build(rng);
466 let ip = validator_config
467 .network_address
468 .to_socket_addr()
469 .unwrap()
470 .ip()
471 .to_string();
472
473 let key_path = get_key_path(&validator_config.authority_key_pair);
474 let config_directory = self
475 .config_directory
476 .unwrap_or_else(|| tempfile::tempdir().unwrap().keep());
477
478 let migration_tx_data_path =
479 Some(config_directory.join(IOTA_GENESIS_MIGRATION_TX_DATA_FILENAME));
480
481 let p2p_config = {
482 let seed_peers = validator_configs
483 .iter()
484 .map(|config| SeedPeer {
485 peer_id: Some(anemo::PeerId(
486 config.network_key_pair().public().0.to_bytes(),
487 )),
488 address: config.p2p_config.external_address.clone().unwrap(),
489 })
490 .collect();
491
492 P2pConfig {
493 listen_address: self.p2p_listen_address.unwrap_or_else(|| {
494 validator_config.p2p_listen_address.unwrap_or_else(|| {
495 validator_config
496 .p2p_address
497 .udp_multiaddr_to_listen_address()
498 .unwrap()
499 })
500 }),
501 external_address: self
502 .p2p_external_address
503 .or(Some(validator_config.p2p_address.clone())),
504 seed_peers,
505 state_sync: Some(StateSyncConfig {
508 checkpoint_content_timeout_ms: Some(10_000),
509 ..Default::default()
510 }),
511 discovery: self.discovery_config,
513 ..Default::default()
514 }
515 };
516
517 let json_rpc_address = self.rpc_addr.unwrap_or_else(|| {
518 let rpc_port = self
519 .rpc_port
520 .unwrap_or_else(|| local_ip_utils::get_available_port(&ip));
521 format!("{ip}:{rpc_port}").parse().unwrap()
522 });
523
524 let checkpoint_executor_config = CheckpointExecutorConfig {
525 data_ingestion_dir: self.data_ingestion_dir,
526 ..Default::default()
527 };
528
529 let mut pruning_config = AuthorityStorePruningConfig::default();
530 if self.disable_pruning {
531 pruning_config.set_num_epochs_to_retain_for_checkpoints(None);
532 pruning_config.set_num_epochs_to_retain(u64::MAX);
533 };
534
535 NodeConfig {
536 authority_key_pair: AuthorityKeyPairWithPath::new(validator_config.authority_key_pair),
537 account_key_pair: KeyPairWithPath::new(validator_config.account_key_pair),
538 protocol_key_pair: KeyPairWithPath::new(IotaKeyPair::Ed25519(
539 validator_config.protocol_key_pair,
540 )),
541 network_key_pair: self.network_key_pair.unwrap_or(KeyPairWithPath::new(
542 IotaKeyPair::Ed25519(validator_config.network_key_pair),
543 )),
544 db_path: self
545 .db_path
546 .unwrap_or(config_directory.join(FULL_NODE_DB_PATH).join(key_path)),
547 network_address: self
548 .network_address
549 .unwrap_or(validator_config.network_address),
550 metrics_address: self
551 .metrics_address
552 .unwrap_or(local_ip_utils::new_local_tcp_socket_for_testing()),
553 admin_interface_address: self
554 .admin_interface_address
555 .unwrap_or(local_ip_utils::new_local_tcp_socket_for_testing()),
556 json_rpc_address: self.json_rpc_address.unwrap_or(json_rpc_address),
557 consensus_config: None,
558 remove_deprecated_tables: false,
559 enable_index_processing: default_enable_index_processing(),
560 genesis,
561 migration_tx_data_path,
562 grpc_load_shed: None,
563 grpc_concurrency_limit: None,
564 p2p_config,
565 authority_store_pruning_config: pruning_config,
566 end_of_epoch_broadcast_channel_capacity:
567 default_end_of_epoch_broadcast_channel_capacity(),
568 checkpoint_executor_config,
569 metrics: None,
570 supported_protocol_versions: self.supported_protocol_versions,
571 db_checkpoint_config: self.db_checkpoint_config.unwrap_or_default(),
572 expensive_safety_check_config: self
573 .expensive_safety_check_config
574 .unwrap_or_else(ExpensiveSafetyCheckConfig::new_enable_all),
575 transaction_deny_config: Default::default(),
576 certificate_deny_config: Default::default(),
577 state_debug_dump_config: Default::default(),
578 state_archive_write_config: StateArchiveConfig::default(),
579 state_archive_read_config: vec![],
580 state_snapshot_write_config: StateSnapshotConfig::default(),
581 indexer_max_subscriptions: Default::default(),
582 transaction_kv_store_read_config: Default::default(),
583 transaction_kv_store_write_config: Default::default(),
584 enable_rest_api: true,
585 rest: Some(iota_rest_api::Config {
586 enable_unstable_apis: Some(true),
587 ..Default::default()
588 }),
589 jwk_fetch_interval_seconds: 3600,
591 zklogin_oauth_providers: default_zklogin_oauth_providers(),
592 authority_overload_config: Default::default(),
593 run_with_range: self.run_with_range,
594 jsonrpc_server_type: None,
595 policy_config: self.policy_config,
596 firewall_config: self.fw_config,
597 execution_cache: ExecutionCacheType::default(),
598 execution_cache_config: ExecutionCacheConfig::default(),
599 enable_validator_tx_finalizer: false,
601 verifier_signing_config: VerifierSigningConfig::default(),
602 enable_db_write_stall: None,
603 iota_names_config: self.iota_names_config,
604 enable_grpc_api: self.grpc_api_config.is_some(),
605 grpc_api_config: self.grpc_api_config,
606 chain_override_for_testing: self.chain_override,
607 }
608 }
609
610 pub fn build<R: rand::RngCore + rand::CryptoRng>(
611 self,
612 rng: &mut R,
613 network_config: &NetworkConfig,
614 ) -> NodeConfig {
615 let genesis = self
616 .genesis
617 .as_ref()
618 .or_else(|| network_config.get_validator_genesis())
619 .cloned()
620 .unwrap_or_else(|| iota_config::node::Genesis::new(network_config.genesis.clone()));
621 self.build_from_parts(rng, network_config.validator_configs(), genesis)
622 }
623}
624
625fn get_key_path(key_pair: &AuthorityKeyPair) -> String {
628 let public_key: AuthorityPublicKeyBytes = key_pair.public().into();
629 let mut key_path = Hex::encode(public_key);
630 key_path.truncate(12);
633 key_path
634}