1use std::net::{IpAddr, SocketAddr};
6
7use anyhow::Result;
8use fastcrypto::traits::KeyPair;
9use iota_config::{
10 Config,
11 genesis::{GenesisCeremonyParameters, PRE_V32_VALIDATOR_LOW_STAKE_THRESHOLD, TokenAllocation},
12 local_ip_utils,
13 node::{DEFAULT_COMMISSION_RATE, DEFAULT_VALIDATOR_GAS_PRICE},
14};
15use iota_genesis_builder::validator_info::{GenesisValidatorInfo, ValidatorInfo};
16use iota_multiaddr::Multiaddr;
17use iota_protocol_config::{Chain, ProtocolConfig};
18use iota_sdk_crypto::simple::SimpleKeypair;
19use iota_sdk_types::Address;
20use iota_types::{
21 committee::ProtocolVersion,
22 crypto::{
23 AccountPrivateKey, AuthorityKeyPair, AuthorityPublicKeyBytes, NetworkPrivateKey,
24 NetworkPublicKey, PublicKey, generate_proof_of_possession, get_key_pair_from_rng,
25 },
26};
27use rand::{
28 SeedableRng,
29 rand_core::UnwrapErr,
30 rngs::{StdRng, SysRng},
31};
32use serde::{Deserialize, Serialize};
33use tracing::info;
34
35#[derive(Serialize, Deserialize, Debug)]
37pub struct SsfnGenesisConfig {
38 pub p2p_address: Multiaddr,
39 #[serde(default, with = "base64_formatted_network_private_key::option")]
40 pub network_key_pair: Option<NetworkPrivateKey>,
41}
42
43#[derive(Serialize, Deserialize)]
45pub struct ValidatorGenesisConfig {
46 #[serde(default = "default_bls12381_key_pair")]
47 pub authority_key_pair: AuthorityKeyPair,
48 #[serde(
49 default = "default_network_private_key",
50 with = "base64_formatted_network_private_key"
51 )]
52 pub protocol_key_pair: NetworkPrivateKey,
53 #[serde(default = "default_iota_key_pair", with = "base64_formatted_keypair")]
54 pub account_key_pair: SimpleKeypair,
55 #[serde(
56 default = "default_network_private_key",
57 with = "base64_formatted_network_private_key"
58 )]
59 pub network_key_pair: NetworkPrivateKey,
60 pub network_address: Multiaddr,
61 pub p2p_address: Multiaddr,
62 pub p2p_listen_address: Option<SocketAddr>,
63 #[serde(default = "default_socket_address")]
64 pub metrics_address: SocketAddr,
65 #[serde(default = "default_socket_address")]
66 pub admin_interface_address: SocketAddr,
67 pub gas_price: u64,
68 pub commission_rate: u64,
69 pub primary_address: Multiaddr,
70 #[serde(default = "default_stake")]
71 pub stake: u64,
72 pub name: Option<String>,
73}
74
75impl ValidatorGenesisConfig {
76 pub fn copy_with_private_keys(&self) -> Self {
80 Self {
81 authority_key_pair: self.authority_key_pair.copy(),
82 protocol_key_pair: self.protocol_key_pair.clone(),
83 account_key_pair: self.account_key_pair.clone(),
84 network_key_pair: self.network_key_pair.clone(),
85 network_address: self.network_address.clone(),
86 p2p_address: self.p2p_address.clone(),
87 p2p_listen_address: self.p2p_listen_address,
88 metrics_address: self.metrics_address,
89 admin_interface_address: self.admin_interface_address,
90 gas_price: self.gas_price,
91 commission_rate: self.commission_rate,
92 primary_address: self.primary_address.clone(),
93 stake: self.stake,
94 name: self.name.clone(),
95 }
96 }
97
98 pub fn to_validator_info(&self, name: String) -> GenesisValidatorInfo {
99 let authority_key: AuthorityPublicKeyBytes = self.authority_key_pair.public().into();
100 let account_key = PublicKey::from(&self.account_key_pair);
101 let network_key: NetworkPublicKey = self.network_key_pair.public_key();
102 let protocol_key: NetworkPublicKey = self.protocol_key_pair.public_key();
103 let network_address = self.network_address.clone();
104
105 let info = ValidatorInfo {
106 name,
107 authority_key,
108 protocol_key,
109 network_key,
110 account_address: Address::from(&account_key),
111 gas_price: self.gas_price,
112 commission_rate: self.commission_rate,
113 network_address,
114 p2p_address: self.p2p_address.clone(),
115 primary_address: self.primary_address.clone(),
116 description: String::new(),
117 image_url: String::new(),
118 project_url: String::new(),
119 };
120 let proof_of_possession = generate_proof_of_possession(
121 &self.authority_key_pair,
122 (&PublicKey::from(&self.account_key_pair)).into(),
123 );
124 GenesisValidatorInfo {
125 info,
126 proof_of_possession,
127 }
128 }
129
130 pub fn to_validator_info_with_random_name(&self) -> GenesisValidatorInfo {
132 self.to_validator_info(self.authority_key_pair.public().to_string())
133 }
134}
135
136#[derive(Default)]
137pub struct ValidatorGenesisConfigBuilder {
138 authority_key_pair: Option<AuthorityKeyPair>,
139 account_private_key: Option<AccountPrivateKey>,
140 ip: Option<String>,
141 gas_price: Option<u64>,
142 port_offset: Option<u16>,
145 p2p_listen_ip_address: Option<IpAddr>,
148 metrics_ip_address: Option<IpAddr>,
149 protocol_version: Option<ProtocolVersion>,
150}
151
152impl ValidatorGenesisConfigBuilder {
153 pub fn new() -> Self {
154 Self::default()
155 }
156
157 pub fn with_authority_key_pair(mut self, key_pair: AuthorityKeyPair) -> Self {
158 self.authority_key_pair = Some(key_pair);
159 self
160 }
161
162 pub fn with_account_private_key(mut self, private_key: AccountPrivateKey) -> Self {
163 self.account_private_key = Some(private_key);
164 self
165 }
166
167 pub fn with_ip(mut self, ip: String) -> Self {
168 self.ip = Some(ip);
169 self
170 }
171
172 pub fn with_gas_price(mut self, gas_price: u64) -> Self {
173 self.gas_price = Some(gas_price);
174 self
175 }
176
177 pub fn with_deterministic_ports(mut self, port_offset: u16) -> Self {
178 self.port_offset = Some(port_offset);
179 self
180 }
181
182 pub fn with_p2p_listen_ip_address(mut self, p2p_listen_ip_address: IpAddr) -> Self {
183 self.p2p_listen_ip_address = Some(p2p_listen_ip_address);
184 self
185 }
186
187 pub fn with_metrics_ip_address(mut self, metrics_ip_address: IpAddr) -> Self {
191 self.metrics_ip_address = Some(metrics_ip_address);
192 self
193 }
194
195 pub fn with_protocol_version(mut self, protocol_version: ProtocolVersion) -> Self {
198 self.protocol_version = Some(protocol_version);
199 self
200 }
201
202 pub fn build<R: rand::CryptoRng>(self, rng: &mut R) -> ValidatorGenesisConfig {
203 let ip = self.ip.unwrap_or_else(local_ip_utils::get_new_ip);
204 let localhost = local_ip_utils::localhost_for_testing();
205
206 let authority_key_pair = self
207 .authority_key_pair
208 .unwrap_or_else(|| get_key_pair_from_rng(rng).1);
209 let account_private_key = self
210 .account_private_key
211 .unwrap_or_else(|| get_key_pair_from_rng(rng).1);
212 let gas_price = self.gas_price.unwrap_or(DEFAULT_VALIDATOR_GAS_PRICE);
213
214 let (protocol_private_key, network_private_key): (NetworkPrivateKey, NetworkPrivateKey) =
215 (get_key_pair_from_rng(rng).1, get_key_pair_from_rng(rng).1);
216
217 let metrics_ip = self.metrics_ip_address.map(|ip| ip.to_string());
218
219 let (
220 network_address,
221 p2p_address,
222 metrics_address,
223 primary_address,
224 admin_interface_address,
225 ) = if let Some(offset) = self.port_offset {
226 (
227 local_ip_utils::new_deterministic_tcp_address_for_testing(&ip, offset),
228 local_ip_utils::new_deterministic_udp_address_for_testing(&ip, offset + 1),
229 match &metrics_ip {
230 Some(metrics_ip) => local_ip_utils::new_deterministic_tcp_address_for_testing(
231 metrics_ip,
232 offset + 2,
233 ),
234 None => {
235 local_ip_utils::new_deterministic_tcp_address_for_testing(&ip, offset + 2)
236 .with_zero_ip()
237 }
238 },
239 local_ip_utils::new_deterministic_udp_address_for_testing(&ip, offset + 3),
240 local_ip_utils::new_deterministic_tcp_address_for_testing(&ip, offset + 4),
241 )
242 } else {
243 (
244 local_ip_utils::new_tcp_address_for_testing(&ip),
245 local_ip_utils::new_udp_address_for_testing(&ip),
246 local_ip_utils::new_tcp_address_for_testing(
247 metrics_ip.as_deref().unwrap_or(&localhost),
248 ),
249 local_ip_utils::new_udp_address_for_testing(&ip),
250 local_ip_utils::new_tcp_address_for_testing(&localhost),
251 )
252 };
253
254 let p2p_listen_address = self
255 .p2p_listen_ip_address
256 .map(|ip| SocketAddr::new(ip, p2p_address.port().unwrap()));
257
258 ValidatorGenesisConfig {
259 authority_key_pair,
260 protocol_key_pair: protocol_private_key,
261 account_key_pair: account_private_key.into(),
262 network_key_pair: network_private_key,
263 network_address,
264 p2p_address,
265 p2p_listen_address,
266 metrics_address: metrics_address.to_socket_addr().unwrap(),
267 admin_interface_address: admin_interface_address.to_socket_addr().unwrap(),
268 gas_price,
269 commission_rate: DEFAULT_COMMISSION_RATE,
270 primary_address,
271 stake: ProtocolConfig::get_for_version(
275 self.protocol_version.unwrap_or(ProtocolVersion::MAX),
276 Chain::Unknown,
277 )
278 .validator_low_stake_threshold_as_option()
279 .unwrap_or(PRE_V32_VALIDATOR_LOW_STAKE_THRESHOLD),
280 name: None,
281 }
282 }
283}
284
285#[derive(Serialize, Deserialize, Default)]
286pub struct GenesisConfig {
287 pub ssfn_config_info: Option<Vec<SsfnGenesisConfig>>,
288 pub validator_config_info: Option<Vec<ValidatorGenesisConfig>>,
289 #[serde(default)]
295 pub fullnode_config_info: Option<ValidatorGenesisConfig>,
296 pub parameters: GenesisCeremonyParameters,
297 pub accounts: Vec<AccountConfig>,
298}
299
300impl Config for GenesisConfig {}
301
302impl GenesisConfig {
303 pub fn protocol_config(&self) -> ProtocolConfig {
305 ProtocolConfig::get_for_version(self.parameters.protocol_version, Chain::Unknown)
306 }
307
308 pub fn generate_accounts<R: rand::CryptoRng>(
309 &self,
310 mut rng: R,
311 ) -> Result<(Vec<AccountPrivateKey>, Vec<TokenAllocation>)> {
312 let mut addresses = Vec::new();
313 let mut allocations = Vec::new();
314
315 info!("Creating accounts and token allocations...");
316
317 let mut keys = Vec::new();
318 for account in &self.accounts {
319 let address = if let Some(address) = account.address {
320 address
321 } else {
322 let (address, key) = get_key_pair_from_rng(&mut rng);
323 keys.push(key);
324 address
325 };
326
327 addresses.push(address);
328
329 account.gas_amounts.iter().for_each(|a| {
331 allocations.push(TokenAllocation {
332 recipient_address: address,
333 amount_nanos: *a,
334 staked_with_validator: None,
335 staked_with_timelock_expiration: None,
336 });
337 });
338 }
339
340 Ok((keys, allocations))
341 }
342}
343
344fn default_socket_address() -> SocketAddr {
345 local_ip_utils::new_local_tcp_socket_for_testing()
346}
347
348fn default_stake() -> u64 {
349 ProtocolConfig::get_for_version(ProtocolVersion::MAX, Chain::Unknown)
353 .validator_low_stake_threshold_as_option()
354 .unwrap_or(PRE_V32_VALIDATOR_LOW_STAKE_THRESHOLD)
355}
356
357fn default_bls12381_key_pair() -> AuthorityKeyPair {
358 get_key_pair_from_rng(&mut UnwrapErr(SysRng)).1
359}
360
361fn default_network_private_key() -> NetworkPrivateKey {
362 get_key_pair_from_rng(&mut UnwrapErr(SysRng)).1
363}
364
365fn default_iota_key_pair() -> SimpleKeypair {
366 SimpleKeypair::from(AccountPrivateKey::random())
367}
368
369mod base64_formatted_keypair {
372 use fastcrypto::encoding::{Base64, Encoding};
373 use iota_sdk_crypto::simple::SimpleKeypair;
374 use serde::{Deserialize, Deserializer, Serializer};
375
376 pub fn serialize<S: Serializer>(kp: &SimpleKeypair, serializer: S) -> Result<S::Ok, S::Error> {
377 serializer.serialize_str(&Base64::encode(kp.to_bytes()))
378 }
379
380 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<SimpleKeypair, D::Error> {
381 use serde::de::Error;
382
383 let s = String::deserialize(d)?;
384 let bytes = Base64::decode(&s).map_err(Error::custom)?;
385 SimpleKeypair::from_bytes(&bytes).map_err(Error::custom)
386 }
387}
388
389mod base64_formatted_network_private_key {
392 use iota_sdk_crypto::ToFromBase64 as _;
393 use iota_types::crypto::NetworkPrivateKey;
394 use serde::{Deserialize, Deserializer, Serializer};
395
396 pub fn serialize<S: Serializer>(
397 private_key: &NetworkPrivateKey,
398 serializer: S,
399 ) -> Result<S::Ok, S::Error> {
400 serializer.serialize_str(&private_key.to_base64())
401 }
402
403 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<NetworkPrivateKey, D::Error> {
404 use serde::de::Error;
405
406 let s = String::deserialize(d)?;
407 NetworkPrivateKey::from_base64(&s).map_err(Error::custom)
408 }
409
410 pub mod option {
411 use super::*;
412
413 pub fn serialize<S: Serializer>(
414 private_key: &Option<NetworkPrivateKey>,
415 serializer: S,
416 ) -> Result<S::Ok, S::Error> {
417 match private_key {
418 Some(private_key) => serializer.serialize_some(&private_key.to_base64()),
419 None => serializer.serialize_none(),
420 }
421 }
422
423 pub fn deserialize<'de, D: Deserializer<'de>>(
424 d: D,
425 ) -> Result<Option<NetworkPrivateKey>, D::Error> {
426 use serde::de::Error;
427
428 Option::<String>::deserialize(d)?
429 .map(|s| NetworkPrivateKey::from_base64(&s).map_err(Error::custom))
430 .transpose()
431 }
432 }
433}
434
435#[derive(Serialize, Deserialize, Debug, Clone)]
436pub struct AccountConfig {
437 #[serde(skip_serializing_if = "Option::is_none")]
438 pub address: Option<Address>,
439 pub gas_amounts: Vec<u64>,
440}
441
442pub const DEFAULT_GAS_AMOUNT: u64 = 30_000_000_000_000_000;
443pub const DEFAULT_NUMBER_OF_AUTHORITIES: usize = 4;
444const DEFAULT_NUMBER_OF_ACCOUNT: usize = 5;
445pub const DEFAULT_NUMBER_OF_OBJECT_PER_ACCOUNT: usize = 5;
446
447impl GenesisConfig {
448 pub const BENCHMARKS_RNG_SEED: u64 = 0;
451 pub const BENCHMARKS_PORT_OFFSET: u16 = 2000;
453 const BENCHMARK_EPOCH_DURATION_MS: u64 = 60 * 60 * 1000;
455
456 pub fn for_local_testing() -> Self {
457 Self::custom_genesis(
458 DEFAULT_NUMBER_OF_ACCOUNT,
459 DEFAULT_NUMBER_OF_OBJECT_PER_ACCOUNT,
460 )
461 }
462
463 pub fn for_local_testing_with_addresses(addresses: Vec<Address>) -> Self {
464 Self::custom_genesis_with_addresses(addresses, DEFAULT_NUMBER_OF_OBJECT_PER_ACCOUNT)
465 }
466
467 pub fn custom_genesis(num_accounts: usize, num_objects_per_account: usize) -> Self {
468 let mut accounts = Vec::new();
469 for _ in 0..num_accounts {
470 accounts.push(AccountConfig {
471 address: None,
472 gas_amounts: vec![DEFAULT_GAS_AMOUNT; num_objects_per_account],
473 })
474 }
475
476 Self {
477 accounts,
478 ..Default::default()
479 }
480 }
481
482 pub fn custom_genesis_with_addresses(
483 addresses: Vec<Address>,
484 num_objects_per_account: usize,
485 ) -> Self {
486 let mut accounts = Vec::new();
487 for address in addresses {
488 accounts.push(AccountConfig {
489 address: Some(address),
490 gas_amounts: vec![DEFAULT_GAS_AMOUNT; num_objects_per_account],
491 })
492 }
493
494 Self {
495 accounts,
496 ..Default::default()
497 }
498 }
499
500 pub fn new_for_benchmarks(
514 ips: &[String],
515 epoch_duration_ms: Option<u64>,
516 chain_start_timestamp_ms: Option<u64>,
517 num_additional_gas_accounts: Option<usize>,
518 total_available_amount: u64,
519 ) -> Self {
520 assert!(
522 total_available_amount < u64::MAX,
523 "Total available amount must be less than 18446744073709551615u64"
524 );
525 let mut rng = StdRng::seed_from_u64(Self::BENCHMARKS_RNG_SEED);
528 let validator_config_info: Vec<_> = ips
529 .iter()
530 .enumerate()
531 .map(|(i, ip)| {
532 ValidatorGenesisConfigBuilder::new()
533 .with_ip(ip.to_string())
534 .with_deterministic_ports(Self::BENCHMARKS_PORT_OFFSET + 10 * i as u16)
535 .with_p2p_listen_ip_address("0.0.0.0".parse().unwrap())
536 .build(&mut rng)
537 })
538 .collect();
539
540 let num_validators = validator_config_info.len();
542 let num_accounts = num_additional_gas_accounts.unwrap_or(0) + num_validators;
543
544 let total_gas_objects = num_accounts * DEFAULT_NUMBER_OF_OBJECT_PER_ACCOUNT;
546 let gas_amount_per_object = if total_gas_objects > 0 {
547 total_available_amount / total_gas_objects as u64
548 } else {
549 0
550 };
551
552 let account_configs = Self::benchmark_gas_keys(num_accounts)
553 .iter()
554 .map(|gas_key| {
555 let gas_address = Address::from(&PublicKey::from(gas_key));
556
557 AccountConfig {
558 address: Some(gas_address),
559 gas_amounts: vec![gas_amount_per_object; DEFAULT_NUMBER_OF_OBJECT_PER_ACCOUNT],
560 }
561 })
562 .collect();
563
564 let parameters = GenesisCeremonyParameters {
567 chain_start_timestamp_ms: chain_start_timestamp_ms.unwrap_or(0),
568 epoch_duration_ms: if let Some(duration_ms) = epoch_duration_ms {
569 duration_ms
570 } else {
571 Self::BENCHMARK_EPOCH_DURATION_MS
572 },
573 ..GenesisCeremonyParameters::new()
574 };
575
576 GenesisConfig {
578 ssfn_config_info: None,
579 validator_config_info: Some(validator_config_info),
580 fullnode_config_info: None,
581 parameters,
582 accounts: account_configs,
583 }
584 }
585
586 pub fn benchmark_gas_keys(n: usize) -> Vec<SimpleKeypair> {
591 let mut rng = StdRng::seed_from_u64(Self::BENCHMARKS_RNG_SEED);
592 (0..n)
593 .map(|_| SimpleKeypair::from(AccountPrivateKey::random_with(&mut rng)))
594 .collect()
595 }
596
597 pub fn add_faucet_account(mut self) -> Self {
598 self.accounts.push(AccountConfig {
599 address: None,
600 gas_amounts: vec![DEFAULT_GAS_AMOUNT; DEFAULT_NUMBER_OF_OBJECT_PER_ACCOUNT],
601 });
602 self
603 }
604}
605
606#[cfg(test)]
607mod tests {
608 use std::net::Ipv4Addr;
609
610 use rand::{rand_core::UnwrapErr, rngs::SysRng};
611
612 use super::ValidatorGenesisConfigBuilder;
613
614 #[test]
615 fn deterministic_ports_fill_the_five_slots_of_a_validator() {
616 let config = ValidatorGenesisConfigBuilder::new()
617 .with_ip("127.0.0.1".to_owned())
618 .with_deterministic_ports(9200)
619 .with_metrics_ip_address(Ipv4Addr::LOCALHOST.into())
620 .build(&mut UnwrapErr(SysRng));
621
622 assert_eq!(
623 config.network_address.to_string(),
624 "/ip4/127.0.0.1/tcp/9200/http"
625 );
626 assert_eq!(
627 config.p2p_address.to_string(),
628 "/ip4/127.0.0.1/udp/9201/http"
629 );
630 assert_eq!(config.metrics_address.to_string(), "127.0.0.1:9202");
631 assert_eq!(
632 config.primary_address.to_string(),
633 "/ip4/127.0.0.1/udp/9203/http"
634 );
635 assert_eq!(config.admin_interface_address.to_string(), "127.0.0.1:9204");
636 }
637
638 #[test]
639 fn the_metrics_endpoint_binds_all_interfaces_unless_an_ip_is_given() {
640 let config = ValidatorGenesisConfigBuilder::new()
641 .with_ip("127.0.0.1".to_owned())
642 .with_deterministic_ports(9200)
643 .build(&mut UnwrapErr(SysRng));
644
645 assert_eq!(config.metrics_address.to_string(), "0.0.0.0:9202");
646 }
647}