-
Notifications
You must be signed in to change notification settings - Fork 981
/
tx.rs
1699 lines (1540 loc) · 55.6 KB
/
tx.rs
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::fs::File;
use std::io::Write;
use borsh::BorshDeserialize;
use borsh_ext::BorshSerializeExt;
use ledger_namada_rs::{BIP44Path, KeyResponse, NamadaApp, NamadaKeys};
use masp_primitives::sapling::redjubjub::PrivateKey;
use masp_primitives::sapling::{redjubjub, ProofGenerationKey};
use masp_primitives::transaction::components::sapling::builder::{
BuildParams, ConvertBuildParams, OutputBuildParams, RngBuildParams,
SpendBuildParams, StoredBuildParams,
};
use masp_primitives::transaction::components::sapling::fees::InputView;
use masp_primitives::zip32::{ExtendedFullViewingKey, ExtendedKey};
use namada_sdk::address::{Address, ImplicitAddress};
use namada_sdk::args::TxBecomeValidator;
use namada_sdk::collections::{HashMap, HashSet};
use namada_sdk::governance::cli::onchain::{
DefaultProposal, PgfFundingProposal, PgfStewardProposal,
};
use namada_sdk::ibc::convert_masp_tx_to_ibc_memo;
use namada_sdk::io::Io;
use namada_sdk::key::*;
use namada_sdk::masp::ExtendedViewingKey;
use namada_sdk::rpc::{InnerTxResult, TxBroadcastData, TxResponse};
use namada_sdk::state::EPOCH_SWITCH_BLOCKS_DELAY;
use namada_sdk::tx::data::compute_inner_tx_hash;
use namada_sdk::tx::{CompressedAuthorization, Section, Signer, Tx};
use namada_sdk::wallet::alias::{validator_address, validator_consensus_key};
use namada_sdk::wallet::{Wallet, WalletIo};
use namada_sdk::{display_line, edisplay_line, error, signing, tx, Namada};
use rand::rngs::OsRng;
use tokio::sync::RwLock;
use super::rpc;
use crate::cli::{args, safe_exit};
use crate::client::tx::signing::{default_sign, SigningTxData};
use crate::client::tx::tx::ProcessTxResponse;
use crate::config::TendermintMode;
use crate::masp_primitives::transaction::components::sapling;
use crate::tendermint_node;
use crate::tendermint_rpc::endpoint::broadcast::tx_sync::Response;
use crate::wallet::{
gen_validator_keys, read_and_confirm_encryption_password, WalletTransport,
};
/// Wrapper around `signing::aux_signing_data` that stores the optional
/// disposable address to the wallet
pub async fn aux_signing_data(
context: &impl Namada,
args: &args::Tx,
owner: Option<Address>,
default_signer: Option<Address>,
disposable_signing_key: bool,
) -> Result<signing::SigningTxData, error::Error> {
let signing_data = signing::aux_signing_data(
context,
args,
owner,
default_signer,
vec![],
disposable_signing_key,
)
.await?;
if disposable_signing_key {
if !(args.dry_run || args.dry_run_wrapper) {
// Store the generated signing key to wallet in case of need
context.wallet().await.save().map_err(|_| {
error::Error::Other(
"Failed to save disposable address to wallet".to_string(),
)
})?;
} else {
display_line!(
context.io(),
"Transaction dry run. The disposable address will not be \
saved to wallet."
)
}
}
Ok(signing_data)
}
pub async fn with_hardware_wallet<'a, U, T>(
mut tx: Tx,
pubkey: common::PublicKey,
parts: HashSet<signing::Signable>,
(wallet, app): (&RwLock<Wallet<U>>, &NamadaApp<T>),
) -> Result<Tx, error::Error>
where
U: WalletIo + Clone,
T: ledger_transport::Exchange + Send + Sync,
<T as ledger_transport::Exchange>::Error: std::error::Error,
{
// Obtain derivation path
let path = wallet
.read()
.await
.find_path_by_pkh(&(&pubkey).into())
.map_err(|_| {
error::Error::Other(
"Unable to find derivation path for key".to_string(),
)
})?;
let path = BIP44Path {
path: path.to_string(),
};
// Now check that the public key at this path in the Ledger
// matches
let response_pubkey = app
.get_address_and_pubkey(&path, false)
.await
.map_err(|err| error::Error::Other(err.to_string()))?;
let response_pubkey =
common::PublicKey::try_from_slice(&response_pubkey.public_key)
.map_err(|err| {
error::Error::Other(format!(
"unable to decode public key from hardware wallet: {}",
err
))
})?;
if response_pubkey != pubkey {
return Err(error::Error::Other(format!(
"Unrecognized public key fetched from Ledger: {}. Expected {}.",
response_pubkey, pubkey,
)));
}
// Get the Ledger to sign using our obtained derivation path
let response = app
.sign(&path, &tx.serialize_to_vec())
.await
.map_err(|err| error::Error::Other(err.to_string()))?;
// Sign the raw header if that is requested
if parts.contains(&signing::Signable::RawHeader) {
let pubkey = common::PublicKey::try_from_slice(&response.pubkey)
.expect("unable to parse public key from Ledger");
let signature =
common::Signature::try_from_slice(&response.raw_signature)
.expect("unable to parse signature from Ledger");
// Signatures from the Ledger come back in compressed
// form
let compressed = CompressedAuthorization {
targets: response.raw_indices,
signer: Signer::PubKeys(vec![pubkey]),
signatures: [(0, signature)].into(),
};
// Expand out the signature before adding it to the
// transaction
tx.add_section(Section::Authorization(compressed.expand(&tx)));
}
// Sign the fee header if that is requested
if parts.contains(&signing::Signable::FeeHeader) {
let pubkey = common::PublicKey::try_from_slice(&response.pubkey)
.expect("unable to parse public key from Ledger");
let signature =
common::Signature::try_from_slice(&response.wrapper_signature)
.expect("unable to parse signature from Ledger");
// Signatures from the Ledger come back in compressed
// form
let compressed = CompressedAuthorization {
targets: response.wrapper_indices,
signer: Signer::PubKeys(vec![pubkey]),
signatures: [(0, signature)].into(),
};
// Expand out the signature before adding it to the
// transaction
tx.add_section(Section::Authorization(compressed.expand(&tx)));
}
Ok(tx)
}
// Sign the given transaction using a hardware wallet as a backup
pub async fn sign<N: Namada>(
context: &N,
tx: &mut Tx,
args: &args::Tx,
signing_data: SigningTxData,
) -> Result<(), error::Error> {
// Setup a reusable context for signing transactions using the Ledger
if args.use_device {
let transport = WalletTransport::from_arg(args.device_transport);
let app = NamadaApp::new(transport);
let with_hw_data = (context.wallet_lock(), &app);
// Finally, begin the signing with the Ledger as backup
context
.sign(
tx,
args,
signing_data,
with_hardware_wallet::<N::WalletUtils, _>,
with_hw_data,
)
.await?;
} else {
// Otherwise sign without a backup procedure
context
.sign(tx, args, signing_data, default_sign, ())
.await?;
}
Ok(())
}
// Build a transaction to reveal the signer of the given transaction.
pub async fn submit_reveal_aux(
context: &impl Namada,
args: args::Tx,
address: &Address,
) -> Result<(), error::Error> {
if args.dump_tx {
return Ok(());
}
if let Address::Implicit(ImplicitAddress(pkh)) = address {
let public_key = context
.wallet_mut()
.await
.find_public_key_by_pkh(pkh)
.map_err(|e| error::Error::Other(e.to_string()))?;
if tx::is_reveal_pk_needed(context.client(), address).await? {
display_line!(
context.io(),
"Submitting a tx to reveal the public key for address \
{address}..."
);
let (mut tx, signing_data) =
tx::build_reveal_pk(context, &args, &public_key).await?;
sign(context, &mut tx, &args, signing_data).await?;
context.submit(tx, &args).await?;
}
}
Ok(())
}
pub async fn submit_bridge_pool_tx<N: Namada>(
namada: &N,
args: args::EthereumBridgePool,
) -> Result<(), error::Error> {
let tx_args = args.tx.clone();
let (mut tx, signing_data) = args.clone().build(namada).await?;
if args.tx.dump_tx {
tx::dump_tx(namada.io(), &args.tx, tx);
} else {
submit_reveal_aux(namada, tx_args.clone(), &args.sender).await?;
sign(namada, &mut tx, &tx_args, signing_data).await?;
namada.submit(tx, &tx_args).await?;
}
Ok(())
}
pub async fn submit_custom<N: Namada>(
namada: &N,
args: args::TxCustom,
) -> Result<(), error::Error>
where
<N::Client as namada_sdk::queries::Client>::Error: std::fmt::Display,
{
submit_reveal_aux(namada, args.tx.clone(), &args.owner).await?;
let (mut tx, signing_data) = args.build(namada).await?;
if args.tx.dump_tx {
tx::dump_tx(namada.io(), &args.tx, tx);
} else {
sign(namada, &mut tx, &args.tx, signing_data).await?;
namada.submit(tx, &args.tx).await?;
}
Ok(())
}
pub async fn submit_update_account<N: Namada>(
namada: &N,
args: args::TxUpdateAccount,
) -> Result<(), error::Error>
where
<N::Client as namada_sdk::queries::Client>::Error: std::fmt::Display,
{
let (mut tx, signing_data) = args.build(namada).await?;
if args.tx.dump_tx {
tx::dump_tx(namada.io(), &args.tx, tx);
} else {
sign(namada, &mut tx, &args.tx, signing_data).await?;
namada.submit(tx, &args.tx).await?;
}
Ok(())
}
pub async fn submit_init_account<N: Namada>(
namada: &N,
args: args::TxInitAccount,
) -> Result<Option<Address>, error::Error>
where
<N::Client as namada_sdk::queries::Client>::Error: std::fmt::Display,
{
let (mut tx, signing_data) = tx::build_init_account(namada, &args).await?;
if args.tx.dump_tx {
tx::dump_tx(namada.io(), &args.tx, tx);
} else {
sign(namada, &mut tx, &args.tx, signing_data).await?;
let cmt = tx.first_commitments().unwrap().to_owned();
let wrapper_hash = tx.wrapper_hash();
let response = namada.submit(tx, &args.tx).await?;
if let Some(result) =
response.is_applied_and_valid(wrapper_hash.as_ref(), &cmt)
{
return Ok(result.initialized_accounts.first().cloned());
}
}
Ok(None)
}
pub async fn submit_change_consensus_key(
namada: &impl Namada,
args: args::ConsensusKeyChange,
) -> Result<(), error::Error> {
let validator = args.validator;
let consensus_key = args.consensus_key;
// Determine the alias for the new key
let mut wallet = namada.wallet_mut().await;
let alias = wallet.find_alias(&validator).cloned();
let base_consensus_key_alias = alias
.map(|al| validator_consensus_key(&al))
.unwrap_or_else(|| {
validator_consensus_key(&validator.to_string().into())
});
let mut consensus_key_alias = base_consensus_key_alias.to_string();
let all_keys = wallet.get_secret_keys();
let mut key_counter = 0;
while all_keys.contains_key(&consensus_key_alias) {
key_counter += 1;
consensus_key_alias =
format!("{base_consensus_key_alias}-{key_counter}");
}
// Check the given key or generate a new one
let new_key = consensus_key
.map(|key| match key {
common::PublicKey::Ed25519(_) => key,
common::PublicKey::Secp256k1(_) => {
edisplay_line!(
namada.io(),
"Consensus key can only be ed25519"
);
safe_exit(1)
}
})
.unwrap_or_else(|| {
display_line!(namada.io(), "Generating new consensus key...");
let password =
read_and_confirm_encryption_password(args.unsafe_dont_encrypt);
wallet
.gen_store_secret_key(
// Note that TM only allows ed25519 for consensus key
SchemeType::Ed25519,
Some(consensus_key_alias.clone()),
args.tx.wallet_alias_force,
password,
&mut OsRng,
)
.expect("Key generation should not fail.")
.1
.ref_to()
});
// To avoid wallet deadlocks in following operations
drop(wallet);
let args = args::ConsensusKeyChange {
validator: validator.clone(),
consensus_key: Some(new_key.clone()),
..args
};
let (mut tx, signing_data) = args.build(namada).await?;
if args.tx.dump_tx {
tx::dump_tx(namada.io(), &args.tx, tx);
} else {
sign(namada, &mut tx, &args.tx, signing_data).await?;
let cmt = tx.first_commitments().unwrap().to_owned();
let wrapper_hash = tx.wrapper_hash();
let resp = namada.submit(tx, &args.tx).await?;
if !args.tx.dry_run {
if resp
.is_applied_and_valid(wrapper_hash.as_ref(), &cmt)
.is_some()
{
namada.wallet_mut().await.save().unwrap_or_else(|err| {
edisplay_line!(namada.io(), "{}", err)
});
display_line!(
namada.io(),
"New consensus key stored with alias \
\"{consensus_key_alias}\". It will become active \
{EPOCH_SWITCH_BLOCKS_DELAY} blocks before the start of \
the pipeline epoch relative to the current epoch \
(current epoch + pipeline offset), at which point you \
will need to give the new key to CometBFT in order to be \
able to sign with it in consensus.",
);
}
} else {
display_line!(
namada.io(),
"Transaction dry run. No new consensus key has been saved."
);
}
}
Ok(())
}
pub async fn submit_become_validator(
namada: &impl Namada,
config: &mut crate::config::Config,
args: args::TxBecomeValidator,
) -> Result<(), error::Error> {
let alias = args
.tx
.initialized_account_alias
.as_ref()
.cloned()
.unwrap_or_else(|| "validator".to_string());
let validator_key_alias = format!("{}-key", alias);
let consensus_key_alias = validator_consensus_key(&alias.clone().into());
let protocol_key_alias = format!("{}-protocol-key", alias);
let eth_hot_key_alias = format!("{}-eth-hot-key", alias);
let eth_cold_key_alias = format!("{}-eth-cold-key", alias);
let address_alias = validator_address(&alias.clone().into());
let mut wallet = namada.wallet_mut().await;
let consensus_key = args
.consensus_key
.clone()
.map(|key| match key {
common::PublicKey::Ed25519(_) => key,
common::PublicKey::Secp256k1(_) => {
edisplay_line!(
namada.io(),
"Consensus key can only be ed25519"
);
safe_exit(1)
}
})
.unwrap_or_else(|| {
display_line!(namada.io(), "Generating consensus key...");
let password =
read_and_confirm_encryption_password(args.unsafe_dont_encrypt);
wallet
.gen_store_secret_key(
// Note that TM only allows ed25519 for consensus key
SchemeType::Ed25519,
Some(consensus_key_alias.clone().into()),
args.tx.wallet_alias_force,
password,
&mut OsRng,
)
.expect("Key generation should not fail.")
.1
.ref_to()
});
let eth_cold_pk = args
.eth_cold_key
.clone()
.map(|key| match key {
common::PublicKey::Secp256k1(_) => key,
common::PublicKey::Ed25519(_) => {
edisplay_line!(
namada.io(),
"Eth cold key can only be secp256k1"
);
safe_exit(1)
}
})
.unwrap_or_else(|| {
display_line!(namada.io(), "Generating Eth cold key...");
let password =
read_and_confirm_encryption_password(args.unsafe_dont_encrypt);
wallet
.gen_store_secret_key(
// Note that ETH only allows secp256k1
SchemeType::Secp256k1,
Some(eth_cold_key_alias.clone()),
args.tx.wallet_alias_force,
password,
&mut OsRng,
)
.expect("Key generation should not fail.")
.1
.ref_to()
});
let eth_hot_pk = args
.eth_hot_key
.clone()
.map(|key| match key {
common::PublicKey::Secp256k1(_) => key,
common::PublicKey::Ed25519(_) => {
edisplay_line!(
namada.io(),
"Eth hot key can only be secp256k1"
);
safe_exit(1)
}
})
.unwrap_or_else(|| {
display_line!(namada.io(), "Generating Eth hot key...");
let password =
read_and_confirm_encryption_password(args.unsafe_dont_encrypt);
wallet
.gen_store_secret_key(
// Note that ETH only allows secp256k1
SchemeType::Secp256k1,
Some(eth_hot_key_alias.clone()),
args.tx.wallet_alias_force,
password,
&mut OsRng,
)
.expect("Key generation should not fail.")
.1
.ref_to()
});
// To avoid wallet deadlocks in following operations
drop(wallet);
if args.protocol_key.is_none() {
display_line!(namada.io(), "Generating protocol signing key...");
}
// Generate the validator keys
let validator_keys = gen_validator_keys(
&mut *namada.wallet_mut().await,
Some(eth_hot_pk.clone()),
args.protocol_key.clone(),
args.scheme,
)
.unwrap();
let protocol_sk = validator_keys.get_protocol_keypair();
let protocol_key = protocol_sk.to_public();
let args = TxBecomeValidator {
consensus_key: Some(consensus_key.clone()),
eth_cold_key: Some(eth_cold_pk),
eth_hot_key: Some(eth_hot_pk),
protocol_key: Some(protocol_key),
..args
};
// Store the protocol key in the wallet so that we can sign the tx with it
// to verify ownership
display_line!(namada.io(), "Storing protocol key in the wallet...");
let password =
read_and_confirm_encryption_password(args.unsafe_dont_encrypt);
namada
.wallet_mut()
.await
.insert_keypair(
protocol_key_alias,
args.tx.wallet_alias_force,
protocol_sk.clone(),
password,
None,
None,
)
.ok_or(error::Error::Other(String::from(
"Failed to store the keypair.",
)))?;
let (mut tx, signing_data) = args.build(namada).await?;
if args.tx.dump_tx {
tx::dump_tx(namada.io(), &args.tx, tx);
} else {
sign(namada, &mut tx, &args.tx, signing_data).await?;
let cmt = tx.first_commitments().unwrap().to_owned();
let wrapper_hash = tx.wrapper_hash();
let resp = namada.submit(tx, &args.tx).await?;
if args.tx.dry_run {
display_line!(
namada.io(),
"Transaction dry run. No key or addresses have been saved."
);
safe_exit(0)
}
if resp
.is_applied_and_valid(wrapper_hash.as_ref(), &cmt)
.is_none()
{
display_line!(
namada.io(),
"Transaction failed. No key or addresses have been saved."
);
safe_exit(1)
}
// add validator address and keys to the wallet
let mut wallet = namada.wallet_mut().await;
wallet.insert_address(
address_alias.normalize(),
args.address.clone(),
false,
);
wallet.add_validator_data(args.address.clone(), validator_keys);
wallet
.save()
.unwrap_or_else(|err| edisplay_line!(namada.io(), "{}", err));
let tendermint_home = config.ledger.cometbft_dir();
tendermint_node::write_validator_key(
&tendermint_home,
&wallet
.find_key_by_pk(&consensus_key, None)
.expect("unable to find consensus key pair in the wallet"),
)
.unwrap();
// To avoid wallet deadlocks in following operations
drop(wallet);
tendermint_node::write_validator_state(tendermint_home).unwrap();
// Write Namada config stuff or figure out how to do the above
// tendermint_node things two epochs in the future!!!
config.ledger.shell.tendermint_mode = TendermintMode::Validator;
config
.write(&config.ledger.shell.base_dir, &config.ledger.chain_id, true)
.unwrap();
let pos_params = rpc::query_pos_parameters(namada.client()).await;
display_line!(namada.io(), "");
display_line!(
namada.io(),
"The keys for validator \"{alias}\" were stored in the wallet:"
);
display_line!(
namada.io(),
" Validator account key \"{}\"",
validator_key_alias
);
display_line!(
namada.io(),
" Consensus key \"{}\"",
consensus_key_alias
);
display_line!(
namada.io(),
"Your validator address {} has been stored in the wallet with \
alias \"{}\".",
args.address,
address_alias
);
display_line!(
namada.io(),
"The ledger node has been setup to use this validator's address \
and consensus key."
);
display_line!(
namada.io(),
"Your validator will be active in {} epochs. Be sure to restart \
your node for the changes to take effect!",
pos_params.pipeline_len
);
}
Ok(())
}
pub async fn submit_init_validator(
namada: &impl Namada,
config: &mut crate::config::Config,
args::TxInitValidator {
tx: tx_args,
scheme,
account_keys,
threshold,
consensus_key,
eth_cold_key,
eth_hot_key,
protocol_key,
commission_rate,
max_commission_rate_change,
email,
website,
description,
discord_handle,
avatar,
name,
validator_vp_code_path,
unsafe_dont_encrypt,
tx_init_account_code_path,
tx_become_validator_code_path,
}: args::TxInitValidator,
) -> Result<(), error::Error> {
let address = submit_init_account(
namada,
args::TxInitAccount {
tx: tx_args.clone(),
vp_code_path: validator_vp_code_path,
tx_code_path: tx_init_account_code_path,
public_keys: account_keys,
threshold,
},
)
.await?;
if tx_args.dry_run {
eprintln!(
"Cannot proceed to become validator in dry-run as no account has \
been created"
);
safe_exit(1)
}
let address = address.unwrap_or_else(|| {
eprintln!(
"Something went wrong with transaction to initialize an account \
as no address has been created. Cannot proceed to become \
validator."
);
safe_exit(1);
});
submit_become_validator(
namada,
config,
args::TxBecomeValidator {
tx: tx_args,
address,
scheme,
consensus_key,
eth_cold_key,
eth_hot_key,
protocol_key,
commission_rate,
max_commission_rate_change,
email,
description,
website,
discord_handle,
avatar,
name,
tx_code_path: tx_become_validator_code_path,
unsafe_dont_encrypt,
},
)
.await
}
pub async fn submit_transparent_transfer(
namada: &impl Namada,
args: args::TxTransparentTransfer,
) -> Result<(), error::Error> {
if args.data.len() > 1 {
// TODO(namada#3379): Vectorized transfers are not yet supported in the
// CLI
return Err(error::Error::Other(
"Unexpected vectorized transparent transfer".to_string(),
));
}
for datum in args.data.iter() {
submit_reveal_aux(namada, args.tx.clone(), &datum.source).await?;
}
let (mut tx, signing_data) = args.clone().build(namada).await?;
if args.tx.dump_tx {
tx::dump_tx(namada.io(), &args.tx, tx);
} else {
sign(namada, &mut tx, &args.tx, signing_data).await?;
namada.submit(tx, &args.tx).await?;
}
Ok(())
}
// A mapper that replaces authorization signatures with those in a built-in map
struct MapSaplingSigAuth(
HashMap<usize, <sapling::Authorized as sapling::Authorization>::AuthSig>,
);
impl sapling::MapAuth<sapling::Authorized, sapling::Authorized>
for MapSaplingSigAuth
{
fn map_proof(
&self,
p: <sapling::Authorized as sapling::Authorization>::Proof,
_pos: usize,
) -> <sapling::Authorized as sapling::Authorization>::Proof {
p
}
fn map_auth_sig(
&self,
s: <sapling::Authorized as sapling::Authorization>::AuthSig,
pos: usize,
) -> <sapling::Authorized as sapling::Authorization>::AuthSig {
self.0.get(&pos).cloned().unwrap_or(s)
}
fn map_authorization(&self, a: sapling::Authorized) -> sapling::Authorized {
a
}
}
pub async fn submit_shielded_transfer(
namada: &impl Namada,
mut args: args::TxShieldedTransfer,
) -> Result<(), error::Error> {
// Records the shielded keys that are on the hardware wallet
let mut shielded_hw_keys = HashMap::new();
// Construct the build parameters that parameterized the Transaction
// authorizations
let mut bparams: Box<dyn BuildParams> = if args.tx.use_device {
let transport = WalletTransport::from_arg(args.tx.device_transport);
let app = NamadaApp::new(transport);
// Make dummy path and tx to supply to buffer cleaning function
let dummy_path = BIP44Path { path: "m/32'/877'/0'".to_string() };
let dummy_tx = Tx::default().serialize_to_vec();
app.clean_randomness_buffers(&dummy_path, &dummy_tx).await.map_err(|err| {
error::Error::Other(format!(
"Unable to clear randomness buffer. Error: {}", err,
))
})?;
let wallet = namada.wallet().await;
// Augment the pseudo spending key with a proof authorization key
for data in &mut args.data {
// Only attempt an augmentation if proof authorization is not there
if data.source.to_spending_key().is_none() {
// First find the derivation path corresponding to this viewing
// key
let viewing_key =
ExtendedViewingKey::from(data.source.to_viewing_key());
let path = wallet
.find_path_by_viewing_key(&viewing_key)
.map_err(|err| {
error::Error::Other(format!(
"Unable to find derivation path from the wallet \
for viewing key {}. Error: {}",
viewing_key, err,
))
})?;
let path = BIP44Path {
path: path.to_string(),
};
// Then confirm that the viewing key at this path in the
// hardware wallet matches the viewing key in this pseudo
// spending key
let response = app
.retrieve_keys(&path, NamadaKeys::ViewKey, true)
.await
.map_err(|err| {
error::Error::Other(format!(
"Unable to obtain viewing key from the hardware \
wallet at path {}. Error: {}",
path.path, err,
))
})?;
let KeyResponse::ViewKey(response_key) = response else {
return Err(error::Error::Other(
"Unexpected response from Ledger".to_string(),
));
};
let xfvk =
ExtendedFullViewingKey::try_from_slice(&response_key.xfvk)
.expect(
"unable to decode extended full viewing key from \
the hardware wallet",
);
if ExtendedFullViewingKey::from(viewing_key) != xfvk {
return Err(error::Error::Other(format!(
"Unexpected viewing key response from Ledger: {}",
ExtendedViewingKey::from(xfvk),
)));
}
// Then obtain the proof authorization key at this path in the
// hardware wallet
let response = app
.retrieve_keys(&path, NamadaKeys::ProofGenerationKey, false)
.await
.map_err(|err| {
error::Error::Other(format!(
"Unable to obtain proof generation key from the \
hardware wallet for viewing key {}. Error: {}",
viewing_key, err,
))
})?;
let KeyResponse::ProofGenKey(response_key) = response else {
return Err(error::Error::Other(
"Unexpected response from Ledger".to_string(),
));
};
let pgk = ProofGenerationKey::try_from_slice(
&[response_key.ak, response_key.nsk].concat(),
)
.map_err(|err| {
error::Error::Other(format!(
"Unexpected proof generation key in response from the \
hardware wallet: {}.",
err,
))
})?;
// Augment the pseudo spending key
data.source.augment_proof_generation_key(pgk).map_err(
|_| {
error::Error::Other(
"Proof generation key in response from the \
hardware wallet does not correspond to stored \
viewing key."
.to_string(),
)
},
)?;
// Finally, augment an incorrect spend authorization key just to
// make sure that the Transaction is built.
data.source.augment_spend_authorizing_key_unchecked(
PrivateKey(jubjub::Fr::default()),
);
shielded_hw_keys.insert(path.path, viewing_key);
}
}
// Get randomness to aid in construction of various descriptors
let mut bparams = StoredBuildParams::default();
// Number of spend descriptions is the number of transfers
let spend_len = args.data.len();
// Number of convert description is assumed to be double the number of
// transfers. This is because each spend description might first be
// converted to epoch 0 before going to the intended epoch.
let convert_len = args.data.len() * 2;
// Number of output descriptions is assumed to be double the number of
// transfers. This is because there may be change from each output
// that's destined for the sender.
let output_len = args.data.len() * 2;
for _ in 0..spend_len {
let spend_randomness = app
.get_spend_randomness()
.await
.map_err(|err| error::Error::Other(err.to_string()))?;
bparams.spend_params.push(SpendBuildParams {
rcv: jubjub::Fr::from_bytes(&spend_randomness.rcv).unwrap(),
alpha: jubjub::Fr::from_bytes(&spend_randomness.alpha).unwrap(),
..SpendBuildParams::default()
});
}
for _ in 0..convert_len {
let convert_randomness = app
.get_convert_randomness()
.await
.map_err(|err| error::Error::Other(err.to_string()))?;
bparams.convert_params.push(ConvertBuildParams {
rcv: jubjub::Fr::from_bytes(&convert_randomness.rcv).unwrap(),
});
}
for _ in 0..output_len {
let output_randomness = app
.get_output_randomness()
.await
.map_err(|err| error::Error::Other(err.to_string()))?;
bparams.output_params.push(OutputBuildParams {
rcv: jubjub::Fr::from_bytes(&output_randomness.rcv).unwrap(),
rseed: output_randomness.rcm,
..OutputBuildParams::default()
});
}
Box::new(bparams)
} else {
Box::new(RngBuildParams::new(OsRng))
};
let (mut tx, signing_data) =
args.clone().build(namada, &mut bparams).await?;
if args.tx.dump_tx {
tx::dump_tx(namada.io(), &args.tx, tx);
} else {
// Get the MASP section that is the target of our signing
if let Some(shielded_hash) = signing_data.shielded_hash {
let mut masp_tx = tx
.get_masp_section(&shielded_hash)
.expect("Expected to find the indicated MASP Transaction")
.clone();