-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreate_cluster.rs
More file actions
1526 lines (1294 loc) · 47.1 KB
/
create_cluster.rs
File metadata and controls
1526 lines (1294 loc) · 47.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Create cluster command implementation.
//!
//! This module implements the `pluto create cluster` command, which creates a
//! local distributed validator cluster configuration including validator keys,
//! threshold BLS key shares, p2p private keys, cluster-lock files, and deposit
//! data files.
use std::{
collections::HashMap,
io::Write,
os::unix::fs::PermissionsExt as _,
path::{Path, PathBuf},
};
use chrono::Utc;
use k256::SecretKey;
use pluto_cluster::{
definition::Definition,
deposit::DepositData,
distvalidator::DistValidator,
helpers,
lock::Lock,
operator::Operator,
registration::{BuilderRegistration, Registration},
};
use pluto_core::consensus::protocols;
use pluto_crypto::{
blst_impl::BlstImpl,
tbls::Tbls,
types::{PrivateKey, PublicKey},
};
use pluto_eth1wrap as eth1wrap;
use pluto_app::{obolapi, utils as app_utils};
use pluto_eth2util::{
self as eth2util,
deposit::{self, Gwei},
enr::Record,
keymanager,
keystore::{self, CONFIRM_INSECURE_KEYS, Keystore},
network, registration as eth2util_registration,
};
use pluto_p2p::k1 as p2p_k1;
use pluto_ssz::to_0x_hex;
use rand::rngs::OsRng;
use tracing::{debug, info, warn};
use crate::{
commands::create_dkg,
error::{
CliError, CreateClusterError, InvalidNetworkConfigError, Result as CliResult,
ThresholdError,
},
};
/// Minimum number of nodes required in a cluster.
pub const MIN_NODES: u64 = 3;
/// Minimum threshold value.
pub const MIN_THRESHOLD: u64 = 2;
/// HTTP scheme.
const HTTP_SCHEME: &str = "http";
/// HTTPS scheme.
const HTTPS_SCHEME: &str = "https";
type Result<T> = std::result::Result<T, CreateClusterError>;
/// Ethereum network options.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, clap::ValueEnum)]
#[value(rename_all = "lowercase")]
pub enum Network {
/// Ethereum mainnet
#[default]
Mainnet,
/// Prater testnet (alias for Goerli)
Prater,
/// Goerli testnet
Goerli,
/// Sepolia testnet
Sepolia,
/// Hoodi testnet
Hoodi,
/// Holesky testnet
Holesky,
/// Gnosis chain
Gnosis,
/// Chiado testnet
Chiado,
}
impl Network {
/// Returns the canonical network name.
pub fn as_str(&self) -> &'static str {
match self {
Network::Mainnet => "mainnet",
Network::Goerli | Network::Prater => "goerli",
Network::Sepolia => "sepolia",
Network::Hoodi => "hoodi",
Network::Holesky => "holesky",
Network::Gnosis => "gnosis",
Network::Chiado => "chiado",
}
}
}
impl TryFrom<&str> for Network {
type Error = InvalidNetworkConfigError;
fn try_from(value: &str) -> std::result::Result<Self, Self::Error> {
match value {
"mainnet" => Ok(Network::Mainnet),
"prater" => Ok(Network::Prater),
"goerli" => Ok(Network::Goerli),
"sepolia" => Ok(Network::Sepolia),
"hoodi" => Ok(Network::Hoodi),
"holesky" => Ok(Network::Holesky),
"gnosis" => Ok(Network::Gnosis),
"chiado" => Ok(Network::Chiado),
_ => Err(InvalidNetworkConfigError::InvalidNetworkSpecified {
network: value.to_string(),
}),
}
}
}
impl std::fmt::Display for Network {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.as_str())
}
}
/// Custom testnet configuration.
#[derive(Debug, Clone, Default, clap::Args)]
pub struct TestnetConfig {
/// Chain ID of the custom test network
#[arg(
long = "testnet-chain-id",
help = "Chain ID of the custom test network."
)]
pub chain_id: Option<u64>,
/// Genesis fork version of the custom test network (in hex)
#[arg(
long = "testnet-fork-version",
help = "Genesis fork version of the custom test network (in hex)."
)]
pub fork_version: Option<String>,
/// Genesis timestamp of the custom test network
#[arg(
long = "testnet-genesis-timestamp",
help = "Genesis timestamp of the custom test network."
)]
pub genesis_timestamp: Option<u64>,
/// Name of the custom test network
#[arg(long = "testnet-name", help = "Name of the custom test network.")]
pub testnet_name: Option<String>,
}
impl TestnetConfig {
pub fn is_empty(&self) -> bool {
self.testnet_name.is_none()
&& self.fork_version.is_none()
&& self.chain_id.is_none()
&& self.genesis_timestamp.is_none()
}
}
/// Arguments for the create cluster command
#[derive(clap::Args)]
pub struct CreateClusterArgs {
/// The target folder to create the cluster in.
#[arg(
long = "cluster-dir",
default_value = "./",
help = "The target folder to create the cluster in."
)]
pub cluster_dir: PathBuf,
/// Enable compounding rewards for validators
#[arg(
long = "compounding",
help = "Enable compounding rewards for validators by using 0x02 withdrawal credentials."
)]
pub compounding: bool,
/// Preferred consensus protocol name for the cluster
#[arg(
long = "consensus-protocol",
help = "Preferred consensus protocol name for the cluster. Selected automatically when not specified."
)]
pub consensus_protocol: Option<String>,
/// Path to a cluster definition file or HTTP URL
#[arg(
long = "definition-file",
help = "Optional path to a cluster definition file or an HTTP URL. This overrides all other configuration flags."
)]
pub definition_file: Option<String>,
/// List of partial deposit amounts (integers) in ETH
#[arg(
long = "deposit-amounts",
value_delimiter = ',',
help = "List of partial deposit amounts (integers) in ETH. Values must sum up to at least 32ETH."
)]
pub deposit_amounts: Vec<u64>,
/// The address of the execution engine JSON-RPC API
#[arg(
long = "execution-client-rpc-endpoint",
help = "The address of the execution engine JSON-RPC API."
)]
pub execution_engine_addr: Option<String>,
/// Comma separated list of fee recipient addresses
#[arg(
long = "fee-recipient-addresses",
value_delimiter = ',',
help = "Comma separated list of Ethereum addresses of the fee recipient for each validator. Either provide a single fee recipient address or fee recipient addresses for each validator."
)]
pub fee_recipient_addrs: Vec<String>,
/// Generates insecure keystore files (testing only)
#[arg(
long = "insecure-keys",
help = "Generates insecure keystore files. This should never be used. It is not supported on mainnet."
)]
pub insecure_keys: bool,
/// Comma separated list of keymanager URLs
#[arg(
long = "keymanager-addresses",
value_delimiter = ',',
help = "Comma separated list of keymanager URLs to import validator key shares to. Note that multiple addresses are required, one for each node in the cluster."
)]
pub keymanager_addrs: Vec<String>,
/// Authentication bearer tokens for keymanager URLs
#[arg(
long = "keymanager-auth-tokens",
value_delimiter = ',',
help = "Authentication bearer tokens to interact with the keymanager URLs. Don't include the \"Bearer\" symbol, only include the api-token."
)]
pub keymanager_auth_tokens: Vec<String>,
/// The cluster name
#[arg(long = "name")]
pub name: Option<String>,
/// Ethereum network to create validators for
#[arg(long = "network", help = "Ethereum network to create validators for.")]
pub network: Option<Network>,
/// The number of charon nodes in the cluster
#[arg(
long = "nodes",
default_value = "0",
help = "The number of charon nodes in the cluster. Minimum is 3."
)]
pub nodes: u64,
/// The number of distributed validators needed in the cluster
#[arg(
long = "num-validators",
default_value = "0",
help = "The number of distributed validators needed in the cluster."
)]
pub num_validators: u64,
/// Publish lock file to obol-api
#[arg(long = "publish", help = "Publish lock file to obol-api.")]
pub publish: bool,
/// The URL to publish the lock file to
#[arg(
long = "publish-address",
default_value = "https://api.obol.tech/v1",
help = "The URL to publish the lock file to."
)]
pub publish_address: String,
/// Split an existing validator's private key
#[arg(
long = "split-existing-keys",
help = "Split an existing validator's private key into a set of distributed validator private key shares. Does not re-create deposit data for this key."
)]
pub split_keys: bool,
/// Directory containing keys to split
#[arg(
long = "split-keys-dir",
help = "Directory containing keys to split. Expects keys in keystore-*.json and passwords in keystore-*.txt. Requires --split-existing-keys."
)]
pub split_keys_dir: Option<PathBuf>,
/// Preferred target gas limit for transactions
#[arg(
long = "target-gas-limit",
default_value = "60000000",
help = "Preferred target gas limit for transactions."
)]
pub target_gas_limit: u64,
/// Custom testnet configuration
#[command(flatten)]
pub testnet_config: TestnetConfig,
/// Optional override of threshold
#[arg(
long = "threshold",
help = "Optional override of threshold required for signature reconstruction. Defaults to ceil(n*2/3) if zero. Warning, non-default values decrease security."
)]
pub threshold: Option<u64>,
/// Comma separated list of withdrawal addresses
#[arg(
long = "withdrawal-addresses",
value_delimiter = ',',
help = "Comma separated list of Ethereum addresses to receive the returned stake and accrued rewards for each validator. Either provide a single withdrawal address or withdrawal addresses for each validator."
)]
pub withdrawal_addrs: Vec<String>,
/// Create a tar archive compressed with gzip
#[arg(
long = "zipped",
help = "Create a tar archive compressed with gzip of the cluster directory after creation."
)]
pub zipped: bool,
}
impl From<TestnetConfig> for network::Network {
fn from(config: TestnetConfig) -> Self {
network::Network {
chain_id: config.chain_id.unwrap_or(0),
name: Box::leak(
config
.testnet_name
.as_ref()
.unwrap_or(&String::new())
.clone()
.into_boxed_str(),
),
genesis_fork_version_hex: Box::leak(
config
.fork_version
.as_ref()
.unwrap_or(&String::new())
.clone()
.into_boxed_str(),
),
genesis_timestamp: config.genesis_timestamp.unwrap_or(0),
capella_hard_fork: "",
}
}
}
fn init_tracing() -> CliResult<()> {
match pluto_tracing::init(&pluto_tracing::TracingConfig::default()) {
Ok(_) | Err(pluto_tracing::init::Error::InitError(_)) => Ok(()),
Err(err) => Err(CliError::from(err)),
}
}
fn validate_threshold(args: &CreateClusterArgs) -> Result<()> {
let Some(threshold) = args.threshold else {
return Ok(());
};
if threshold < MIN_THRESHOLD {
return Err(ThresholdError::ThresholdTooLow { threshold }.into());
}
let number_of_nodes = args.nodes;
if threshold > number_of_nodes {
return Err(ThresholdError::ThresholdTooHigh {
threshold,
number_of_nodes,
}
.into());
}
Ok(())
}
/// Runs the create cluster command
pub async fn run(w: &mut dyn Write, mut args: CreateClusterArgs) -> CliResult<()> {
init_tracing()?;
let mut definition_input = None;
if let Some(definition_file) = args.definition_file.as_ref() {
let Some(addr) = args.execution_engine_addr.as_ref() else {
return Err(CreateClusterError::MissingExecutionEngineAddress.into());
};
let eth1cl = eth1wrap::EthClient::new(addr.clone()).await?;
let def = load_definition(definition_file, ð1cl).await?;
args.nodes = u64::try_from(def.operators.len()).expect("operators length is too large");
args.threshold = Some(def.threshold);
let network_name = eth2util::network::fork_version_to_network(&def.fork_version)?;
args.network = Some(
Network::try_from(network_name.as_str())
.map_err(CreateClusterError::InvalidNetworkConfig)?,
);
definition_input = Some((def, eth1cl));
}
validate_threshold(&args)?;
validate_create_config(&args)?;
let mut secrets: Vec<PrivateKey> = Vec::new();
// If we're splitting keys, read them from `split_keys_dir` and set
// args.num_validators to the amount of secrets we read.
// If `split_keys` wasn't set, we wouldn't have reached this part of code
// because `validate_create_config()` would've already errored.
if args.split_keys {
let use_sequence_keys = args.withdrawal_addrs.len() > 1;
let Some(split_keys_dir) = &args.split_keys_dir else {
return Err(CreateClusterError::MissingSplitKeysDir.into());
};
secrets = get_keys(&split_keys_dir, use_sequence_keys).await?;
debug!(
"Read {} secrets from {}",
secrets.len(),
split_keys_dir.display()
);
// Needed if --split-existing-keys is called without a definition file.
// It's safe to unwrap here because we know the length is less than u64::MAX.
args.num_validators = u64::try_from(secrets.len()).expect("secrets length is too large");
}
// Get a cluster definition, either from a definition file or from the config.
let (mut def, mut deposit_amounts) = if let Some((def, eth1cl)) = definition_input {
validate_definition(&def, args.insecure_keys, &args.keymanager_addrs, ð1cl).await?;
let deposit_amounts = def.deposit_amounts.clone();
(def, deposit_amounts)
} else {
// Create new definition from cluster config
let def = new_def_from_config(&args)?;
let deposit_amounts = deposit::eths_to_gweis(&args.deposit_amounts);
(def, deposit_amounts)
};
if deposit_amounts.is_empty() {
deposit_amounts = deposit::default_deposit_amounts(args.compounding);
}
if secrets.is_empty() {
// This is the case in which split-keys is undefined and user passed validator
// amount on CLI
secrets = generate_keys(def.num_validators)?;
}
let num_validators_usize =
usize::try_from(def.num_validators).map_err(|_| CreateClusterError::ValueExceedsUsize {
value: def.num_validators,
})?;
if secrets.len() != num_validators_usize {
return Err(CreateClusterError::KeyCountMismatch {
disk_keys: secrets.len(),
definition_keys: def.num_validators,
}
.into());
}
let num_nodes = u64::try_from(def.operators.len()).expect("operators length is too large");
// Generate threshold bls key shares
let (pub_keys, share_sets) = get_tss_shares(&secrets, def.threshold, num_nodes)?;
// Create cluster directory at the given location
tokio::fs::create_dir_all(&args.cluster_dir).await?;
// Set directory permissions to 0o755
let permissions = std::fs::Permissions::from_mode(0o755);
tokio::fs::set_permissions(&args.cluster_dir, permissions).await?;
// Create operators and their enr node keys
let (ops, node_keys) = get_operators(num_nodes, &args.cluster_dir)?;
def.operators = ops;
let keys_to_disk = args.keymanager_addrs.is_empty();
if keys_to_disk {
write_keys_to_disk(
num_nodes,
&args.cluster_dir,
args.insecure_keys,
&share_sets,
)
.await?;
} else {
write_keys_to_keymanager(&args, num_nodes, &share_sets).await?;
}
let network = eth2util::network::fork_version_to_network(&def.fork_version)?;
let deposit_datas = create_deposit_datas(
&def.withdrawal_addresses(),
&network,
&secrets,
&deposit_amounts,
def.compounding,
)?;
let eth2util_deposit_datas = deposit_datas
.iter()
.map(|dd| cluster_deposit_data_to_eth2util_deposit_data(dd))
.collect::<Vec<_>>();
// Write deposit-data files
eth2util::deposit::write_cluster_deposit_data_files(
ð2util_deposit_datas,
network,
&args.cluster_dir,
usize::try_from(num_nodes).expect("num_nodes should fit in usize"),
)
.await?;
let val_regs = create_validator_registrations(
&def.fee_recipient_addresses(),
&secrets,
&def.fork_version,
args.split_keys,
args.target_gas_limit,
)?;
let vals = get_validators(&pub_keys, &share_sets, &deposit_datas, val_regs)?;
let mut lock = Lock {
definition: def,
distributed_validators: vals,
..Default::default()
};
lock.set_lock_hash().map_err(CreateClusterError::from)?;
lock.signature_aggregate = agg_sign(&share_sets, &lock.lock_hash)?;
for op_key in &node_keys {
let node_sig =
pluto_k1util::sign(op_key, &lock.lock_hash).map_err(CreateClusterError::K1UtilError)?;
lock.node_signatures.push(node_sig.to_vec());
}
let mut dashboard_url = String::new();
if args.publish {
match write_lock_to_api(&args.publish_address, &lock).await {
Ok(url) => dashboard_url = url,
Err(err) => {
warn!(error = %err, "Failed to publish lock file to Obol API");
}
}
}
write_lock(&lock, &args.cluster_dir, num_nodes).await?;
if args.zipped {
app_utils::bundle_output(&args.cluster_dir, "cluster.tar.gz")
.map_err(CreateClusterError::BundleOutputError)?;
}
if args.split_keys {
write_split_keys_warning(w).map_err(CreateClusterError::IoError)?;
}
write_output(
w,
args.split_keys,
&args.cluster_dir,
num_nodes,
keys_to_disk,
args.zipped,
)
.map_err(CreateClusterError::IoError)?;
if !dashboard_url.is_empty() {
info!(
"You can find your newly-created cluster dashboard here: {}",
dashboard_url
);
}
Ok(())
}
async fn write_lock_to_api(publish_addr: &str, lock: &Lock) -> Result<String> {
let client = obolapi::Client::new(publish_addr, obolapi::ClientOptions::default())
.map_err(CreateClusterError::ObolApiError)?;
match client.publish_lock(lock.clone()).await {
Ok(()) => {
info!(addr = publish_addr, "Published lock file");
match client.launchpad_url_for_lock(lock) {
Ok(url) => Ok(url),
Err(err) => Err(CreateClusterError::ObolApiError(err)),
}
}
Err(err) => Err(CreateClusterError::ObolApiError(err)),
}
}
fn create_validator_registrations(
fee_recipient_addresses: &[String],
secrets: &[PrivateKey],
fork_version: &[u8],
split_keys: bool,
target_gas_limit: u64,
) -> Result<Vec<BuilderRegistration>> {
if fee_recipient_addresses.len() != secrets.len() {
return Err(CreateClusterError::InsufficientFeeAddresses {
expected: secrets.len(),
got: fee_recipient_addresses.len(),
});
}
let effective_gas_limit = if target_gas_limit == 0 {
warn!(
default_gas_limit = eth2util_registration::DEFAULT_GAS_LIMIT,
"Custom target gas limit not supported, setting to default"
);
eth2util_registration::DEFAULT_GAS_LIMIT
} else {
target_gas_limit
};
let fork_version: [u8; 4] = fork_version
.try_into()
.map_err(|_| CreateClusterError::InvalidForkVersionLength)?;
let tbls = BlstImpl;
let mut registrations = Vec::with_capacity(secrets.len());
for (secret, fee_address) in secrets.iter().zip(fee_recipient_addresses.iter()) {
let timestamp = if split_keys {
Utc::now()
} else {
eth2util::network::fork_version_to_genesis_time(&fork_version)?
};
let pk = tbls.secret_to_public_key(secret)?;
let unsigned_reg = eth2util_registration::new_message(
pk,
fee_address,
effective_gas_limit,
u64::try_from(timestamp.timestamp()).expect("timestamp should fit in u64"),
)?;
let sig_root = eth2util_registration::get_message_signing_root(&unsigned_reg, fork_version);
let sig = tbls.sign(secret, &sig_root)?;
registrations.push(BuilderRegistration {
message: Registration {
fee_recipient: unsigned_reg.fee_recipient,
gas_limit: unsigned_reg.gas_limit,
timestamp,
pub_key: unsigned_reg.pubkey,
},
signature: sig,
});
}
Ok(registrations)
}
fn cluster_deposit_data_to_eth2util_deposit_data(
deposit_datas: &[DepositData],
) -> Vec<eth2util::deposit::DepositData> {
deposit_datas
.iter()
.map(|dd| eth2util::deposit::DepositData {
pubkey: dd.pub_key,
withdrawal_credentials: dd.withdrawal_credentials,
amount: dd.amount,
signature: dd.signature,
})
.collect()
}
async fn write_keys_to_disk(
num_nodes: u64,
cluster_dir: impl AsRef<Path>,
insecure_keys: bool,
share_sets: &[Vec<PrivateKey>],
) -> Result<()> {
for i in 0..num_nodes {
let i_usize = usize::try_from(i).expect("node index should fit in usize on all platforms");
let mut secrets: Vec<PrivateKey> = Vec::new();
for shares in share_sets {
secrets.push(shares[i_usize]);
}
let keys_dir = helpers::create_validator_keys_dir(node_dir(cluster_dir.as_ref(), i))
.await
.map_err(CreateClusterError::IoError)?;
if insecure_keys {
keystore::store_keys_insecure(&secrets, &keys_dir, &CONFIRM_INSECURE_KEYS).await?;
} else {
keystore::store_keys(&secrets, &keys_dir).await?;
}
}
Ok(())
}
fn random_hex64() -> Result<String> {
let mut bytes = [0u8; 32];
rand::RngCore::fill_bytes(&mut OsRng, &mut bytes);
Ok(hex::encode(bytes))
}
async fn write_keys_to_keymanager(
args: &CreateClusterArgs,
num_nodes: u64,
share_sets: &[Vec<PrivateKey>],
) -> Result<()> {
// Create and verify all keymanager clients first.
let mut clients: Vec<keymanager::Client> = Vec::new();
for i in 0..num_nodes {
let i_usize = usize::try_from(i).expect("node index should fit in usize on all platforms");
let cl = keymanager::Client::new(
&args.keymanager_addrs[i_usize],
&args.keymanager_auth_tokens[i_usize],
)?;
cl.verify_connection().await?;
clients.push(cl);
}
// For each node, build keystores from this node's share of each validator,
// then import them into that node's keymanager.
for i in 0..num_nodes {
let i_usize = usize::try_from(i).expect("node index should fit in usize on all platforms");
let mut keystores: Vec<Keystore> = Vec::new();
let mut passwords: Vec<String> = Vec::new();
// share_sets[validator_idx][node_idx]
for shares in share_sets {
let password = random_hex64()?;
let pbkdf2_c = if args.insecure_keys {
// Match Charon's `keystorev4.WithCost(..., 4)` => 2^4 iterations.
Some(16u32)
} else {
None
};
let store = keystore::encrypt(&shares[i_usize], &password, pbkdf2_c, &mut OsRng)?;
passwords.push(password);
keystores.push(store);
}
clients[i_usize]
.import_keystores(&keystores, &passwords)
.await
.inspect_err(|_| {
tracing::error!(
addr = %args.keymanager_addrs[i_usize],
"Failed to import keys",
);
})?;
info!(
node = format!("node{}", i),
addr = %args.keymanager_addrs[i_usize],
"Imported key shares to keymanager",
);
}
info!("Imported all validator keys to respective keymanagers");
Ok(())
}
fn create_deposit_datas(
withdrawal_addresses: &[String],
network: impl AsRef<str>,
secrets: &[PrivateKey],
deposit_amounts: &[Gwei],
compounding: bool,
) -> Result<Vec<Vec<DepositData>>> {
if secrets.len() != withdrawal_addresses.len() {
return Err(CreateClusterError::InsufficientWithdrawalAddresses);
}
if deposit_amounts.is_empty() {
return Err(CreateClusterError::EmptyDepositAmounts);
}
let deduped = deposit::dedup_amounts(deposit_amounts);
sign_deposit_datas(
secrets,
withdrawal_addresses,
network.as_ref(),
&deduped,
compounding,
)
}
fn sign_deposit_datas(
secrets: &[PrivateKey],
withdrawal_addresses: &[String],
network: &str,
deposit_amounts: &[Gwei],
compounding: bool,
) -> Result<Vec<Vec<DepositData>>> {
if secrets.len() != withdrawal_addresses.len() {
return Err(CreateClusterError::InsufficientWithdrawalAddresses);
}
if deposit_amounts.is_empty() {
return Err(CreateClusterError::EmptyDepositAmounts);
}
let tbls = BlstImpl;
let mut dd = Vec::new();
for &deposit_amount in deposit_amounts {
let mut datas = Vec::new();
for (secret, withdrawal_addr) in secrets.iter().zip(withdrawal_addresses.iter()) {
let withdrawal_addr = eth2util::helpers::checksum_address(withdrawal_addr)?;
let pk = tbls.secret_to_public_key(secret)?;
let msg = deposit::new_message(pk, &withdrawal_addr, deposit_amount, compounding)?;
let sig_root = deposit::get_message_signing_root(&msg, network)?;
let sig = tbls.sign(secret, &sig_root)?;
datas.push(DepositData {
pub_key: msg.pubkey,
withdrawal_credentials: msg.withdrawal_credentials,
amount: msg.amount,
signature: sig,
});
}
dd.push(datas);
}
Ok(dd)
}
fn generate_keys(num_validators: u64) -> Result<Vec<PrivateKey>> {
let tbls = BlstImpl;
let mut secrets = Vec::new();
for _ in 0..num_validators {
let secret = tbls.generate_secret_key(OsRng)?;
secrets.push(secret);
}
Ok(secrets)
}
fn get_operators(
num_nodes: u64,
cluster_dir: impl AsRef<Path>,
) -> Result<(Vec<Operator>, Vec<SecretKey>)> {
let mut ops = Vec::new();
let mut node_keys = Vec::new();
for i in 0..num_nodes {
let (record, identity_key) = new_peer(&cluster_dir, i)?;
ops.push(Operator {
enr: record.to_string(),
..Default::default()
});
node_keys.push(identity_key);
}
Ok((ops, node_keys))
}
fn new_peer(cluster_dir: impl AsRef<Path>, peer_idx: u64) -> Result<(Record, SecretKey)> {
let dir = node_dir(cluster_dir.as_ref(), peer_idx);
let p2p_key = p2p_k1::new_saved_priv_key(&dir)?;
let record = Record::new(&p2p_key, Vec::new())?;
Ok((record, p2p_key))
}
async fn get_keys(
split_keys_dir: impl AsRef<Path>,
use_sequence_keys: bool,
) -> Result<Vec<PrivateKey>> {
if use_sequence_keys {
let files = keystore::load_files_unordered(split_keys_dir).await?;
Ok(files.sequenced_keys()?)
} else {
let files = keystore::load_files_recursively(split_keys_dir).await?;
Ok(files.keys())
}
}
/// Creates a new cluster definition from the provided configuration.
fn new_def_from_config(args: &CreateClusterArgs) -> Result<Definition> {
let num_validators = args.num_validators;
if num_validators == 0 {
return Err(CreateClusterError::MissingNumValidatorsOrDefinitionFile);
}
let (fee_recipient_addrs, withdrawal_addrs) = validate_addresses(
num_validators,
&args.fee_recipient_addrs,
&args.withdrawal_addrs,
)?;
let fork_version = if let Some(network) = args.network {
eth2util::network::network_to_fork_version(network.as_str())?
} else if let Some(ref fork_version_hex) = args.testnet_config.fork_version {
fork_version_hex.clone()
} else {
return Err(CreateClusterError::InvalidNetworkConfig(
InvalidNetworkConfigError::MissingNetworkFlagAndNoTestnetConfigFlag,
));
};
let num_nodes = args.nodes;
if num_nodes == 0 {
return Err(CreateClusterError::MissingNodesOrDefinitionFile);
}
let operators = vec![
pluto_cluster::operator::Operator::default();
usize::try_from(num_nodes).expect("num_nodes should fit in usize")
];
let threshold = safe_threshold(num_nodes, args.threshold);
let name = args.name.clone().unwrap_or_default();
let consensus_protocol = args.consensus_protocol.clone().unwrap_or_default();
let def = pluto_cluster::definition::Definition::new(
name,
num_validators,
threshold,
fee_recipient_addrs,
withdrawal_addrs,
fork_version,
pluto_cluster::definition::Creator::default(),
operators,
args.deposit_amounts.clone(),
consensus_protocol,
args.target_gas_limit,
args.compounding,
vec![],
)?;
Ok(def)
}
fn get_tss_shares(
secrets: &[PrivateKey],
threshold: u64,
num_nodes: u64,
) -> Result<(Vec<PublicKey>, Vec<Vec<PrivateKey>>)> {
let tbls = BlstImpl;
let mut dvs = Vec::new();
let mut splits = Vec::new();
let num_nodes = u8::try_from(num_nodes)
.map_err(|_| CreateClusterError::ValueExceedsU8 { value: num_nodes })?;
let threshold = u8::try_from(threshold)
.map_err(|_| CreateClusterError::ValueExceedsU8 { value: threshold })?;
for secret in secrets {
let shares = tbls.threshold_split(secret, num_nodes, threshold)?;
// Preserve order when transforming from map of private shares to array of
// private keys
let mut entries: Vec<_> = shares.into_iter().collect();
entries.sort_by_key(|(idx, _)| *idx);
let secret_set = entries.into_iter().map(|(_, share)| share).collect();
splits.push(secret_set);
let pubkey = tbls.secret_to_public_key(secret)?;
dvs.push(pubkey);
}
Ok((dvs, splits))
}
async fn validate_definition(
def: &Definition,
insecure_keys: bool,
keymanager_addrs: &[String],
eth1cl: ð1wrap::EthClient,
) -> Result<()> {
if def.num_validators == 0 {