-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathutils.rs
More file actions
1178 lines (1080 loc) · 37.8 KB
/
utils.rs
File metadata and controls
1178 lines (1080 loc) · 37.8 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
use std::env;
use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use base64::prelude::{BASE64_STANDARD, Engine};
use color_eyre::owo_colors::OwoColorize;
use flate2::Compression;
use flate2::read::GzDecoder;
use flate2::write::GzEncoder;
use itertools::Either;
use namada_sdk::address::{Address, ImplicitAddress};
use namada_sdk::args::DeviceTransport;
use namada_sdk::borsh::BorshSerializeExt;
use namada_sdk::chain::ChainId;
use namada_sdk::dec::Dec;
use namada_sdk::ibc::trace::ibc_token;
use namada_sdk::key::*;
use namada_sdk::signing::OfflineSignatures;
use namada_sdk::string_encoding::StringEncoded;
use namada_sdk::token;
use namada_sdk::tx::Tx;
use namada_sdk::uint::Uint;
use namada_sdk::wallet::{LoadStoreError, Wallet, alias};
use namada_vm::validate_untrusted_wasm;
use prost::bytes::Bytes;
use serde_json::json;
use sha2::{Digest, Sha256};
use tokio::sync::RwLock;
use crate::cli::args;
use crate::cli::context::wasm_dir_from_env_or;
use crate::config::genesis::chain::DeriveEstablishedAddress;
use crate::config::genesis::transactions::{
UnsignedTransactions, sign_delegation_bond_tx, sign_validator_account_tx,
};
use crate::config::genesis::{AddrOrPk, GenesisAddress};
use crate::config::global::GlobalConfig;
use crate::config::{self, TendermintMode, genesis, get_default_namada_folder};
use crate::tendermint::node::Id as TendermintNodeId;
use crate::wallet::{CliWalletUtils, pre_genesis};
use crate::{tendermint_node, wasm_loader};
pub const NET_ACCOUNTS_DIR: &str = "setup";
pub const NET_OTHER_ACCOUNTS_DIR: &str = "other";
pub const ENV_VAR_NETWORK_CONFIGS_DIR: &str = "NAMADA_NETWORK_CONFIGS_DIR";
/// Github URL prefix of released Namada network configs
pub const ENV_VAR_NETWORK_CONFIGS_SERVER: &str =
"NAMADA_NETWORK_CONFIGS_SERVER";
const DEFAULT_NETWORK_CONFIGS_SERVER: &str =
"https://github.com/heliaxdev/anoma-network-config/releases/download";
/// We do pre-genesis validator set up in this directory
pub const PRE_GENESIS_DIR: &str = "pre-genesis";
/// Configure Namada to join an existing network. The chain must be released in
/// the <https://github.com/heliaxdev/anoma-network-config> repository.
pub async fn join_network(
global_args: args::Global,
args::JoinNetwork {
chain_id,
genesis_validator,
pre_genesis_path,
allow_duplicate_ip,
add_persistent_peers,
}: args::JoinNetwork,
) {
use tokio::fs;
let base_dir = global_args.base_dir;
// If the base-dir doesn't exist yet, create it
if let Err(err) = fs::canonicalize(&base_dir).await {
if err.kind() == std::io::ErrorKind::NotFound {
fs::create_dir_all(&base_dir).await.unwrap();
}
} else {
// If the base-dir exists, check if it's already got this chain ID
if fs::canonicalize(base_dir.join(chain_id.as_str()))
.await
.is_ok()
{
eprintln!("The chain directory for {} already exists.", chain_id);
safe_exit(1);
}
}
let base_dir_full = fs::canonicalize(&base_dir).await.unwrap();
let chain_dir = base_dir_full.join(chain_id.as_str());
let validator_alias_and_dir = pre_genesis_path
.and_then(|path| {
let alias = path.components().next_back()?;
match alias {
std::path::Component::Normal(alias) => {
let alias = alias.to_string_lossy().to_string();
println!(
"Using {alias} parsed from the given \
--pre-genesis-path"
);
Some((alias, path))
}
_ => None,
}
})
.or_else(|| {
genesis_validator.as_ref().map(|alias| {
(
alias.clone(),
validator_pre_genesis_dir(&base_dir_full, alias),
)
})
});
// Pre-load the validator pre-genesis wallet and its keys to validate that
// everything is in place before downloading the network archive
let validator_alias_and_pre_genesis_wallet = validator_alias_and_dir
.as_ref()
.map(|(validator_alias, pre_genesis_dir)| {
(
alias::Alias::from(validator_alias),
pre_genesis::load(pre_genesis_dir).unwrap_or_else(|err| {
eprintln!(
"Error loading validator pre-genesis wallet {err}",
);
safe_exit(1)
}),
)
});
let release_filename = format!("{}.tar.gz", chain_id);
let net_config = if let Some(configs_dir) = network_configs_dir() {
fs::read(PathBuf::from(&configs_dir).join(release_filename))
.await
.unwrap_or_else(|err| {
panic!(
"Network config not found or couldn't be read from dir \
\"{configs_dir}\" set by an env var \
{ENV_VAR_NETWORK_CONFIGS_DIR}. Error: {err}."
)
})
} else {
let release_url = format!(
"{}/{}",
network_configs_url_prefix(&chain_id),
release_filename
);
// Read or download the release archive
println!("Downloading config release from {} ...", release_url);
let release: Bytes = match download_file(release_url).await {
Ok(contents) => contents,
Err(error) => {
eprintln!("Error downloading release: {}", error);
safe_exit(1);
}
};
release.to_vec()
};
// Decode and unpack the archive
let decoder = GzDecoder::new(&net_config[..]);
let mut archive = tar::Archive::new(decoder);
archive.unpack(&base_dir_full).unwrap();
_ = archive;
// Read the genesis files
let genesis = genesis::chain::Finalized::read_toml_files(&chain_dir)
.unwrap_or_else(|err| {
eprintln!(
"Failed to read genesis TOML files from {} with {err}.",
chain_dir.to_string_lossy()
);
safe_exit(1)
});
// Try to find validator data when using a pre-genesis validator
let validator_keys = validator_alias_and_pre_genesis_wallet.as_ref().map(
|(_alias, wallet)| {
let tendermint_node_key: common::SecretKey =
wallet.tendermint_node_key.clone();
let consensus_key: common::SecretKey = wallet.consensus_key.clone();
(tendermint_node_key, consensus_key)
},
);
let is_validator = validator_alias_and_pre_genesis_wallet.is_some();
let node_mode = if is_validator {
TendermintMode::Validator
} else {
TendermintMode::Full
};
// Derive config from genesis
let mut config = genesis.derive_config(
&chain_dir,
node_mode,
validator_keys.as_ref().map(|(sk, _)| sk.ref_to()).as_ref(),
allow_duplicate_ip,
add_persistent_peers,
);
// Try to load pre-genesis wallet, if any
let pre_genesis_wallet_path = base_dir.join(PRE_GENESIS_DIR);
let pre_genesis_wallet =
if let Ok(wallet) = crate::wallet::load(&pre_genesis_wallet_path) {
Some(wallet)
} else {
validator_alias_and_dir
.as_ref()
.and_then(|(_, path)| crate::wallet::load(path).ok())
};
// Derive wallet from genesis
let wallet = genesis.derive_wallet(
&chain_dir,
pre_genesis_wallet,
validator_alias_and_pre_genesis_wallet,
);
// Setup the node for a genesis validator, if used
if let Some((tendermint_node_key, consensus_key)) = validator_keys {
println!(
"Setting up validator keys in CometBFT. Consensus key: {}.",
consensus_key.to_public()
);
let tm_home_dir = chain_dir.join(config::COMETBFT_DIR);
// Write consensus key to tendermint home
tendermint_node::write_validator_key(&tm_home_dir, &consensus_key)
.unwrap();
// Write tendermint node key
write_tendermint_node_key(&tm_home_dir, tendermint_node_key);
// Pre-initialize tendermint validator state
tendermint_node::write_validator_state(&tm_home_dir).unwrap();
} else {
println!(
"No validator keys are being used. Make sure you didn't forget to \
specify `--genesis-validator`?"
);
}
// Move wasm-dir and update config if it's non-default
if let Some(wasm_dir) = wasm_dir_from_env_or(global_args.wasm_dir.as_ref())
{
let wasm_dir_full = chain_dir.join(wasm_dir);
tokio::fs::rename(
base_dir_full
.join(chain_id.as_str())
.join(config::DEFAULT_WASM_DIR),
&wasm_dir_full,
)
.await
.unwrap();
config.wasm_dir = wasm_dir_full;
}
// Validate the wasm artifacts checksums
validate_wasm_artifacts_aux(&chain_id, &chain_dir.join(&config.wasm_dir))
.await;
// Save the config and the wallet
config.write(&base_dir, &chain_id, true).unwrap();
crate::wallet::save(&wallet).unwrap();
println!("Successfully configured for chain ID {chain_id}");
}
async fn validate_wasm_artifacts_aux(chain_id: &ChainId, wasm_dir: &Path) {
println!("Validating wasms artifacts for chain ID {chain_id}...");
wasm_loader::validate_wasm_artifacts(wasm_dir).await;
}
pub fn validate_wasm(args::ValidateWasm { code_path }: args::ValidateWasm) {
let code = std::fs::read(code_path).unwrap();
match validate_untrusted_wasm(code) {
Ok(()) => println!("Wasm code is valid"),
Err(e) => {
eprintln!("Wasm code is invalid: {e}");
safe_exit(1)
}
}
}
/// Length of a Tendermint Node ID in bytes
const TENDERMINT_NODE_ID_LENGTH: usize = 20;
/// Derive Tendermint node ID from public key
pub fn id_from_pk(pk: &common::PublicKey) -> TendermintNodeId {
let mut bytes = [0u8; TENDERMINT_NODE_ID_LENGTH];
match pk {
common::PublicKey::Ed25519(_) => {
let _pk: ed25519::PublicKey = pk.try_to_pk().unwrap();
let digest = Sha256::digest(_pk.serialize_to_vec().as_slice());
bytes.copy_from_slice(&digest[..TENDERMINT_NODE_ID_LENGTH]);
}
common::PublicKey::Secp256k1(_) => {
let _pk: secp256k1::PublicKey = pk.try_to_pk().unwrap();
let digest = Sha256::digest(_pk.serialize_to_vec().as_slice());
bytes.copy_from_slice(&digest[..TENDERMINT_NODE_ID_LENGTH]);
}
}
TendermintNodeId::new(bytes)
}
/// Initialize a new test network from the given configuration.
pub fn init_network(
global_args: args::Global,
args::InitNetwork {
templates_path,
wasm_checksums_path,
chain_id_prefix,
genesis_time,
consensus_timeout_commit,
archive_dir,
}: args::InitNetwork,
) -> PathBuf {
let base_dir = tempfile::tempdir().unwrap();
// Load and validate the templates
let templates = genesis::templates::load_and_validate(&templates_path)
.unwrap_or_else(|| {
eprintln!("Invalid templates, aborting.");
safe_exit(1)
});
// In addition to standard templates validation, check that there is at
// least one validator account.
if !templates.transactions.has_at_least_one_validator() {
eprintln!("No validator genesis transaction found, aborting.");
safe_exit(1)
}
// Also check that at least one validator account has positive voting power.
let tm_votes_per_token = templates.parameters.pos_params.tm_votes_per_token;
if !templates
.transactions
.has_validator_with_positive_voting_power(tm_votes_per_token)
{
let min_stake = token::Amount::from_uint(
if tm_votes_per_token > Dec::from(1) {
Uint::one()
} else {
(Dec::from(1).checked_div(tm_votes_per_token).unwrap())
.ceil()
.unwrap()
.abs()
},
token::NATIVE_MAX_DECIMAL_PLACES,
)
.unwrap();
eprintln!(
"No validator with positive voting power, aborting. The minimum \
staked tokens amount required to run the network is {}, because \
there are {tm_votes_per_token} votes per NAMNAM tokens.",
min_stake.to_string_native(),
);
safe_exit(1)
}
// Finalize the genesis config to derive the chain ID
let genesis = genesis::chain::finalize(
templates,
chain_id_prefix,
genesis_time,
consensus_timeout_commit,
);
let chain_id = &genesis.metadata.chain_id;
println!("Derived chain ID: {chain_id}");
// Check that chain dir is empty
let chain_dir = base_dir.path().join(chain_id.as_str());
fs::create_dir_all(&chain_dir).unwrap();
// Write the finalized genesis config to the chain dir
genesis.write_toml_files(&chain_dir).unwrap_or_else(|err| {
eprintln!(
"Failed to write finalized genesis TOML files to {} with {err}.",
chain_dir.to_string_lossy()
);
safe_exit(1)
});
// Write the global config setting the default chain ID
let global_config = GlobalConfig::new(chain_id.clone());
global_config.write(base_dir.path()).unwrap();
// Copy the WASM checksums
let wasm_dir_full = chain_dir.join(config::DEFAULT_WASM_DIR);
fs::create_dir_all(&wasm_dir_full).unwrap();
fs::copy(
wasm_checksums_path,
wasm_dir_full.join(config::DEFAULT_WASM_CHECKSUMS_FILE),
)
.unwrap();
// Try to copy the built WASM, if they're present with the checksums
let checksums = wasm_loader::Checksums::read_checksums(&wasm_dir_full)
.unwrap_or_else(|_| safe_exit(1));
let base_wasm_path = global_args.wasm_dir.unwrap_or_else(|| {
std::env::current_dir()
.unwrap()
.join(crate::config::DEFAULT_WASM_DIR)
});
for (_, full_name) in checksums.0 {
// try to copy built file from the Namada WASM root dir
let file = base_wasm_path.join(&full_name);
if !file.exists() {
println!(
"Skipping nonexistent wasm artifact: {}",
file.to_string_lossy()
);
continue;
}
fs::copy(file, wasm_dir_full.join(&full_name)).unwrap();
}
// Create release tarball
let mut release = tar::Builder::new(Vec::new());
release
.append_dir_all(PathBuf::from(chain_id.as_str()), &chain_dir)
.unwrap();
let global_config_path = GlobalConfig::file_path(base_dir.path());
let release_global_config_path = GlobalConfig::file_path("");
release
.append_path_with_name(global_config_path, release_global_config_path)
.unwrap();
// Gzip tar release and write to file
let release_file = archive_dir
.unwrap_or_else(|| env::current_dir().unwrap())
.join(format!("{}.tar.gz", chain_id));
let compressed_file = File::create(&release_file).unwrap();
let mut encoder = GzEncoder::new(compressed_file, Compression::default());
encoder.write_all(&release.into_inner().unwrap()).unwrap();
encoder.finish().unwrap();
println!(
"Release archive created at {}",
release_file.to_string_lossy()
);
release_file
}
pub fn pk_to_tm_address(
_global_args: args::Global,
args::PkToTmAddress { public_key }: args::PkToTmAddress,
) {
let tm_addr = tm_consensus_key_raw_hash(&public_key);
println!("{tm_addr}");
}
pub fn default_base_dir(
_global_args: args::Global,
_args: args::DefaultBaseDir,
) {
println!(
"{}",
get_default_namada_folder().to_str().expect(
"expected a default namada folder to be possible to determine"
)
);
}
/// Derive and print all established addresses from the provided
/// genesis txs toml file.
pub fn derive_genesis_addresses(
global_args: args::Global,
args: args::DeriveGenesisAddresses,
) {
let maybe_pre_genesis_wallet =
try_load_pre_genesis_wallet(&global_args.base_dir)
.ok()
.map(|(wallet, _)| wallet);
let contents =
fs::read_to_string(&args.genesis_txs_path).unwrap_or_else(|err| {
eprintln!(
"Unable to read from file {}. Failed with error {err}.",
args.genesis_txs_path.to_string_lossy()
);
safe_exit(1)
});
let (estbd_txs, validator_addrs) =
toml::from_str::<UnsignedTransactions>(&contents)
.ok()
.map(|txs| {
(
txs.established_account.unwrap_or_default(),
txs.validator_account
.unwrap_or_default()
.into_iter()
.map(|acct| acct.address)
.collect::<Vec<_>>(),
)
})
.unwrap_or_else(|| {
let genesis_txs = genesis::templates::read_transactions(
&args.genesis_txs_path,
)
.unwrap();
(
genesis_txs.established_account.unwrap_or_default(),
genesis_txs
.validator_account
.unwrap_or_default()
.into_iter()
.map(|acct| acct.data.address)
.collect(),
)
});
println!("{}", "Established account txs:".underline().bold());
for tx in &estbd_txs {
println!();
println!(
"{} {}",
"Address:".bold().bright_green(),
tx.derive_address()
);
println!("{}", "Public key(s):".bold().bright_green());
for (ix, pk) in tx.public_keys.iter().enumerate() {
println!(" {}. {}", ix, pk);
let maybe_alias =
maybe_pre_genesis_wallet.as_ref().and_then(|wallet| {
let implicit_address = (&pk.raw).into();
wallet.find_alias(&implicit_address)
});
if let Some(alias) = maybe_alias {
println!("{} {alias}", "Wallet alias:".bold().bright_green());
}
}
}
if estbd_txs.is_empty() {
println!();
println!("{}", "<nil>".dimmed());
}
println!();
println!("{}", "Validator account txs:".underline().bold());
for addr in &validator_addrs {
println!();
println!("{} {}", "Address:".bold().bright_green(), addr.raw);
}
if validator_addrs.is_empty() {
println!();
println!("{}", "<nil>".dimmed());
}
}
/// Initialize a genesis established account.
/// key into a special "pre-genesis" wallet.
pub fn init_genesis_established_account(
global_args: args::Global,
args: args::InitGenesisEstablishedAccount,
) {
let (pre_genesis_wallet, _) =
load_pre_genesis_wallet_or_exit(&global_args.base_dir);
let public_keys: Vec<_> = args
.wallet_aliases
.iter()
.map(|alias| {
let pk = pre_genesis_wallet.find_public_key(alias).unwrap_or_else(
|err| {
eprintln!(
"Failed to look-up `{alias}` in the pre-genesis \
wallet: {err}",
);
safe_exit(1)
},
);
StringEncoded::new(pk)
})
.collect();
let (address, txs) = genesis::transactions::init_established_account(
args.vp,
public_keys,
args.threshold,
);
let toml_path = args.output_path;
let toml_path_str = toml_path.to_string_lossy();
let genesis_part = toml::to_string(&txs).unwrap();
fs::write(&toml_path, genesis_part).unwrap_or_else(|err| {
eprintln!(
"Couldn't write pre-genesis transactions file to {toml_path_str}. \
Failed with: {err}",
);
safe_exit(1)
});
println!(
"{}: {}\n",
"Derived established account address".bold(),
address.green(),
);
println!(
"{}: keep a note of this address, especially if you plan to use it \
for a validator account in the future!\n",
"IMPORTANT".bold().yellow()
);
println!("{}: {toml_path_str}\n", "Wrote genesis tx to".bold());
}
/// Bond to a validator at pre-genesis.
pub fn genesis_bond(global_args: args::Global, args: args::GenesisBond) {
let args::GenesisBond {
source,
validator,
bond_amount,
output: toml_path,
} = args;
let (wallet, _wallet_file) =
load_pre_genesis_wallet_or_exit(&global_args.base_dir);
let source = match source {
AddrOrPk::Address(addr) => match &addr {
Address::Established(established) => {
GenesisAddress::EstablishedAddress(established.clone())
}
Address::Implicit(internal) => {
match wallet.find_public_key_from_implicit_addr(internal) {
Ok(pk) => GenesisAddress::PublicKey(StringEncoded::new(pk)),
Err(err) => {
eprintln!(
"Couldn't find the PK associated with the given \
implicit address {addr} in the wallet: {err}"
);
safe_exit(1)
}
}
}
Address::Internal(_) => {
eprintln!("Unexpected internal address as bond source");
safe_exit(1);
}
},
AddrOrPk::PublicKey(pk) => GenesisAddress::PublicKey(pk),
};
let txs = genesis::transactions::init_bond(source, validator, bond_amount);
let toml_path_str = toml_path.to_string_lossy();
let genesis_part = toml::to_string(&txs).unwrap();
fs::write(&toml_path, genesis_part).unwrap_or_else(|err| {
eprintln!(
"Couldn't write pre-genesis transactions file to {toml_path_str}. \
Failed with: {err}",
);
safe_exit(1)
});
println!("{}: {toml_path_str}", "Wrote genesis tx to".bold());
}
/// Initialize genesis validator's address, consensus key and validator account
/// key into a special "pre-genesis" wallet.
pub fn init_genesis_validator(
global_args: args::Global,
args::InitGenesisValidator {
alias,
commission_rate,
max_commission_rate_change,
net_address,
unsafe_dont_encrypt,
key_scheme,
self_bond_amount,
email,
description,
website,
discord_handle,
avatar,
name,
tx_path,
address,
}: args::InitGenesisValidator,
) {
let contents = fs::read_to_string(&tx_path).unwrap_or_else(|err| {
eprintln!(
"Unable to read from file {}. Failed with error {err}.",
tx_path.to_string_lossy()
);
safe_exit(1)
});
let prev_txs: UnsignedTransactions = toml::from_str(&contents).unwrap();
if prev_txs
.established_account
.as_ref()
.and_then(|accts| {
accts
.iter()
.find(|acct| acct.derive_established_address() == address)
})
.is_none()
{
eprintln!(
"The provided file did not contain an established account tx with \
the provided address {}",
address
);
safe_exit(1);
}
// Validate the commission rate data
if commission_rate > Dec::one() {
eprintln!("The validator commission rate must not exceed 1.0 or 100%");
safe_exit(1)
}
if max_commission_rate_change > Dec::one() {
eprintln!(
"The validator maximum change in commission rate per epoch must \
not exceed 1.0 or 100%"
);
safe_exit(1)
}
// Validate the email
if email.is_empty() {
eprintln!("The validator email must not be an empty string");
safe_exit(1)
}
let pre_genesis_dir =
validator_pre_genesis_dir(&global_args.base_dir, &alias);
println!("Generating validator keys...");
let validator_wallet = pre_genesis::gen_and_store(
key_scheme,
unsafe_dont_encrypt,
&pre_genesis_dir,
)
.unwrap_or_else(|err| {
eprintln!(
"Unable to generate the validator pre-genesis wallet: {}",
err
);
safe_exit(1)
});
println!(
"The validator's keys were stored in the wallet at {}",
pre_genesis::validator_file_name(&pre_genesis_dir).to_string_lossy()
);
let (address, mut transactions) = genesis::transactions::init_validator(
genesis::transactions::GenesisValidatorData {
address,
commission_rate,
max_commission_rate_change,
net_address,
self_bond_amount,
email,
description,
website,
discord_handle,
avatar,
name,
},
&validator_wallet,
);
let toml_path = tx_path;
let toml_path_str = toml_path.to_string_lossy();
// append new transactions to the previous txs from the provided file.
transactions.established_account = prev_txs.established_account;
transactions
.validator_account
.as_mut()
.unwrap()
.append(&mut prev_txs.validator_account.unwrap_or_default());
transactions
.bond
.as_mut()
.unwrap()
.append(&mut prev_txs.bond.unwrap_or_default());
let genesis_part = toml::to_string(&transactions).unwrap();
fs::write(&toml_path, genesis_part).unwrap_or_else(|err| {
eprintln!(
"Couldn't write pre-genesis transactions file to {toml_path_str}. \
Failed with: {err}",
);
safe_exit(1)
});
println!(
"{}: {}",
"Validator account address".bold(),
address.green()
);
println!("{}: {toml_path_str}", "Wrote genesis tx to".bold());
}
/// Try to load a pre-genesis wallet or return nothing,
/// if it cannot be found.
pub fn try_load_pre_genesis_wallet(
base_dir: &Path,
) -> Result<(Wallet<CliWalletUtils>, PathBuf), LoadStoreError> {
let pre_genesis_dir = base_dir.join(PRE_GENESIS_DIR);
crate::wallet::load(&pre_genesis_dir).map(|wallet| {
let wallet_file = crate::wallet::wallet_file(&pre_genesis_dir);
(wallet, wallet_file)
})
}
/// Try to load a pre-genesis wallet or terminate if it cannot be found.
pub fn load_pre_genesis_wallet_or_exit(
base_dir: &Path,
) -> (Wallet<CliWalletUtils>, PathBuf) {
match try_load_pre_genesis_wallet(base_dir) {
Ok(wallet) => wallet,
Err(e) => {
eprintln!("Error loading the wallet: {e}");
safe_exit(1)
}
}
}
async fn download_file(url: impl AsRef<str>) -> reqwest::Result<Bytes> {
let url = url.as_ref();
let response = reqwest::get(url).await?;
response.error_for_status_ref()?;
let contents = response.bytes().await?;
Ok(contents)
}
fn network_configs_url_prefix(chain_id: &ChainId) -> String {
std::env::var(ENV_VAR_NETWORK_CONFIGS_SERVER).unwrap_or_else(|_| {
format!("{DEFAULT_NETWORK_CONFIGS_SERVER}/{chain_id}")
})
}
fn network_configs_dir() -> Option<String> {
std::env::var(ENV_VAR_NETWORK_CONFIGS_DIR).ok()
}
/// Write the node key into tendermint config dir.
pub fn write_tendermint_node_key(
tm_home_dir: &Path,
node_sk: common::SecretKey,
) -> common::PublicKey {
let node_pk: common::PublicKey = node_sk.ref_to();
// Convert and write the keypair into Tendermint node_key.json file.
// Tendermint requires concatenating the private-public keys for ed25519
// but does not for secp256k1.
let (node_keypair, key_str) = match node_sk {
common::SecretKey::Ed25519(sk) => (
[sk.serialize_to_vec(), sk.ref_to().serialize_to_vec()].concat(),
"Ed25519",
),
common::SecretKey::Secp256k1(sk) => {
(sk.serialize_to_vec(), "Secp256k1")
}
};
let tm_node_keypair_json = json!({
"priv_key": {
"type": format!("tendermint/PrivKey{}",key_str),
"value": BASE64_STANDARD.encode(node_keypair),
}
});
let tm_config_dir = tm_home_dir.join("config");
fs::create_dir_all(&tm_config_dir)
.expect("Couldn't create validator directory");
let node_key_path = tm_config_dir.join("node_key.json");
let file = OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(node_key_path)
.expect("Couldn't create validator node key file");
serde_json::to_writer_pretty(file, &tm_node_keypair_json)
.expect("Couldn't write validator node key file");
node_pk
}
/// The default path to a validator pre-genesis txs file.
pub fn validator_pre_genesis_txs_file(pre_genesis_path: &Path) -> PathBuf {
pre_genesis_path.join("transactions.toml")
}
/// The default validator pre-genesis directory
pub fn validator_pre_genesis_dir(base_dir: &Path, alias: &str) -> PathBuf {
base_dir.join(PRE_GENESIS_DIR).join(alias)
}
/// Validate genesis templates. Exits process if invalid.
pub fn validate_genesis_templates(
_global_args: args::Global,
args::ValidateGenesisTemplates { path }: args::ValidateGenesisTemplates,
) {
if genesis::templates::load_and_validate(&path).is_none() {
safe_exit(1)
}
}
async fn append_signature_to_signed_toml(
input_txs: &Path,
wallet: &RwLock<Wallet<CliWalletUtils>>,
use_device: bool,
device_transport: DeviceTransport,
) -> genesis::transactions::Transactions<genesis::templates::Unvalidated> {
// Parse signed txs toml to append new signatures to
let mut genesis_txs = genesis::templates::read_transactions(input_txs)
.unwrap_or_else(|_| {
eprintln!(
"Unable to parse the TOML from path: {}",
input_txs.to_string_lossy()
);
safe_exit(1)
});
// Sign bond txs and append signatures to toml file
if let Some(txs) = genesis_txs.bond {
let mut bonds = vec![];
for tx in txs {
bonds.push(
sign_delegation_bond_tx(
tx,
wallet,
&genesis_txs.established_account,
use_device,
device_transport,
)
.await,
);
}
genesis_txs.bond = Some(bonds);
}
// Sign validator txs and append signatures to toml file
if let Some(txs) = genesis_txs.validator_account {
let mut validator_accounts = vec![];
for tx in txs {
validator_accounts.push(
sign_validator_account_tx(
Either::Right(tx),
wallet,
genesis_txs.established_account.as_ref().expect(
"Established account txs required when signing \
validator account txs",
),
use_device,
device_transport,
)
.await,
);
}
genesis_txs.validator_account = Some(validator_accounts);
}
genesis_txs
}
/// Sign genesis transactions.
pub async fn sign_genesis_tx(
global_args: args::Global,
args::SignGenesisTxs {
path,
output,
validator_alias,
use_device,
device_transport,
}: args::SignGenesisTxs,
) {
let (wallet, _wallet_file) =
load_pre_genesis_wallet_or_exit(&global_args.base_dir);
let wallet_lock = RwLock::new(wallet);
let maybe_pre_genesis_wallet = validator_alias.and_then(|alias| {
let pre_genesis_dir =
validator_pre_genesis_dir(&global_args.base_dir, &alias);
pre_genesis::load(&pre_genesis_dir).ok()
});
let contents = fs::read_to_string(&path).unwrap_or_else(|err| {
eprintln!(
"Unable to read from file {}. Failed with {err}.",
path.to_string_lossy()
);
safe_exit(1)
});
// Sign a subset of the input txs (the ones whose keys we own)
let signed = if let Ok(unsigned) =
genesis::transactions::parse_unsigned(&contents)
{
let signed = genesis::transactions::sign_txs(
unsigned,
&wallet_lock,
maybe_pre_genesis_wallet.as_ref(),
use_device,
device_transport,
)
.await;
if let Some(output_path) = output.as_ref() {
// If the output path contains existing signed txs, we append
// the newly signed txs to the file
#[allow(clippy::disallowed_methods)]
let mut prev_txs =
genesis::templates::read_transactions(output_path)
.unwrap_or_default();
prev_txs.merge(signed);