-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathfinalize_block.rs
More file actions
6399 lines (5846 loc) · 226 KB
/
finalize_block.rs
File metadata and controls
6399 lines (5846 loc) · 226 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
//! Implementation of the `FinalizeBlock` ABCI++ method for the Shell
use data_encoding::HEXUPPER;
use either::Either;
use masp_primitives::merkle_tree::CommitmentTree;
use masp_primitives::sapling::Node;
use namada_sdk::events::extend::{ComposeEvent, Height, Info, TxHash};
use namada_sdk::events::{EmitEvents, Event};
use namada_sdk::gas::GasMetering;
use namada_sdk::gas::event::GasUsed;
use namada_sdk::governance::pgf::inflation as pgf_inflation;
use namada_sdk::hash::Hash;
use namada_sdk::parameters::get_gas_scale;
use namada_sdk::proof_of_stake::storage::{
find_validator_by_raw_hash, write_last_block_proposer_address,
};
use namada_sdk::state::write_log::StorageModification;
use namada_sdk::state::{
EPOCH_SWITCH_BLOCKS_DELAY, Result, ResultExt, StorageWrite,
};
use namada_sdk::storage::{BlockHeader, BlockResults, Epoch};
use namada_sdk::tx::data::protocol::ProtocolTxType;
use namada_sdk::tx::data::{VpStatusFlags, compute_inner_tx_hash};
use namada_sdk::tx::event::{Batch, Code};
use namada_sdk::tx::new_tx_event;
use namada_sdk::{ibc, proof_of_stake};
use namada_vote_ext::ethereum_events::MultiSignedEthEvent;
use namada_vote_ext::ethereum_tx_data_variants;
use tendermint::abci::types::Misbehavior;
use super::*;
use crate::protocol::{DispatchArgs, DispatchError};
use crate::shell::stats::InternalStats;
use crate::tendermint::abci::types::VoteInfo;
use crate::tendermint_proto;
impl<D, H> Shell<D, H>
where
D: DB + for<'iter> DBIter<'iter> + Sync + 'static,
H: StorageHasher + Sync + 'static,
{
/// Updates the chain with new header, height, etc. Also keeps track
/// of epoch changes and applies associated updates to validator sets,
/// etc. as necessary.
///
/// Apply the transactions included in the block.
pub fn finalize_block(
&mut self,
req: shim::request::FinalizeBlock,
) -> ShellResult<shim::response::FinalizeBlock> {
let mut response = shim::response::FinalizeBlock::default();
// Begin the new block and check if a new epoch has begun
let (height, new_epoch) = self.update_state(req.header);
let masp_epoch_multiplier =
parameters::read_masp_epoch_multiplier_parameter(&self.state)
.expect("Must have parameters");
let is_masp_new_epoch = self
.state
.is_masp_new_epoch(new_epoch, masp_epoch_multiplier)?;
let (current_epoch, _gas) = self.state.in_mem().get_current_epoch();
let update_for_tendermint = matches!(
self.state.in_mem().update_epoch_blocks_delay,
Some(EPOCH_SWITCH_BLOCKS_DELAY)
);
tracing::info!(
"Block height: {height}, epoch: {current_epoch}, is new epoch: \
{new_epoch}, is masp new epoch: {is_masp_new_epoch}."
);
if update_for_tendermint {
tracing::info!(
"Will begin a new epoch {} in {} blocks starting at height {}",
current_epoch.next(),
EPOCH_SWITCH_BLOCKS_DELAY,
height
.0
.checked_add(u64::from(EPOCH_SWITCH_BLOCKS_DELAY))
.expect("Shouldn't overflow")
);
}
tracing::debug!(
"New epoch block delay for updating the Tendermint validator set: \
{:?}",
self.state.in_mem().update_epoch_blocks_delay
);
let emit_events = &mut response.events;
// Get the actual votes from cometBFT in the preferred format
let votes =
pos_votes_from_abci(&self.state, &req.decided_last_commit.votes);
let validator_set_update_epoch =
self.get_validator_set_update_epoch(current_epoch);
let gas_scale = get_gas_scale(&self.state)
.expect("Failed to get gas scale from parameters");
// Sub-system updates:
// - Governance - applied first in case a proposal changes any of the
// other syb-systems
gov_finalize_block(
self,
emit_events,
current_epoch,
new_epoch,
gas_scale,
)?;
// - Token
token_finalize_block(&mut self.state, emit_events, is_masp_new_epoch)?;
// - PoS
// - Must be applied after governance in case it changes PoS params
pos_finalize_block(
&mut self.state,
emit_events,
new_epoch,
validator_set_update_epoch,
votes,
req.byzantine_validators,
)?;
// - IBC
ibc::finalize_block(&mut self.state, emit_events, new_epoch)?;
if new_epoch {
// Apply PoS and PGF inflation
self.apply_inflation(current_epoch, emit_events)?;
}
let mut stats = InternalStats::default();
let native_block_proposer_address = {
let tm_raw_hash_string =
tm_raw_hash_to_string(req.proposer_address);
find_validator_by_raw_hash(&self.state, tm_raw_hash_string)
.unwrap()
.expect(
"Unable to find native validator address of block \
proposer from tendermint raw hash",
)
};
// Tracks the accepted transactions
self.state.in_mem_mut().block.results = BlockResults::default();
let mut changed_keys = BTreeSet::new();
// Execute wrapper and protocol transactions
let successful_wrappers = self.retrieve_and_execute_transactions(
&native_block_proposer_address,
&req.txs,
gas_scale,
ExecutionArgs {
response: &mut response,
changed_keys: &mut changed_keys,
stats: &mut stats,
height,
},
);
// Execute inner transactions
self.execute_tx_batches(
successful_wrappers,
ExecutionArgs {
response: &mut response,
changed_keys: &mut changed_keys,
stats: &mut stats,
height,
},
);
stats.set_tx_cache_size(
self.tx_wasm_cache.get_size(),
self.tx_wasm_cache.get_cache_size(),
);
stats.set_vp_cache_size(
self.vp_wasm_cache.get_size(),
self.vp_wasm_cache.get_cache_size(),
);
tracing::info!("{}", stats);
tracing::info!("{}", stats.format_tx_executed());
// Update the MASP commitment tree anchor if the tree was updated
let tree_key = token::storage_key::masp_commitment_tree_key();
if let Some(StorageModification::Write { value }) = self
.state
.write_log()
.read(&tree_key)
.expect("Must be able to read masp commitment tree")
.0
{
let updated_tree = CommitmentTree::<Node>::try_from_slice(value)
.into_storage_result()?;
let anchor_key = token::storage_key::masp_commitment_anchor_key(
updated_tree.root(),
);
self.state.write(&anchor_key, ())?;
}
if update_for_tendermint {
self.update_epoch(&mut response);
// send the latest oracle configs. These may have changed due to
// governance.
self.update_eth_oracle(&changed_keys);
}
write_last_block_proposer_address(
&mut self.state,
native_block_proposer_address,
)?;
self.event_log_mut().emit_many(response.events.clone());
tracing::debug!("End finalize_block {height} of epoch {current_epoch}");
Ok(response)
}
/// Sets the metadata necessary for a new block, including the height,
/// validator changes, and evidence of byzantine behavior. Applies slashes
/// if necessary. Returns a boolean indicating if a new epoch and the height
/// of the new block.
fn update_state(&mut self, header: BlockHeader) -> (BlockHeight, bool) {
let height = self.state.in_mem().get_last_block_height().next_height();
self.state
.in_mem_mut()
.begin_block(height)
.expect("Beginning a block shouldn't fail");
let header_time = header.time;
self.state
.in_mem_mut()
.set_header(header)
.expect("Setting a header shouldn't fail");
let parameters =
parameters::read(&self.state).expect("Must have parameters");
let new_epoch = self
.state
.update_epoch(height, header_time, ¶meters)
.expect("Must be able to update epoch");
(height, new_epoch)
}
fn update_tx_gas(&mut self, tx_hash: Hash, gas: Gas) {
self.state.in_mem_mut().add_tx_gas(tx_hash, gas);
}
/// If a new epoch begins, we update the response to include
/// changes to the validator sets and consensus parameters
fn update_epoch(&mut self, response: &mut shim::response::FinalizeBlock) {
// Apply validator set update
response.validator_updates = self
.get_abci_validator_updates(false, |pk, power| {
let pub_key = tendermint_proto::crypto::PublicKey {
sum: Some(key_to_tendermint(&pk).unwrap()),
};
let pub_key = Some(pub_key);
tendermint_proto::abci::ValidatorUpdate { pub_key, power }
})
.expect("Must be able to update validator set");
}
/// Calculate the new inflation rate, mint the new tokens to the PoS
/// account, then update the reward products of the validators. This is
/// executed while finalizing the first block of a new epoch and is applied
/// with respect to the previous epoch.
fn apply_inflation(
&mut self,
current_epoch: Epoch,
events: &mut impl EmitEvents,
) -> Result<()> {
let last_epoch = current_epoch
.prev()
.expect("Must have a prev epoch when applying inflation");
// Get the number of blocks in the last epoch
let first_block_of_last_epoch =
self.state.in_mem().block.pred_epochs.first_block_heights
[usize::try_from(last_epoch.0)
.expect("Last epoch shouldn't exceed `usize::MAX`")]
.0;
let num_blocks_in_last_epoch = self
.state
.in_mem()
.block
.height
.0
.checked_sub(first_block_of_last_epoch)
.expect(
"First block of last epoch must always be lower than or equal \
to current block height",
);
// PoS inflation
proof_of_stake::rewards::apply_inflation::<
_,
governance::Store<_>,
parameters::Store<_>,
token::Store<_>,
>(&mut self.state, last_epoch, num_blocks_in_last_epoch)?;
// Pgf inflation
pgf_apply_inflation(self.state.restrict_writes_to_write_log())?;
// Take events that may be emitted from PGF
for event in self.state.write_log_mut().take_events() {
events.emit(event.with(Height(
self.state.in_mem().get_last_block_height().next_height(),
)));
}
Ok(())
}
// Write the batch hash to storage and mark the corresponding wrapper
// hash as redundant (we check the batch hash too when validating
// the wrapper). Requires the wrapper transaction as argument to recover
// both the hashes.
fn commit_batch_hash(&mut self, hashes: Option<ReplayProtectionHashes>) {
if let Some(ReplayProtectionHashes {
raw_header_hash,
header_hash,
}) = hashes
{
self.state
.write_tx_hash(raw_header_hash)
.expect("Error while writing tx hash to storage");
self.state
.redundant_tx_hash(&header_hash)
.expect("Error while marking tx hash as redundant");
}
}
// Evaluate the result of a transaction. Commit or drop the storage changes,
// update stats and event, manage replay protection. For successful wrapper
// transactions return the relevant data and delay the evaluation after the
// batch execution
fn evaluate_tx_result(
&mut self,
response: &mut shim::response::FinalizeBlock,
extended_dispatch_result: std::result::Result<
namada_sdk::tx::data::TxResult<protocol::Error>,
Box<DispatchError>,
>,
tx_data: TxData<'_>,
mut tx_logs: TxLogs<'_>,
) -> Option<WrapperCache> {
match extended_dispatch_result {
Ok(mut tx_result) => match tx_data.tx.header.tx_type {
TxType::Wrapper(_) => {
// Commit any changes brought in by the inner txs executed
// when handling the wrapper. For now it should be at most
// one, the first tx of the batch that runs to pay fees via
// the masp, this way we can commit the fee payment itself
self.state.write_log_mut().commit_batch_and_current_tx();
// Emit the events of all the inner txs that have been
// successfully executed when handling the wrapper. These
// txs have just been committed so we need to ensure the
// relative events are emitted for consistency
for cmt in tx_data.tx.commitments() {
let inner_tx_hash = compute_inner_tx_hash(
tx_data.tx.wrapper_hash().as_ref(),
Either::Right(cmt),
);
if let Some(Ok(batched_result)) =
tx_result.get_mut(&inner_tx_hash)
{
if batched_result.is_accepted() {
// Take the events from the batch result to
// avoid emitting them again after the exection
// of the entire batch
response.events.emit_many(
std::mem::take(&mut batched_result.events)
.into_iter()
.map(|event| {
event.with(Height(tx_data.height))
}),
);
}
}
}
// Return cached data for the execution of the batch
return Some(WrapperCache {
tx: tx_data.tx.to_owned(),
tx_index: tx_data.tx_index,
gas_meter: tx_data.tx_gas_meter,
event: tx_logs.tx_event,
tx_result,
});
}
_ => self.handle_inner_tx_results(
response,
tx_result,
tx_data,
&mut tx_logs,
),
},
Err(dispatch_error) => match *dispatch_error {
DispatchError {
error: protocol::Error::WrapperRunnerError(msg),
tx_result: _,
} => {
tracing::info!(
"Wrapper transaction {} failed with: {}",
tx_logs
.tx_event
.raw_read_attribute::<TxHash>()
.unwrap_or("<unknown>"),
msg,
);
let gas_scale = tx_data.tx_gas_meter.get_gas_scale();
let scaled_gas = tx_data
.tx_gas_meter
.get_consumed_gas()
.get_whole_gas_units(gas_scale);
tx_logs
.tx_event
.extend(GasUsed(scaled_gas))
.extend(Info(msg.to_string()))
.extend(Code(ResultCode::InvalidTx));
// Drop the batch write log which could contain invalid
// data. Important data that could be
// valid (e.g. a valid fee payment) must
// have already been moved to the block write log by now
self.state.write_log_mut().drop_batch();
}
_ => {
// This branch represents an error that affects the entire
// batch
let (msg, tx_result) = (
Error::TxApply(dispatch_error.error),
// The tx result should always be present at this point
dispatch_error.tx_result.unwrap_or_default(),
);
tracing::info!(
"Transaction {} failed with: {}",
tx_logs
.tx_event
.raw_read_attribute::<TxHash>()
.unwrap_or("<unknown>"),
msg
);
let gas_scale = tx_data.tx_gas_meter.get_gas_scale();
let scaled_gas = tx_data
.tx_gas_meter
.get_consumed_gas()
.get_whole_gas_units(gas_scale);
tx_logs
.tx_event
.extend(GasUsed(scaled_gas))
.extend(Info(msg.to_string()))
.extend(Code(ResultCode::WasmRuntimeError));
self.handle_batch_error(
response,
&msg,
tx_result,
tx_data,
&mut tx_logs,
);
}
},
}
response.events.emit(tx_logs.tx_event);
None
}
// Evaluate the results of all the transactions of the batch. Commit or drop
// the storage changes, update stats and event, manage replay protection.
fn handle_inner_tx_results(
&mut self,
response: &mut shim::response::FinalizeBlock,
mut tx_result: namada_sdk::tx::data::TxResult<protocol::Error>,
tx_data: TxData<'_>,
tx_logs: &mut TxLogs<'_>,
) {
let mut temp_log = TempTxLogs::new_from_tx_logs(tx_logs);
let ValidityFlags {
commit_batch_hash,
is_any_tx_invalid,
} = temp_log.check_inner_results(&mut tx_result, tx_data.height);
if tx_data.is_atomic_batch && is_any_tx_invalid {
// Atomic batches need custom handling when even a single tx fails,
// since we need to drop everything
let unrun_txs = tx_data
.commitments_len
.checked_sub(
u64::try_from(tx_result.len())
.expect("Should be able to convert to u64"),
)
.expect("Shouldn't underflow");
temp_log.stats.set_failing_atomic_batch(unrun_txs);
temp_log.commit_stats_only(tx_logs);
self.state.write_log_mut().drop_batch();
tx_logs.tx_event.extend(Code(ResultCode::WasmRuntimeError));
} else {
self.state.write_log_mut().commit_batch_and_current_tx();
self.state
.in_mem_mut()
.block
.results
.accept(tx_data.tx_index);
temp_log.commit(tx_logs, response);
// Atomic successful batches or non-atomic batches (even if the
// inner txs failed) are marked as Ok
tx_logs.tx_event.extend(Code(ResultCode::Ok));
}
if commit_batch_hash {
// If at least one of the inner txs of the batch requires its hash
// to be committed than commit the hash of the entire batch
self.commit_batch_hash(tx_data.replay_protection_hashes);
}
let gas_scale = tx_data.tx_gas_meter.get_gas_scale();
let scaled_gas = tx_data
.tx_gas_meter
.get_consumed_gas()
.get_whole_gas_units(gas_scale);
tx_logs
.tx_event
.extend(GasUsed(scaled_gas))
.extend(Info("Check batch for result.".to_string()))
.extend(Batch(&tx_result.to_result_string()));
}
fn handle_batch_error(
&mut self,
response: &mut shim::response::FinalizeBlock,
msg: &Error,
mut tx_result: namada_sdk::tx::data::TxResult<protocol::Error>,
tx_data: TxData<'_>,
tx_logs: &mut TxLogs<'_>,
) {
let mut temp_log = TempTxLogs::new_from_tx_logs(tx_logs);
let ValidityFlags {
commit_batch_hash,
is_any_tx_invalid: _,
} = temp_log.check_inner_results(&mut tx_result, tx_data.height);
let unrun_txs = tx_data
.commitments_len
.checked_sub(
u64::try_from(tx_result.len())
.expect("Should be able to convert to u64"),
)
.expect("Shouldn't underflow");
if tx_data.is_atomic_batch {
tx_logs.stats.set_failing_atomic_batch(unrun_txs);
temp_log.commit_stats_only(tx_logs);
self.state.write_log_mut().drop_batch();
} else {
temp_log.stats.set_failing_batch(unrun_txs);
self.state
.in_mem_mut()
.block
.results
.accept(tx_data.tx_index);
temp_log.commit(tx_logs, response);
// Commit the successful inner transactions before the error. Drop
// the current tx write log which might be still populated with data
// to be discarded (this is the case when we propagate an error
// from the function that runs the actual batch)
self.state.write_log_mut().drop_tx();
self.state.write_log_mut().commit_batch_only();
}
if commit_batch_hash {
// If at least one of the inner txs of the batch requires its hash
// to be committed than commit the hash of the entire batch
// regardless of the specific error
self.commit_batch_hash(tx_data.replay_protection_hashes);
} else {
self.handle_batch_error_reprot(msg, tx_data);
}
tx_logs
.tx_event
.extend(Batch(&tx_result.to_result_string()));
}
fn handle_batch_error_reprot(&mut self, err: &Error, tx_data: TxData<'_>) {
// If user transaction didn't fail because of out of gas nor replay
// attempt, commit its hash to prevent replays. If it failed because of
// a replay attempt just remove the redundant wrapper hash
if !matches!(
err,
Error::TxApply(protocol::Error::GasError(_))
| Error::TxApply(protocol::Error::ReplayAttempt(_))
) {
self.commit_batch_hash(tx_data.replay_protection_hashes);
} else if let Error::TxApply(protocol::Error::ReplayAttempt(_)) = err {
// Remove the wrapper hash but keep the inner tx
// hash. A replay of the wrapper is impossible since
// the inner tx hash is committed to storage and
// we validate the wrapper against that hash too
let header_hash = tx_data
.replay_protection_hashes
.expect("This cannot fail")
.header_hash;
self.state
.redundant_tx_hash(&header_hash)
.expect("Error while marking tx hash as redundant");
}
}
// Get the transactions from the consensus engine, preprocess and execute
// them. Return the cache of successful wrapper transactions later used when
// executing the inner txs.
fn retrieve_and_execute_transactions(
&mut self,
native_block_proposer_address: &Address,
processed_txs: &[shim::request::ProcessedTx],
gas_scale: u64,
ExecutionArgs {
response,
changed_keys,
stats,
height,
}: ExecutionArgs<'_>,
) -> Vec<WrapperCache> {
let mut successful_wrappers = vec![];
for (tx_index, processed_tx) in processed_txs.iter().enumerate() {
let tx =
if let Ok(tx) = Tx::try_from_bytes(processed_tx.tx.as_ref()) {
tx
} else {
tracing::error!(
"FinalizeBlock received a tx that could not be \
deserialized to a Tx type. This is likely a protocol \
transaction."
);
continue;
};
let result_code = ResultCode::from_u32(processed_tx.result.code)
.expect("Result code conversion should not fail");
let tx_header = tx.header();
// If [`process_proposal`] rejected a Tx, emit an event here and
// move on to next tx
if result_code != ResultCode::Ok {
let base_event: Event = match result_code {
// If [`process_proposal`] rejected a Tx due to invalid
// signature, emit an event here and
// move on to next tx
ResultCode::InvalidSig => match tx.header().tx_type {
TxType::Wrapper(_) | TxType::Protocol(_) => {
new_tx_event(&tx, height.0)
}
_ => {
tracing::error!(
"Internal logic error: FinalizeBlock received \
a tx with an invalid signature error code \
that could not be deserialized to a \
WrapperTx / ProtocolTx type"
);
continue;
}
},
_ => new_tx_event(&tx, height.0),
};
response.events.emit(
base_event
.with(Code(result_code))
.with(Info(format!(
"Tx rejected: {}",
&processed_tx.result.info
)))
.with(GasUsed(0.into())),
);
continue;
}
let (dispatch_args, tx_gas_meter): (
DispatchArgs<'_, WasmCacheRwAccess>,
TxGasMeter,
) = match &tx_header.tx_type {
TxType::Wrapper(wrapper) => {
stats.increment_wrapper_txs();
let gas_limit =
match wrapper.gas_limit.as_scaled_gas(gas_scale) {
Ok(value) => value,
Err(_) => {
response.events.emit(
new_tx_event(&tx, height.0)
.with(Code(ResultCode::InvalidTx))
.with(Info(
"The wrapper gas limit overflowed \
gas representation"
.to_owned(),
))
.with(GasUsed(0.into())),
);
continue;
}
};
let tx_gas_meter = TxGasMeter::new(gas_limit, gas_scale);
for cmt in tx.commitments() {
if let Some(code_sec) = tx
.get_section(cmt.code_sechash())
.and_then(|x| Section::code_sec(x.as_ref()))
{
stats.increment_tx_type(
code_sec.code.hash().to_string(),
);
}
}
(
DispatchArgs::Wrapper {
wrapper,
tx_bytes: processed_tx.tx.as_ref(),
tx_index: TxIndex::must_from_usize(tx_index),
height,
block_proposer: native_block_proposer_address,
vp_wasm_cache: &mut self.vp_wasm_cache,
tx_wasm_cache: &mut self.tx_wasm_cache,
},
tx_gas_meter,
)
}
TxType::Raw => {
tracing::error!(
"Internal logic error: FinalizeBlock received a \
TxType::Raw transaction"
);
continue;
}
TxType::Protocol(protocol_tx) => {
match protocol_tx.tx {
ProtocolTxType::BridgePoolVext
| ProtocolTxType::BridgePool
| ProtocolTxType::ValSetUpdateVext
| ProtocolTxType::ValidatorSetUpdate => (),
ProtocolTxType::EthEventsVext => {
let ext =
ethereum_tx_data_variants::EthEventsVext::try_from(&tx)
.unwrap();
if self
.mode
.get_validator_address()
.map(|validator| {
validator == &ext.data.validator_addr
})
.unwrap_or(false)
{
for event in ext.data.ethereum_events.iter() {
self.mode.dequeue_eth_event(event);
}
}
}
ProtocolTxType::EthereumEvents => {
let digest =
ethereum_tx_data_variants::EthereumEvents::try_from(
&tx,
)
.unwrap();
if let Some(address) =
self.mode.get_validator_address().cloned()
{
let this_signer = &(
address,
self.state.in_mem().get_last_block_height(),
);
for MultiSignedEthEvent { event, signers } in
&digest.events
{
if signers.contains(this_signer) {
self.mode.dequeue_eth_event(event);
}
}
}
}
}
(
DispatchArgs::Protocol(protocol_tx),
TxGasMeter::new(0, gas_scale),
)
}
};
let tx_event = new_tx_event(&tx, height.0);
let is_atomic_batch = tx.header.atomic;
let commitments_len = tx.commitments().len() as u64;
let tx_hash = tx.header_hash();
let tx_gas_meter = RefCell::new(tx_gas_meter);
let dispatch_result = protocol::dispatch_tx(
&tx,
dispatch_args,
&tx_gas_meter,
&mut self.state,
);
let tx_gas_meter = tx_gas_meter.into_inner();
let consumed_gas = tx_gas_meter.get_consumed_gas();
// save the gas cost
self.update_tx_gas(tx_hash, consumed_gas);
if let Some(wrapper_cache) = self.evaluate_tx_result(
response,
dispatch_result,
TxData {
is_atomic_batch,
tx: &tx,
commitments_len,
tx_index,
replay_protection_hashes: None,
tx_gas_meter,
height,
},
TxLogs {
tx_event,
stats,
changed_keys,
},
) {
successful_wrappers.push(wrapper_cache);
}
}
successful_wrappers
}
// Execute the transaction batches for successful wrapper transactions
fn execute_tx_batches(
&mut self,
successful_wrappers: Vec<WrapperCache>,
ExecutionArgs {
response,
changed_keys,
stats,
height,
}: ExecutionArgs<'_>,
) {
for WrapperCache {
mut tx,
tx_index,
gas_meter: tx_gas_meter,
event: tx_event,
tx_result: wrapper_tx_result,
} in successful_wrappers
{
let tx_hash = tx.header_hash();
let is_atomic_batch = tx.header.atomic;
let commitments_len = tx.commitments().len() as u64;
let replay_protection_hashes = Some(ReplayProtectionHashes {
raw_header_hash: tx.raw_header_hash(),
header_hash: tx.header_hash(),
});
// change tx type to raw for execution
tx.update_header(TxType::Raw);
let tx_gas_meter = RefCell::new(tx_gas_meter);
let dispatch_result = protocol::dispatch_tx(
&tx,
DispatchArgs::Raw {
wrapper_hash: Some(&tx_hash),
tx_index: TxIndex::must_from_usize(tx_index),
height,
wrapper_tx_result: Some(wrapper_tx_result),
vp_wasm_cache: &mut self.vp_wasm_cache,
tx_wasm_cache: &mut self.tx_wasm_cache,
},
&tx_gas_meter,
&mut self.state,
);
let tx_gas_meter = tx_gas_meter.into_inner();
let consumed_gas = tx_gas_meter.get_consumed_gas();
// update the gas cost of the corresponding wrapper
self.update_tx_gas(tx_hash, consumed_gas);
self.evaluate_tx_result(
response,
dispatch_result,
TxData {
is_atomic_batch,
tx: &tx,
commitments_len,
tx_index,
replay_protection_hashes,
tx_gas_meter,
height,
},
TxLogs {
tx_event,
stats,
changed_keys,
},
);
}
}
}
struct ExecutionArgs<'finalize> {
response: &'finalize mut shim::response::FinalizeBlock,
changed_keys: &'finalize mut BTreeSet<Key>,
stats: &'finalize mut InternalStats,
height: BlockHeight,
}
// Caches the execution of a wrapper transaction to be used when later executing
// the inner batch
struct WrapperCache {
tx: Tx,
tx_index: usize,
gas_meter: TxGasMeter,
event: Event,
tx_result: namada_sdk::tx::data::TxResult<protocol::Error>,
}
struct TxData<'tx> {
is_atomic_batch: bool,
tx: &'tx Tx,
commitments_len: u64,
tx_index: usize,
replay_protection_hashes: Option<ReplayProtectionHashes>,
tx_gas_meter: TxGasMeter,
height: BlockHeight,
}
struct TxLogs<'finalize> {
tx_event: Event,
stats: &'finalize mut InternalStats,
changed_keys: &'finalize mut BTreeSet<Key>,
}
#[derive(Default)]
struct ValidityFlags {
// Track the need to commit the batch hash for replay protection. Hash
// must be written if at least one of the txs in the batch requires so
commit_batch_hash: bool,
// Track if any of the inner txs failed or was rejected
is_any_tx_invalid: bool,
}
// Temporary support type to update the tx logs. If the tx is confirmed this
// gets merged to the non-temporary type
struct TempTxLogs {
tx_event: Event,
stats: InternalStats,
changed_keys: BTreeSet<Key>,
response_events: Vec<Event>,
}
impl TempTxLogs {
fn new_from_tx_logs(tx_logs: &TxLogs<'_>) -> Self {
Self {
tx_event: Event::new(
tx_logs.tx_event.kind().to_owned(),
tx_logs.tx_event.level().to_owned(),
),
stats: Default::default(),
changed_keys: Default::default(),
response_events: Default::default(),
}
}
}
impl<'finalize> TempTxLogs {
// Consumes the temporary logs and merges them to confirmed ones. Pushes ibc
// and eth events to the finalize block response
fn commit(
self,
logs: &mut TxLogs<'finalize>,
response: &mut shim::response::FinalizeBlock,
) {
logs.tx_event.merge(self.tx_event);
logs.stats.merge(self.stats);
logs.changed_keys.extend(self.changed_keys);
response.events.extend(self.response_events);
}
// Consumes the temporary logs and merges the statistics to confirmed ones.
// This is useful for failing atomic batches
fn commit_stats_only(self, logs: &mut TxLogs<'finalize>) {
logs.stats.merge(self.stats);
}
fn check_inner_results(
&mut self,
tx_result: &mut namada_sdk::tx::data::TxResult<protocol::Error>,
height: BlockHeight,
) -> ValidityFlags {
let mut flags = ValidityFlags::default();