-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathprotocol.rs
More file actions
1849 lines (1729 loc) · 65.4 KB
/
protocol.rs
File metadata and controls
1849 lines (1729 loc) · 65.4 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
//! The ledger's protocol
use std::cell::RefCell;
use std::collections::BTreeSet;
use std::fmt::{Debug, Display};
use either::Either;
use eyre::{WrapErr, eyre};
use namada_sdk::address::{Address, InternalAddress};
use namada_sdk::booleans::BoolResultUnitExt;
use namada_sdk::chain::BlockHeight;
use namada_sdk::collections::HashSet;
use namada_sdk::events::EventLevel;
use namada_sdk::events::extend::{
ComposeEvent, Height as HeightAttr, InnerTxHash as InnerTxHashAttr,
TxHash as TxHashAttr, UserAccount,
};
use namada_sdk::gas::{self, Gas, GasMetering, TxGasMeter, VpGasMeter};
use namada_sdk::hash::Hash;
use namada_sdk::parameters::get_gas_scale;
use namada_sdk::state::{
DB, DBIter, State, StorageHasher, StorageRead, TxWrites, WlState,
};
use namada_sdk::storage::TxIndex;
use namada_sdk::token::Amount;
use namada_sdk::token::event::{TokenEvent, TokenOperation};
use namada_sdk::token::utils::is_masp_transfer;
use namada_sdk::tx::action::{self, Read};
use namada_sdk::tx::data::protocol::{ProtocolTx, ProtocolTxType};
use namada_sdk::tx::data::{
BatchedTxResult, TxResult, VpStatusFlags, VpsResult, WrapperTx,
compute_inner_tx_hash,
};
use namada_sdk::tx::event::{MaspEvent, MaspEventKind, MaspTxRef};
use namada_sdk::tx::{BatchedTxRef, IndexedTx, Tx, TxCommitments};
use namada_sdk::validation::{
EthBridgeNutVp, EthBridgePoolVp, EthBridgeVp, GovernanceVp, IbcVp, MaspVp,
MultitokenVp, NativeVpCtx, ParametersVp, PgfVp, PosVp,
};
use namada_sdk::{governance, parameters, state, storage, token};
#[doc(inline)]
pub use namada_vm::wasm::run::GasMeterKind;
use namada_vm::wasm::{TxCache, VpCache};
use namada_vm::{self, WasmCacheAccess, wasm};
use namada_vote_ext::EthereumTxData;
use namada_vp::native_vp::NativeVp;
use namada_vp::state::ReadConversionState;
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use smooth_operator::checked;
use thiserror::Error;
#[allow(missing_docs)]
#[derive(Error, Debug)]
pub enum Error {
#[error("No inner transactions were found")]
MissingInnerTxs,
#[error("Missing tx section: {0}")]
MissingSection(String),
#[error("State error: {0}")]
StateError(state::Error),
#[error("Storage error: {0}")]
Error(state::Error),
#[error("Wrapper tx runner error: {0}")]
WrapperRunnerError(String),
#[error("Transaction runner error: {0}")]
TxRunnerError(wasm::run::Error),
#[error("{0:?}")]
ProtocolTxError(#[from] eyre::Error),
#[error("The atomic batch failed at inner transaction {0}")]
FailingAtomicBatch(Hash),
#[error("Gas error: {0}")]
GasError(String),
#[error("Error while processing transaction's fees: {0}")]
FeeError(String),
#[error("Invalid transaction section signature: {0}")]
InvalidSectionSignature(String),
#[error(
"The decrypted transaction {0} has already been applied in this block"
)]
ReplayAttempt(Hash),
#[error("Error executing VP for addresses: {0:?}")]
VpRunnerError(wasm::run::Error),
#[error("The address {0} doesn't exist")]
MissingAddress(Address),
#[error("Native VP error: {0}")]
NativeVpError(state::Error),
#[error("Access to an internal address {0:?} is forbidden")]
AccessForbidden(InternalAddress),
}
impl Error {
/// Determine if the error originates from an invalid transaction
/// section signature. This is required for replay protection.
const fn invalid_section_signature_flag(&self) -> VpStatusFlags {
if matches!(self, Self::InvalidSectionSignature(_)) {
VpStatusFlags::INVALID_SIGNATURE
} else {
VpStatusFlags::empty()
}
}
}
/// Shell parameters for running wasm transactions.
#[allow(missing_docs)]
#[derive(Debug)]
pub struct ShellParams<'a, S, D, H, CA>
where
S: State<D = D, H = H> + Sync,
D: 'static + DB + for<'iter> DBIter<'iter> + Sync,
H: 'static + StorageHasher + Sync,
CA: 'static + WasmCacheAccess + Sync,
{
pub tx_gas_meter: &'a RefCell<TxGasMeter>,
pub state: &'a mut S,
pub vp_wasm_cache: &'a mut VpCache<CA>,
pub tx_wasm_cache: &'a mut TxCache<CA>,
}
impl<'a, S, D, H, CA> ShellParams<'a, S, D, H, CA>
where
S: State<D = D, H = H> + Sync,
D: 'static + DB + for<'iter> DBIter<'iter> + Sync,
H: 'static + StorageHasher + Sync,
CA: 'static + WasmCacheAccess + Sync,
{
/// Create a new instance of `ShellParams`
pub fn new(
tx_gas_meter: &'a RefCell<TxGasMeter>,
state: &'a mut S,
vp_wasm_cache: &'a mut VpCache<CA>,
tx_wasm_cache: &'a mut TxCache<CA>,
) -> Self {
Self {
tx_gas_meter,
state,
vp_wasm_cache,
tx_wasm_cache,
}
}
}
/// Result of applying a transaction
pub type Result<T> = std::result::Result<T, Error>;
/// The result of a call to [`dispatch_tx`]
pub struct DispatchError {
/// The result of the function call
pub error: Error,
/// The tx result produced. It could be produced even in case of
/// an error
pub tx_result: Option<TxResult<Error>>,
}
impl Display for DispatchError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.error)
}
}
impl From<Error> for DispatchError {
fn from(error: Error) -> Self {
Self {
error,
tx_result: None,
}
}
}
/// Arguments for transactions' execution
pub enum DispatchArgs<'a, CA: 'static + WasmCacheAccess + Sync> {
/// Protocol tx data
Protocol(&'a ProtocolTx),
/// Raw tx data
Raw {
/// The tx index
tx_index: TxIndex,
/// The block height
height: BlockHeight,
/// Hash of the header of the wrapper tx containing
/// this raw tx
wrapper_hash: Option<&'a Hash>,
/// The result of the corresponding wrapper tx (missing if governance
/// transaction)
wrapper_tx_result: Option<TxResult<Error>>,
/// Vp cache
vp_wasm_cache: &'a mut VpCache<CA>,
/// Tx cache
tx_wasm_cache: &'a mut TxCache<CA>,
},
/// Wrapper tx data
Wrapper {
/// The wrapper header
wrapper: &'a WrapperTx,
/// The transaction bytes for gas accounting
tx_bytes: &'a [u8],
/// The tx index
tx_index: TxIndex,
/// The block height
height: BlockHeight,
/// The block proposer
block_proposer: &'a Address,
/// Vp cache
vp_wasm_cache: &'a mut VpCache<CA>,
/// Tx cache
tx_wasm_cache: &'a mut TxCache<CA>,
},
}
/// Dispatch a given transaction to be applied based on its type.
///
/// Some storage updates may be derived and applied natively rather than via the
/// wasm environment, in which case validity predicates will be bypassed.
pub fn dispatch_tx<'a, D, H, CA>(
tx: &Tx,
dispatch_args: DispatchArgs<'a, CA>,
tx_gas_meter: &'a RefCell<TxGasMeter>,
state: &'a mut WlState<D, H>,
) -> std::result::Result<TxResult<Error>, Box<DispatchError>>
where
D: 'static + DB + for<'iter> DBIter<'iter> + Sync,
H: 'static + StorageHasher + Sync,
CA: 'static + WasmCacheAccess + Sync,
{
match dispatch_args {
DispatchArgs::Raw {
tx_index,
height,
wrapper_hash,
wrapper_tx_result,
vp_wasm_cache,
tx_wasm_cache,
} => {
if let Some(tx_result) = wrapper_tx_result {
// Replay protection check on the batch
let tx_hash = tx.raw_header_hash();
if state.write_log().has_replay_protection_entry(&tx_hash) {
// If the same batch has already been committed in
// this block, skip execution and return
return Err(Box::new(DispatchError {
error: Error::ReplayAttempt(tx_hash),
tx_result: None,
}));
}
dispatch_inner_txs(
tx,
wrapper_hash,
tx_result,
tx_index,
height,
tx_gas_meter,
state,
vp_wasm_cache,
tx_wasm_cache,
GasMeterKind::MutGlobal,
)
} else {
// Governance proposal. We don't allow tx batches in this case,
// just take the first one
let cmt = tx.first_commitments().ok_or_else(|| {
Box::new(DispatchError::from(Error::MissingInnerTxs))
})?;
let batched_tx_result = apply_wasm_tx(
wrapper_hash,
&tx.batch_ref_tx(cmt),
&tx_index,
ShellParams {
tx_gas_meter,
state,
vp_wasm_cache,
tx_wasm_cache,
},
GasMeterKind::MutGlobal,
)
.map_err(|e| Box::new(DispatchError::from(e)))?;
Ok({
let mut batch_results = TxResult::new();
batch_results.insert_inner_tx_result(
wrapper_hash,
either::Right(cmt),
Ok(batched_tx_result),
);
batch_results
})
}
}
DispatchArgs::Protocol(protocol_tx) => {
// No bundles of protocol transactions, only take the first one
let cmt = tx.first_commitments().ok_or_else(|| {
Box::new(DispatchError::from(Error::MissingInnerTxs))
})?;
let batched_tx_result =
apply_protocol_tx(protocol_tx.tx, tx.data(cmt), state)
.map_err(|e| Box::new(DispatchError::from(e)))?;
Ok({
let mut batch_results = TxResult::new();
batch_results.insert_inner_tx_result(
None,
either::Right(cmt),
Ok(batched_tx_result),
);
batch_results
})
}
DispatchArgs::Wrapper {
wrapper,
tx_bytes,
tx_index,
height,
block_proposer,
vp_wasm_cache,
tx_wasm_cache,
} => {
let mut shell_params = ShellParams::new(
tx_gas_meter,
state,
vp_wasm_cache,
tx_wasm_cache,
);
apply_wrapper_tx(
tx,
wrapper,
tx_bytes,
&tx_index,
height,
tx_gas_meter,
&mut shell_params,
Some(block_proposer),
)
.map_err(|e| {
Box::new(Error::WrapperRunnerError(e.to_string()).into())
})
}
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn dispatch_inner_txs<'a, S, D, H, CA>(
tx: &Tx,
wrapper_hash: Option<&'a Hash>,
mut tx_result: TxResult<Error>,
tx_index: TxIndex,
height: BlockHeight,
tx_gas_meter: &'a RefCell<TxGasMeter>,
state: &'a mut S,
vp_wasm_cache: &'a mut VpCache<CA>,
tx_wasm_cache: &'a mut TxCache<CA>,
gas_meter_kind: GasMeterKind,
) -> std::result::Result<TxResult<Error>, Box<DispatchError>>
where
S: 'static
+ State<D = D, H = H>
+ Read<Err = state::Error>
+ ReadConversionState
+ Sync,
D: 'static + DB + for<'iter> DBIter<'iter> + Sync,
H: 'static + StorageHasher + Sync,
CA: 'static + WasmCacheAccess + Sync,
{
// Extract the inner transactions of the batch that need to be executed,
// excluding those that already ran during the handling of the wrapper tx.
let inner_txs = tx
.commitments()
.iter()
.filter(|cmt| {
let inner_tx_hash =
compute_inner_tx_hash(wrapper_hash, Either::Right(cmt));
!tx_result.contains_key(&inner_tx_hash)
})
.collect::<HashSet<_>>()
.into_iter();
for cmt in inner_txs {
match apply_wasm_tx(
wrapper_hash,
&tx.batch_ref_tx(cmt),
&tx_index,
ShellParams {
tx_gas_meter,
state,
vp_wasm_cache,
tx_wasm_cache,
},
gas_meter_kind,
) {
Err(Error::GasError(msg)) => {
// Gas error aborts the execution of the entire batch
tx_result.insert_inner_tx_result(
wrapper_hash,
either::Right(cmt),
Err(Error::GasError(msg.to_owned())),
);
state.write_log_mut().drop_tx();
return Err(Box::new(DispatchError {
error: Error::GasError(msg.to_owned()),
tx_result: Some(tx_result),
}));
}
Ok(mut batched_tx_result) if batched_tx_result.is_accepted() => {
// If the transaction was a masp one generate the
// appropriate event
if let Some(masp_ref) = get_optional_masp_ref(
state,
cmt,
Either::Right(&batched_tx_result),
)
.map_err(|e| Box::new(DispatchError::from(e)))?
{
let inner_tx_hash =
compute_inner_tx_hash(wrapper_hash, Either::Right(cmt));
batched_tx_result.events.insert(
MaspEvent {
tx_index: IndexedTx {
block_height: height,
block_index: tx_index,
batch_index: tx
.header
.batch
.get_index_of(cmt)
.map(|idx| {
TxIndex::must_from_usize(idx).into()
}),
},
kind: MaspEventKind::Transfer,
data: masp_ref,
}
.with(TxHashAttr(
// Zero hash if the wrapper is not provided
// (governance proposal)
wrapper_hash.cloned().unwrap_or_default(),
))
.with(InnerTxHashAttr(inner_tx_hash))
.into(),
);
}
tx_result.insert_inner_tx_result(
wrapper_hash,
either::Right(cmt),
Ok(batched_tx_result),
);
state.write_log_mut().commit_tx_to_batch();
}
// Handle all the other failure cases
res => {
tx_result.insert_inner_tx_result(
wrapper_hash,
either::Right(cmt),
res,
);
state.write_log_mut().drop_tx();
if tx.header.atomic {
// Stop the execution of an atomic batch at the
// first failed transaction
return Err(Box::new(DispatchError {
error: Error::FailingAtomicBatch(cmt.get_hash()),
tx_result: Some(tx_result),
}));
}
}
};
}
Ok(tx_result)
}
/// Transaction result for masp transfer
pub struct MaspTxResult {
tx_result: BatchedTxResult,
masp_section_ref: MaspTxRef,
}
/// Performs the required operation on a wrapper transaction:
/// - replay protection
/// - fee payment
/// - gas accounting
#[allow(clippy::too_many_arguments)]
pub(crate) fn apply_wrapper_tx<S, D, H, CA>(
tx: &Tx,
wrapper: &WrapperTx,
tx_bytes: &[u8],
tx_index: &TxIndex,
height: BlockHeight,
tx_gas_meter: &RefCell<TxGasMeter>,
shell_params: &mut ShellParams<'_, S, D, H, CA>,
block_proposer: Option<&Address>,
) -> Result<TxResult<Error>>
where
S: 'static
+ State<D = D, H = H>
+ Read<Err = state::Error>
+ TxWrites
+ ReadConversionState
+ Sync,
D: 'static + DB + for<'iter> DBIter<'iter> + Sync,
H: 'static + StorageHasher + Sync,
CA: 'static + WasmCacheAccess + Sync,
{
// Write wrapper tx hash to storage
shell_params
.state
.write_log_mut()
.write_tx_hash(tx.header_hash())
.expect("Error while writing tx hash to storage");
// Charge or check fees, propagate any errors to prevent committing invalid
// data
let payment_result = match block_proposer {
Some(block_proposer) => {
transfer_fee(shell_params, block_proposer, tx, wrapper, tx_index)?
}
None => check_fees(shell_params, tx, wrapper)?,
};
// Commit tx to the block write log even in case of subsequent errors (if
// the fee payment failed instead, then the previous two functions must
// have propagated an error)
shell_params
.state
.write_log_mut()
.commit_batch_and_current_tx();
let batch_results =
payment_result.map_or_else(TxResult::default, |mut masp_tx_result| {
// Ok to unwrap cause if we have a batched result it means we've
// executed the first tx in the batch
let first_commitments = tx.first_commitments().unwrap();
let mut batch = TxResult::default();
// Generate Masp event if needed
masp_tx_result.tx_result.events.insert(
MaspEvent {
tx_index: IndexedTx {
block_height: height,
block_index: tx_index.to_owned(),
batch_index: Some(0),
},
kind: MaspEventKind::FeePayment,
data: masp_tx_result.masp_section_ref,
}
.with(TxHashAttr(tx.header_hash()))
.with(InnerTxHashAttr(compute_inner_tx_hash(
tx.wrapper_hash().as_ref(),
Either::Right(first_commitments),
)))
.into(),
);
batch.insert_inner_tx_result(
tx.wrapper_hash().as_ref(),
either::Right(first_commitments),
Ok(masp_tx_result.tx_result),
);
batch
});
// Account for gas
tx_gas_meter
.borrow_mut()
.add_wrapper_gas(tx_bytes)
.map_err(|err| Error::GasError(err.to_string()))?;
Ok(batch_results)
}
/// Perform the actual transfer of fees from the fee payer to the block
/// proposer. No modifications to the write log are committed or dropped in this
/// function: this logic is up to the caller.
pub fn transfer_fee<S, D, H, CA>(
shell_params: &mut ShellParams<'_, S, D, H, CA>,
block_proposer: &Address,
tx: &Tx,
wrapper: &WrapperTx,
tx_index: &TxIndex,
) -> Result<Option<MaspTxResult>>
where
S: 'static
+ State<D = D, H = H>
+ StorageRead
+ TxWrites
+ Read<Err = state::Error>
+ ReadConversionState
+ Sync,
D: 'static + DB + for<'iter> DBIter<'iter> + Sync,
H: 'static + StorageHasher + Sync,
CA: 'static + WasmCacheAccess + Sync,
{
match wrapper.get_tx_fee() {
Ok(fees) => {
let fees = token::denom_to_amount(
fees,
&wrapper.fee.token,
shell_params.state,
)
.map_err(Error::Error)?;
#[cfg(not(fuzzing))]
let balance = token::read_balance(
shell_params.state,
&wrapper.fee.token,
&wrapper.fee_payer(),
)
.map_err(Error::Error)?;
// Use half of the max value to make the balance check pass
// sometimes with arbitrary fees
#[cfg(fuzzing)]
let balance = Amount::max().checked_div_u64(2).unwrap();
let (post_bal, valid_batched_tx_result) = if let Some(post_bal) =
balance.checked_sub(fees)
{
fee_token_transfer(
shell_params.state,
&wrapper.fee.token,
&wrapper.fee_payer(),
block_proposer,
fees,
)?;
(post_bal, None)
} else {
// See if the first inner transaction of the batch pays the fees
// with a masp unshield
match try_masp_fee_payment(shell_params, tx, tx_index) {
Ok(valid_batched_tx_result) => {
#[cfg(not(fuzzing))]
let balance = token::read_balance(
shell_params.state,
&wrapper.fee.token,
&wrapper.fee_payer(),
)
.expect("Could not read balance key from storage");
#[cfg(fuzzing)]
let balance = Amount::max().checked_div_u64(2).unwrap();
let post_bal = match balance.checked_sub(fees) {
Some(post_bal) => {
// This cannot fail given the checked_sub check
// here above
fee_token_transfer(
shell_params.state,
&wrapper.fee.token,
&wrapper.fee_payer(),
block_proposer,
fees,
)?;
post_bal
}
None => {
// This shouldn't happen as it should be
// prevented
// from process_proposal.
tracing::error!(
"Transfer of tx fee cannot be applied to \
due to insufficient funds. This \
shouldn't happen."
);
return Err(Error::FeeError(
"Insufficient funds for fee payment"
.to_string(),
));
}
};
// Batched tx result must be returned (and considered)
// only if fee payment was
// successful
(post_bal, Some(valid_batched_tx_result))
}
Err(e) => {
// This shouldn't happen as it should be prevented by
// process_proposal.
tracing::error!(
"Transfer of tx fee cannot be applied because of \
an error: {}. This shouldn't happen.",
e
);
return Err(e.into());
}
}
};
let target_post_balance = Some(
token::read_balance(
shell_params.state,
&wrapper.fee.token,
block_proposer,
)
.map_err(Error::Error)?
.into(),
);
const FEE_PAYMENT_DESCRIPTOR: std::borrow::Cow<'static, str> =
std::borrow::Cow::Borrowed("wrapper-fee-payment");
let current_block_height = shell_params
.state
.in_mem()
.get_last_block_height()
.next_height();
shell_params.state.write_log_mut().emit_event(
TokenEvent {
descriptor: FEE_PAYMENT_DESCRIPTOR,
level: EventLevel::Tx,
operation: TokenOperation::transfer(
UserAccount::Internal(wrapper.fee_payer()),
UserAccount::Internal(block_proposer.clone()),
wrapper.fee.token.clone(),
fees.into(),
post_bal.into(),
target_post_balance,
),
}
.with(HeightAttr(current_block_height))
.with(TxHashAttr(tx.header_hash())),
);
Ok(valid_batched_tx_result)
}
Err(e) => {
// Fee overflow. This shouldn't happen as it should be prevented
// by process_proposal.
tracing::error!(
"Transfer of tx fee cannot be applied to due to fee overflow. \
This shouldn't happen."
);
Err(Error::FeeError(format!("{}", e)))
}
}
}
/// Custom wrapper type for masp fee payment errors. The purpose of this type is
/// to prepend errors with some masp fee payment string to ensure that the
/// messages we produce are not misleading
pub struct MaspFeeError(Error);
impl Display for MaspFeeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", Error::from(self))
}
}
impl From<&MaspFeeError> for Error {
fn from(value: &MaspFeeError) -> Self {
let msg = match &value.0 {
// Destructure the error to avoid nesting a FeeError into another
// instance of itself, which would produce a duplicated message
Error::FeeError(inner_msg) => inner_msg,
error => &error.to_string(),
};
Self::FeeError(format!(
"The transparent balance of the fee payer was insufficient to pay \
fees. The protocol tried to run the first transaction in the \
batch to pay fees via the MASP but it failed: {msg}",
))
}
}
impl From<MaspFeeError> for Error {
fn from(value: MaspFeeError) -> Self {
Self::from(&value)
}
}
impl From<Error> for MaspFeeError {
fn from(value: Error) -> Self {
Self(value)
}
}
fn try_masp_fee_payment<S, D, H, CA>(
ShellParams {
tx_gas_meter,
state,
vp_wasm_cache,
tx_wasm_cache,
}: &mut ShellParams<'_, S, D, H, CA>,
tx: &Tx,
tx_index: &TxIndex,
) -> std::result::Result<MaspTxResult, MaspFeeError>
where
S: 'static
+ State<D = D, H = H>
+ StorageRead
+ Read<Err = state::Error>
+ ReadConversionState
+ Sync,
D: 'static + DB + for<'iter> DBIter<'iter> + Sync,
H: 'static + StorageHasher + Sync,
CA: 'static + WasmCacheAccess + Sync,
{
// The fee payment is subject to a gas limit imposed by a protocol
// parameter. Here we instantiate a custom gas meter for this step where the
// gas limit is actually the lowest between the protocol parameter and the
// actual remaining gas of the transaction. The latter is because we want to
// enforce that no tx exceeds its own gas limit, which could happen for
// some transactions (e.g. batches consuming a lot of gas for
// their size) if we were to take their gas limit instead of the remaining
// gas
let max_gas_limit = state
.read::<u64>(¶meters::storage::get_masp_fee_payment_gas_limit_key())
.expect("Error reading the storage")
.expect("Missing masp fee payment gas limit in storage")
.min(tx_gas_meter.borrow().get_available_gas().into());
let gas_scale = get_gas_scale(&**state).map_err(Error::Error)?;
let masp_gas_meter = RefCell::new(TxGasMeter::new(
Gas::from_whole_units(max_gas_limit.into(), gas_scale).ok_or_else(
|| Error::GasError("Overflow in gas expansion".to_string()),
)?,
gas_scale,
));
let valid_batched_tx_result = {
let first_tx = tx
.batch_ref_first_tx()
.ok_or_else(|| Error::MissingInnerTxs)?;
match apply_wasm_tx(
Some(&tx.header_hash()),
&first_tx,
tx_index,
ShellParams {
tx_gas_meter: &masp_gas_meter,
state: *state,
vp_wasm_cache,
tx_wasm_cache,
},
GasMeterKind::MutGlobal,
) {
Ok(result) => {
// NOTE: do not commit yet cause this could be exploited to get
// free masp operations. We can commit only after the entire fee
// payment has been deemed valid. Also, do not commit to batch
// cause we might need to discard the effects of this valid
// unshield (e.g. if it unshields an amount which is not enough
// to pay the fees)
let is_masp_transfer = is_masp_transfer(&result.changed_keys);
// Ensure that the transaction is actually a masp one, otherwise
// reject
if is_masp_transfer && result.is_accepted() {
let masp_section_ref = get_optional_masp_ref(
*state,
first_tx.cmt,
Either::Left(true),
)?
.ok_or_else(|| {
Error::FeeError(
"Missing expected masp section reference"
.to_string(),
)
})?;
MaspTxResult {
tx_result: result,
masp_section_ref,
}
} else {
state.write_log_mut().drop_tx();
let error_msg = if !is_masp_transfer {
"Not a MASP transaction.".to_string()
} else {
format!(
"Some VPs rejected it: {:?}",
result.vps_result.errors
)
};
tracing::error!(error_msg);
return Err(Error::FeeError(error_msg).into());
}
}
Err(e) => {
state.write_log_mut().drop_tx();
let error_msg = format!("Wasm run failed: {}", e);
tracing::error!(error_msg);
return Err(Error::FeeError(error_msg).into());
}
}
};
tx_gas_meter
.borrow_mut()
.consume(masp_gas_meter.borrow().get_consumed_gas())
.map_err(|e| Error::GasError(e.to_string()))?;
Ok(valid_batched_tx_result)
}
// Check that the transaction was a MASP one and extract the MASP tx reference
// (if any) in the same order that the MASP VP follows (IBC first, Actions
// second). The order is important to prevent malicious transactions from
// messing up with indexers/clients. Also a transaction can only be of one of
// the two types, not both at the same time (the MASP VP accepts a single
// Transaction)
fn get_optional_masp_ref<S: Read<Err = state::Error>>(
state: &S,
cmt: &TxCommitments,
is_masp_tx: Either<bool, &BatchedTxResult>,
) -> Result<Option<MaspTxRef>> {
// Always check that the transaction was indeed a MASP one by looking at the
// changed keys. A malicious tx could push a MASP Action without touching
// any storage keys associated with the shielded pool
let is_masp_tx = match is_masp_tx {
Either::Left(res) => res,
Either::Right(tx_result) => is_masp_transfer(&tx_result.changed_keys),
};
if !is_masp_tx {
return Ok(None);
}
let masp_ref = if action::is_ibc_shielding_transfer(state)
.map_err(Error::StateError)?
{
Some(MaspTxRef::IbcData(cmt.data_sechash().to_owned()))
} else {
let actions = state.read_actions().map_err(Error::StateError)?;
action::get_masp_section_ref(&actions)
.map_err(|msg| {
Error::StateError(state::Error::new_alloc(msg.to_string()))
})?
.map(MaspTxRef::MaspSection)
};
Ok(masp_ref)
}
// Manage the token transfer for the fee payment. If an error is detected the
// write log is dropped to prevent committing an inconsistent state. Propagates
// the result to the caller
fn fee_token_transfer<WLS>(
state: &mut WLS,
token: &Address,
src: &Address,
dest: &Address,
amount: Amount,
) -> Result<()>
where
WLS: State + StorageRead + TxWrites,
{
token::transfer(&mut state.with_tx_writes(), token, src, dest, amount)
.map_err(|err| {
state.write_log_mut().drop_tx();
Error::Error(err)
})
}
/// Check if the fee payer has enough transparent balance to pay fees
pub fn check_fees<S, D, H, CA>(
shell_params: &mut ShellParams<'_, S, D, H, CA>,
tx: &Tx,
wrapper: &WrapperTx,
) -> Result<Option<MaspTxResult>>
where
S: 'static
+ State<D = D, H = H>
+ StorageRead
+ Read<Err = state::Error>
+ ReadConversionState
+ Sync,
D: 'static + DB + for<'iter> DBIter<'iter> + Sync,
H: 'static + StorageHasher + Sync,
CA: 'static + WasmCacheAccess + Sync,
{
match wrapper.get_tx_fee() {
Ok(fees) => {
let fees = token::denom_to_amount(
fees,
&wrapper.fee.token,
shell_params.state,
)
.map_err(Error::Error)?;
let balance = token::read_balance(
shell_params.state,
&wrapper.fee.token,
&wrapper.fee_payer(),
)
.map_err(Error::Error)?;
checked!(balance - fees).map_or_else(
|_| {
// See if the first inner transaction of the batch pays
// the fees with a masp unshield
let valid_batched_tx_result = try_masp_fee_payment(
shell_params,
tx,
&TxIndex::default(),
)?;
let balance = token::read_balance(
shell_params.state,
&wrapper.fee.token,