-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathlib.rs
More file actions
1544 lines (1438 loc) · 51.3 KB
/
lib.rs
File metadata and controls
1544 lines (1438 loc) · 51.3 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
extern crate alloc;
extern crate core;
pub use namada_core::*;
#[cfg(feature = "tendermint-rpc")]
pub use tendermint_rpc;
pub use {
bip39, masp_primitives, masp_proofs, namada_account as account,
namada_governance as governance, namada_proof_of_stake as proof_of_stake,
namada_state as state, namada_storage as storage, zeroize,
};
pub mod eth_bridge;
pub mod rpc;
pub mod args;
pub mod masp;
pub mod signing;
#[allow(clippy::result_large_err)]
pub mod tx;
pub mod control_flow;
pub mod error;
pub mod events;
pub(crate) mod internal_macros;
pub mod io;
pub mod migrations;
pub mod queries;
pub mod wallet;
#[cfg(feature = "async-send")]
pub use std::marker::Send as MaybeSend;
#[cfg(feature = "async-send")]
pub use std::marker::Sync as MaybeSync;
use std::path::PathBuf;
use std::str::FromStr;
use args::{InputAmount, SdkTypes};
use namada_core::address::Address;
use namada_core::collections::HashSet;
use namada_core::dec::Dec;
use namada_core::ethereum_events::EthAddress;
use namada_core::ibc::core::host::types::identifiers::{ChannelId, PortId};
use namada_core::key::*;
use namada_core::masp::{TransferSource, TransferTarget};
use namada_tx::data::wrapper::GasLimit;
use namada_tx::Tx;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use crate::io::Io;
use crate::masp::{ShieldedContext, ShieldedUtils};
use crate::rpc::{
denominate_amount, format_denominated_amount, query_native_token,
};
use crate::signing::SigningTxData;
use crate::token::{DenominatedAmount, NATIVE_MAX_DECIMAL_PLACES};
use crate::tx::{
ProcessTxResponse, TX_BECOME_VALIDATOR_WASM, TX_BOND_WASM,
TX_BRIDGE_POOL_WASM, TX_CHANGE_COMMISSION_WASM,
TX_CHANGE_CONSENSUS_KEY_WASM, TX_CHANGE_METADATA_WASM,
TX_CLAIM_REWARDS_WASM, TX_DEACTIVATE_VALIDATOR_WASM, TX_IBC_WASM,
TX_INIT_ACCOUNT_WASM, TX_INIT_PROPOSAL, TX_REACTIVATE_VALIDATOR_WASM,
TX_REDELEGATE_WASM, TX_RESIGN_STEWARD, TX_REVEAL_PK, TX_TRANSFER_WASM,
TX_UNBOND_WASM, TX_UNJAIL_VALIDATOR_WASM, TX_UPDATE_ACCOUNT_WASM,
TX_UPDATE_STEWARD_COMMISSION, TX_VOTE_PROPOSAL, TX_WITHDRAW_WASM,
VP_USER_WASM,
};
use crate::wallet::{Wallet, WalletIo, WalletStorage};
#[cfg(not(feature = "async-send"))]
pub trait MaybeSync {}
#[cfg(not(feature = "async-send"))]
impl<T> MaybeSync for T where T: ?Sized {}
#[cfg(not(feature = "async-send"))]
pub trait MaybeSend {}
#[cfg(not(feature = "async-send"))]
impl<T> MaybeSend for T where T: ?Sized {}
#[cfg_attr(feature = "async-send", async_trait::async_trait)]
#[cfg_attr(not(feature = "async-send"), async_trait::async_trait(?Send))]
/// An interface for high-level interaction with the Namada SDK
pub trait Namada: Sized + MaybeSync + MaybeSend {
/// A client with async request dispatcher method
type Client: queries::Client + MaybeSend + Sync;
/// Captures the interactive parts of the wallet's functioning
type WalletUtils: WalletIo + WalletStorage + MaybeSend + MaybeSync;
/// Abstracts platform specific details away from the logic of shielded pool
/// operations.
type ShieldedUtils: ShieldedUtils + MaybeSend + MaybeSync;
/// Captures the input/output streams used by this object
type Io: Io + MaybeSend + MaybeSync;
/// Obtain the client for communicating with the ledger
fn client(&self) -> &Self::Client;
/// Obtain the input/output handle for this context
fn io(&self) -> &Self::Io;
/// Obtain read guard on the wallet
async fn wallet(&self) -> RwLockReadGuard<Wallet<Self::WalletUtils>>;
/// Obtain write guard on the wallet
async fn wallet_mut(&self) -> RwLockWriteGuard<Wallet<Self::WalletUtils>>;
/// Obtain the wallet lock
fn wallet_lock(&self) -> &RwLock<Wallet<Self::WalletUtils>>;
/// Obtain read guard on the shielded context
async fn shielded(
&self,
) -> RwLockReadGuard<ShieldedContext<Self::ShieldedUtils>>;
/// Obtain write guard on the shielded context
async fn shielded_mut(
&self,
) -> RwLockWriteGuard<ShieldedContext<Self::ShieldedUtils>>;
/// Return the native token
fn native_token(&self) -> Address;
/// Make a tx builder using no arguments
fn tx_builder(&self) -> args::Tx {
args::Tx {
dry_run: false,
dry_run_wrapper: false,
dump_tx: false,
output_folder: None,
force: false,
broadcast_only: false,
ledger_address: tendermint_rpc::Url::from_str(
"http://127.0.0.1:26657",
)
.unwrap(),
initialized_account_alias: None,
wallet_alias_force: false,
fee_amount: None,
wrapper_fee_payer: None,
fee_token: self.native_token(),
fee_unshield: None,
gas_limit: GasLimit::from(20_000),
expiration: Default::default(),
disposable_signing_key: false,
chain_id: None,
signing_keys: vec![],
signatures: vec![],
tx_reveal_code_path: PathBuf::from(TX_REVEAL_PK),
password: None,
memo: None,
use_device: false,
}
}
/// Make a TxTransfer builder from the given minimum set of arguments
fn new_transfer(
&self,
source: TransferSource,
target: TransferTarget,
token: Address,
amount: InputAmount,
) -> args::TxTransfer {
args::TxTransfer {
source,
target,
token,
amount,
tx_code_path: PathBuf::from(TX_TRANSFER_WASM),
tx: self.tx_builder(),
}
}
/// Make a InitAccount builder from the given minimum set of arguments
fn new_init_account(
&self,
public_keys: Vec<common::PublicKey>,
threshold: Option<u8>,
) -> args::TxInitAccount {
args::TxInitAccount {
tx: self.tx_builder(),
vp_code_path: PathBuf::from(VP_USER_WASM),
tx_code_path: PathBuf::from(TX_INIT_ACCOUNT_WASM),
public_keys,
threshold,
}
}
/// Make a RevealPK builder from the given minimum set of arguments
fn new_reveal_pk(&self, public_key: common::PublicKey) -> args::RevealPk {
args::RevealPk {
public_key,
tx: self.tx_builder(),
}
}
/// Make a Bond builder from the given minimum set of arguments
fn new_bond(
&self,
validator: Address,
amount: token::Amount,
) -> args::Bond {
args::Bond {
validator,
amount,
source: None,
tx: self.tx_builder(),
tx_code_path: PathBuf::from(TX_BOND_WASM),
}
}
/// Make a Unbond builder from the given minimum set of arguments
fn new_unbond(
&self,
validator: Address,
amount: token::Amount,
) -> args::Unbond {
args::Unbond {
validator,
amount,
source: None,
tx: self.tx_builder(),
tx_code_path: PathBuf::from(TX_UNBOND_WASM),
}
}
// Make a Redelegation builder for the given minimum set of arguments
fn new_redelegation(
&self,
source: Address,
src_validator: Address,
dest_validator: Address,
amount: token::Amount,
) -> args::Redelegate {
args::Redelegate {
tx: self.tx_builder(),
// Source validator address
src_validator,
// Destination validator address
dest_validator,
// Owner of the bonds that are being redelegated
owner: source,
// The amount of tokens to redelegate
amount,
// Path to the TX WASM code file
tx_code_path: PathBuf::from(TX_REDELEGATE_WASM),
}
}
/// Make a TxIbcTransfer builder from the given minimum set of arguments
fn new_ibc_transfer(
&self,
source: TransferSource,
receiver: String,
token: Address,
amount: InputAmount,
channel_id: ChannelId,
) -> args::TxIbcTransfer {
args::TxIbcTransfer {
source,
receiver,
token,
amount,
channel_id,
port_id: PortId::from_str("transfer").unwrap(),
timeout_height: None,
timeout_sec_offset: None,
refund_target: None,
memo: None,
tx: self.tx_builder(),
tx_code_path: PathBuf::from(TX_IBC_WASM),
}
}
/// Make a InitProposal builder from the given minimum set of arguments
fn new_init_proposal(&self, proposal_data: Vec<u8>) -> args::InitProposal {
args::InitProposal {
proposal_data,
is_pgf_stewards: false,
is_pgf_funding: false,
tx_code_path: PathBuf::from(TX_INIT_PROPOSAL),
tx: self.tx_builder(),
}
}
/// Make a TxUpdateAccount builder from the given minimum set of arguments
fn new_update_account(
&self,
addr: Address,
public_keys: Vec<common::PublicKey>,
threshold: u8,
) -> args::TxUpdateAccount {
args::TxUpdateAccount {
addr,
vp_code_path: None,
public_keys,
threshold: Some(threshold),
tx_code_path: PathBuf::from(TX_UPDATE_ACCOUNT_WASM),
tx: self.tx_builder(),
}
}
/// Make a VoteProposal builder from the given minimum set of arguments
fn new_proposal_vote(
&self,
proposal_id: u64,
vote: String,
voter_address: Address,
) -> args::VoteProposal {
args::VoteProposal {
vote,
voter_address,
proposal_id,
tx_code_path: PathBuf::from(TX_VOTE_PROPOSAL),
tx: self.tx_builder(),
}
}
/// Make a CommissionRateChange builder from the given minimum set of
/// arguments
fn new_change_commission_rate(
&self,
rate: Dec,
validator: Address,
) -> args::CommissionRateChange {
args::CommissionRateChange {
rate,
validator,
tx_code_path: PathBuf::from(TX_CHANGE_COMMISSION_WASM),
tx: self.tx_builder(),
}
}
/// Make ConsensusKeyChange builder from the given minimum set of arguments
fn new_change_consensus_key(
&self,
validator: Address,
consensus_key: common::PublicKey,
) -> args::ConsensusKeyChange {
args::ConsensusKeyChange {
validator,
consensus_key: Some(consensus_key),
tx_code_path: PathBuf::from(TX_CHANGE_CONSENSUS_KEY_WASM),
unsafe_dont_encrypt: false,
tx: self.tx_builder(),
}
}
/// Make a CommissionRateChange builder from the given minimum set of
/// arguments
fn new_change_metadata(&self, validator: Address) -> args::MetaDataChange {
args::MetaDataChange {
validator,
email: None,
description: None,
website: None,
discord_handle: None,
avatar: None,
commission_rate: None,
tx_code_path: PathBuf::from(TX_CHANGE_METADATA_WASM),
tx: self.tx_builder(),
}
}
/// Make a TxBecomeValidator builder from the given minimum set of arguments
#[allow(clippy::too_many_arguments)]
fn new_become_validator(
&self,
address: Address,
commission_rate: Dec,
max_commission_rate_change: Dec,
consesus_key: common::PublicKey,
eth_cold_key: common::PublicKey,
eth_hot_key: common::PublicKey,
protocol_key: common::PublicKey,
email: String,
) -> args::TxBecomeValidator {
args::TxBecomeValidator {
address,
commission_rate,
max_commission_rate_change,
scheme: SchemeType::Ed25519,
consensus_key: Some(consesus_key),
eth_cold_key: Some(eth_cold_key),
eth_hot_key: Some(eth_hot_key),
protocol_key: Some(protocol_key),
unsafe_dont_encrypt: false,
tx_code_path: PathBuf::from(TX_BECOME_VALIDATOR_WASM),
tx: self.tx_builder(),
email,
description: None,
website: None,
discord_handle: None,
avatar: None,
}
}
/// Make a TxInitValidator builder from the given minimum set of arguments
fn new_init_validator(
&self,
commission_rate: Dec,
max_commission_rate_change: Dec,
email: String,
) -> args::TxInitValidator {
args::TxInitValidator {
commission_rate,
max_commission_rate_change,
scheme: SchemeType::Ed25519,
account_keys: vec![],
threshold: None,
consensus_key: None,
eth_cold_key: None,
eth_hot_key: None,
protocol_key: None,
validator_vp_code_path: PathBuf::from(VP_USER_WASM),
unsafe_dont_encrypt: false,
tx_init_account_code_path: PathBuf::from(TX_INIT_ACCOUNT_WASM),
tx_become_validator_code_path: PathBuf::from(
TX_BECOME_VALIDATOR_WASM,
),
tx: self.tx_builder(),
email,
description: None,
website: None,
discord_handle: None,
avatar: None,
}
}
/// Make a TxUnjailValidator builder from the given minimum set of arguments
fn new_unjail_validator(
&self,
validator: Address,
) -> args::TxUnjailValidator {
args::TxUnjailValidator {
validator,
tx_code_path: PathBuf::from(TX_UNJAIL_VALIDATOR_WASM),
tx: self.tx_builder(),
}
}
/// Make a TxDeactivateValidator builder from the given minimum set of
/// arguments
fn new_deactivate_validator(
&self,
validator: Address,
) -> args::TxDeactivateValidator {
args::TxDeactivateValidator {
validator,
tx_code_path: PathBuf::from(TX_DEACTIVATE_VALIDATOR_WASM),
tx: self.tx_builder(),
}
}
/// Make a TxReactivateValidator builder from the given minimum set of
/// arguments
fn new_reactivate_validator(
&self,
validator: Address,
) -> args::TxReactivateValidator {
args::TxReactivateValidator {
validator,
tx_code_path: PathBuf::from(TX_REACTIVATE_VALIDATOR_WASM),
tx: self.tx_builder(),
}
}
/// Make a Withdraw builder from the given minimum set of arguments
fn new_withdraw(&self, validator: Address) -> args::Withdraw {
args::Withdraw {
validator,
source: None,
tx_code_path: PathBuf::from(TX_WITHDRAW_WASM),
tx: self.tx_builder(),
}
}
/// Make a Claim-rewards builder from the given minimum set of arguments
fn new_claim_rewards(&self, validator: Address) -> args::ClaimRewards {
args::ClaimRewards {
validator,
source: None,
tx_code_path: PathBuf::from(TX_CLAIM_REWARDS_WASM),
tx: self.tx_builder(),
}
}
/// Make a Withdraw builder from the given minimum set of arguments
fn new_add_erc20_transfer(
&self,
sender: Address,
recipient: EthAddress,
asset: EthAddress,
amount: InputAmount,
) -> args::EthereumBridgePool {
args::EthereumBridgePool {
sender,
recipient,
asset,
amount,
fee_amount: InputAmount::Unvalidated(
token::DenominatedAmount::new(
token::Amount::default(),
NATIVE_MAX_DECIMAL_PLACES.into(),
),
),
fee_payer: None,
fee_token: self.native_token(),
nut: false,
code_path: PathBuf::from(TX_BRIDGE_POOL_WASM),
tx: self.tx_builder(),
}
}
/// Make a ResignSteward builder from the given minimum set of arguments
fn new_resign_steward(&self, steward: Address) -> args::ResignSteward {
args::ResignSteward {
steward,
tx: self.tx_builder(),
tx_code_path: PathBuf::from(TX_RESIGN_STEWARD),
}
}
/// Make a UpdateStewardCommission builder from the given minimum set of
/// arguments
fn new_update_steward_rewards(
&self,
steward: Address,
commission: Vec<u8>,
) -> args::UpdateStewardCommission {
args::UpdateStewardCommission {
steward,
commission,
tx: self.tx_builder(),
tx_code_path: PathBuf::from(TX_UPDATE_STEWARD_COMMISSION),
}
}
/// Make a TxCustom builder from the given minimum set of arguments
fn new_custom(&self, owner: Address) -> args::TxCustom {
args::TxCustom {
owner,
tx: self.tx_builder(),
code_path: None,
data_path: None,
serialized_tx: None,
}
}
/// Sign the given transaction using the given signing data
async fn sign<D, F>(
&self,
tx: &mut Tx,
args: &args::Tx,
signing_data: SigningTxData,
with: impl Fn(Tx, common::PublicKey, HashSet<signing::Signable>, D) -> F
+ MaybeSend
+ MaybeSync,
user_data: D,
) -> crate::error::Result<()>
where
D: Clone + MaybeSend + MaybeSync,
F: MaybeSend
+ MaybeSync
+ std::future::Future<Output = crate::error::Result<Tx>>,
{
signing::sign_tx(
self.wallet_lock(),
args,
tx,
signing_data,
with,
user_data,
)
.await
}
/// Process the given transaction using the given flags
async fn submit(
&self,
tx: Tx,
args: &args::Tx,
) -> crate::error::Result<ProcessTxResponse> {
tx::process_tx(self, args, tx).await
}
/// Look up the denomination of a token in order to make a correctly
/// denominated amount.
async fn denominate_amount(
&self,
token: &Address,
amount: token::Amount,
) -> DenominatedAmount {
denominate_amount(self.client(), self.io(), token, amount).await
}
/// Look up the denomination of a token in order to format it correctly as a
/// string.
async fn format_amount(
&self,
token: &Address,
amount: token::Amount,
) -> String {
format_denominated_amount(self.client(), self.io(), token, amount).await
}
}
/// Provides convenience methods for common Namada interactions
pub struct NamadaImpl<C, U, V, I>
where
C: queries::Client,
U: WalletIo,
V: ShieldedUtils,
I: Io,
{
/// Used to send and receive messages from the ledger
pub client: C,
/// Stores the addresses and keys required for ledger interactions
pub wallet: RwLock<Wallet<U>>,
/// Stores the current state of the shielded pool
pub shielded: RwLock<ShieldedContext<V>>,
/// Captures the input/output streams used by this object
pub io: I,
/// The address of the native token
native_token: Address,
/// The default builder for a Tx
prototype: args::Tx,
}
impl<C, U, V, I> NamadaImpl<C, U, V, I>
where
C: queries::Client + Sync,
U: WalletIo,
V: ShieldedUtils,
I: Io,
{
/// Construct a new Namada context with the given native token address
pub fn native_new(
client: C,
wallet: Wallet<U>,
shielded: ShieldedContext<V>,
io: I,
native_token: Address,
) -> Self {
NamadaImpl {
client,
wallet: RwLock::new(wallet),
shielded: RwLock::new(shielded),
io,
native_token: native_token.clone(),
prototype: args::Tx {
dry_run: false,
dry_run_wrapper: false,
dump_tx: false,
output_folder: None,
force: false,
broadcast_only: false,
ledger_address: tendermint_rpc::Url::from_str(
"http://127.0.0.1:26657",
)
.unwrap(),
initialized_account_alias: None,
wallet_alias_force: false,
fee_amount: None,
wrapper_fee_payer: None,
fee_token: native_token,
fee_unshield: None,
gas_limit: GasLimit::from(20_000),
expiration: Default::default(),
disposable_signing_key: false,
chain_id: None,
signing_keys: vec![],
signatures: vec![],
tx_reveal_code_path: PathBuf::from(TX_REVEAL_PK),
password: None,
memo: None,
use_device: false,
},
}
}
/// Construct a new Namada context looking up the native token address
pub async fn new(
client: C,
wallet: Wallet<U>,
shielded: ShieldedContext<V>,
io: I,
) -> crate::error::Result<NamadaImpl<C, U, V, I>> {
let native_token = query_native_token(&client).await?;
Ok(NamadaImpl::native_new(
client,
wallet,
shielded,
io,
native_token,
))
}
}
#[cfg_attr(feature = "async-send", async_trait::async_trait)]
#[cfg_attr(not(feature = "async-send"), async_trait::async_trait(?Send))]
impl<C, U, V, I> Namada for NamadaImpl<C, U, V, I>
where
C: queries::Client + MaybeSend + Sync,
U: WalletIo + WalletStorage + MaybeSync + MaybeSend,
V: ShieldedUtils + MaybeSend + MaybeSync,
I: Io + MaybeSend + MaybeSync,
{
type Client = C;
type Io = I;
type ShieldedUtils = V;
type WalletUtils = U;
/// Obtain the prototypical Tx builder
fn tx_builder(&self) -> args::Tx {
self.prototype.clone()
}
fn native_token(&self) -> Address {
self.native_token.clone()
}
fn io(&self) -> &Self::Io {
&self.io
}
fn client(&self) -> &Self::Client {
&self.client
}
async fn wallet(&self) -> RwLockReadGuard<Wallet<Self::WalletUtils>> {
self.wallet.read().await
}
async fn wallet_mut(&self) -> RwLockWriteGuard<Wallet<Self::WalletUtils>> {
self.wallet.write().await
}
async fn shielded(
&self,
) -> RwLockReadGuard<ShieldedContext<Self::ShieldedUtils>> {
self.shielded.read().await
}
async fn shielded_mut(
&self,
) -> RwLockWriteGuard<ShieldedContext<Self::ShieldedUtils>> {
self.shielded.write().await
}
fn wallet_lock(&self) -> &RwLock<Wallet<Self::WalletUtils>> {
&self.wallet
}
}
/// Allow the prototypical Tx builder to be modified
impl<C, U, V, I> args::TxBuilder<SdkTypes> for NamadaImpl<C, U, V, I>
where
C: queries::Client + Sync,
U: WalletIo,
V: ShieldedUtils,
I: Io,
{
fn tx<F>(self, func: F) -> Self
where
F: FnOnce(args::Tx<SdkTypes>) -> args::Tx<SdkTypes>,
{
Self {
prototype: func(self.prototype),
..self
}
}
}
#[cfg(any(test, feature = "testing"))]
/// Tests and strategies for transactions
pub mod testing {
use borsh_ext::BorshSerializeExt;
use governance::ProposalType;
use ibc::primitives::proto::Any;
use masp_primitives::transaction::TransparentAddress;
use namada_account::{InitAccount, UpdateAccount};
use namada_core::address::testing::{
arb_established_address, arb_non_internal_address,
};
use namada_core::address::MASP;
use namada_core::eth_bridge_pool::PendingTransfer;
use namada_core::hash::testing::arb_hash;
use namada_core::key::testing::arb_common_keypair;
use namada_core::storage::testing::arb_epoch;
use namada_core::token::testing::{arb_denominated_amount, arb_transfer};
use namada_core::token::Transfer;
use namada_governance::storage::proposal::testing::{
arb_init_proposal, arb_vote_proposal,
};
use namada_governance::{InitProposalData, VoteProposalData};
use namada_ibc::testing::arb_ibc_any;
use namada_tx::data::pgf::UpdateStewardCommission;
use namada_tx::data::pos::{
BecomeValidator, Bond, CommissionChange, ConsensusKeyChange,
MetaDataChange, Redelegation, Unbond, Withdraw,
};
use namada_tx::data::{DecryptedTx, Fee, TxType, WrapperTx};
use proptest::prelude::{Just, Strategy};
use proptest::{arbitrary, collection, option, prop_compose, prop_oneof};
use prost::Message;
use ripemd::Digest as RipemdDigest;
use sha2::Digest;
use super::*;
use crate::account::tests::{arb_init_account, arb_update_account};
use crate::chain::ChainId;
use crate::eth_bridge_pool::testing::arb_pending_transfer;
use crate::key::testing::arb_common_pk;
use crate::masp::testing::{
arb_deshielding_transfer, arb_shielded_transfer, arb_shielding_transfer,
};
use crate::time::{DateTime, DateTimeUtc, Utc};
use crate::tx::data::pgf::tests::arb_update_steward_commission;
use crate::tx::data::pos::tests::{
arb_become_validator, arb_bond, arb_commission_change,
arb_consensus_key_change, arb_metadata_change, arb_redelegation,
arb_withdraw,
};
use crate::tx::{
Authorization, Code, Commitment, Header, MaspBuilder, Section,
};
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
// To facilitate propagating debugging information
pub enum TxData {
CommissionChange(CommissionChange),
ConsensusKeyChange(ConsensusKeyChange),
MetaDataChange(MetaDataChange),
ClaimRewards(Withdraw),
DeactivateValidator(Address),
InitAccount(InitAccount),
InitProposal(InitProposalData),
InitValidator(BecomeValidator),
ReactivateValidator(Address),
RevealPk(common::PublicKey),
Unbond(Unbond),
UnjailValidator(Address),
UpdateAccount(UpdateAccount),
VoteProposal(VoteProposalData),
Withdraw(Withdraw),
Transfer(Transfer),
Bond(Bond),
Redelegation(Redelegation),
UpdateStewardCommission(UpdateStewardCommission),
ResignSteward(Address),
PendingTransfer(PendingTransfer),
IbcAny(Any),
Custom,
}
prop_compose! {
// Generate an arbitrary commitment
pub fn arb_commitment()(
commitment in prop_oneof![
arb_hash().prop_map(Commitment::Hash),
collection::vec(arbitrary::any::<u8>(), 0..=1024).prop_map(Commitment::Id),
],
) -> Commitment {
commitment
}
}
prop_compose! {
// Generate an arbitrary code section
pub fn arb_code()(
salt: [u8; 8],
code in arb_commitment(),
tag in option::of("[a-zA-Z0-9_]*"),
) -> Code {
Code {
salt,
code,
tag,
}
}
}
prop_compose! {
// Generate an arbitrary uttf8 commitment
pub fn arb_utf8_commitment()(
commitment in prop_oneof![
arb_hash().prop_map(Commitment::Hash),
"[a-zA-Z0-9_]{0,1024}".prop_map(|x| Commitment::Id(x.into_bytes())),
],
) -> Commitment {
commitment
}
}
prop_compose! {
// Generate an arbitrary code section
pub fn arb_utf8_code()(
salt: [u8; 8],
code in arb_utf8_commitment(),
tag in option::of("[a-zA-Z0-9_]{0,1024}"),
) -> Code {
Code {
salt,
code,
tag,
}
}
}
prop_compose! {
// Generate a chain ID
pub fn arb_chain_id()(id in "[a-zA-Z0-9_]*") -> ChainId {
ChainId(id)
}
}
prop_compose! {
// Generate a date and time
pub fn arb_date_time_utc()(
secs in DateTime::<Utc>::MIN_UTC.timestamp()..=DateTime::<Utc>::MAX_UTC.timestamp(),
nsecs in ..1000000000u32,
) -> DateTimeUtc {
DateTimeUtc(DateTime::<Utc>::from_timestamp(secs, nsecs).unwrap())
}
}
prop_compose! {
// Generate an arbitrary fee
pub fn arb_fee()(
amount_per_gas_unit in arb_denominated_amount(),
token in arb_established_address().prop_map(Address::Established),
) -> Fee {
Fee {
amount_per_gas_unit,
token,
}
}
}
prop_compose! {
// Generate an arbitrary gas limit
pub fn arb_gas_limit()(multiplier: u64) -> GasLimit {
multiplier.into()
}
}
prop_compose! {
// Generate an arbitrary wrapper transaction
pub fn arb_wrapper_tx()(
fee in arb_fee(),
epoch in arb_epoch(),
pk in arb_common_pk(),
gas_limit in arb_gas_limit(),
unshield_section_hash in option::of(arb_hash()),
) -> WrapperTx {
WrapperTx {
fee,
epoch,
pk,
gas_limit,
unshield_section_hash,
}
}
}
prop_compose! {
// Generate an arbitrary decrypted transaction
pub fn arb_decrypted_tx()(decrypted_tx in prop_oneof![
Just(DecryptedTx::Decrypted),
Just(DecryptedTx::Undecryptable),
]) -> DecryptedTx {
decrypted_tx
}
}
prop_compose! {
// Generate an arbitrary transaction type
pub fn arb_tx_type()(tx_type in prop_oneof![
Just(TxType::Raw),
arb_wrapper_tx().prop_map(|x| TxType::Wrapper(Box::new(x))),
]) -> TxType {
tx_type
}
}
prop_compose! {
// Generate an arbitrary header
pub fn arb_header()(
chain_id in arb_chain_id(),
expiration in option::of(arb_date_time_utc()),
timestamp in arb_date_time_utc(),
code_hash in arb_hash(),
data_hash in arb_hash(),
memo_hash in arb_hash(),
tx_type in arb_tx_type(),
) -> Header {
Header {
chain_id,
expiration,
timestamp,