-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathprocess_proposal.rs
More file actions
1884 lines (1764 loc) · 70.1 KB
/
process_proposal.rs
File metadata and controls
1884 lines (1764 loc) · 70.1 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 ['VerifyHeader`], [`ProcessProposal`],
//! and [`RevertProposal`] ABCI++ methods for the Shell
use data_encoding::HEXUPPER;
use namada::hash::Hash;
use namada::ledger::pos::PosQueries;
use namada::proof_of_stake::storage::find_validator_by_raw_hash;
use namada::tx::data::protocol::ProtocolTxType;
use namada::vote_ext::ethereum_tx_data_variants;
use super::block_alloc::{BlockGas, BlockSpace};
use super::*;
use crate::facade::tendermint_proto::v0_37::abci::RequestProcessProposal;
use crate::shell::block_alloc::{AllocFailure, TxBin};
use crate::shims::abcipp_shim_types::shim::response::ProcessProposal;
use crate::shims::abcipp_shim_types::shim::TxBytes;
/// Validation metadata, to keep track of used resources or
/// transaction numbers, in a block proposal.
#[derive(Default)]
pub struct ValidationMeta {
/// Gas emitted by users.
pub user_gas: TxBin<BlockGas>,
/// Space utilized by all txs.
pub txs_bin: TxBin<BlockSpace>,
}
impl<D, H> From<&WlState<D, H>> for ValidationMeta
where
D: 'static + DB + for<'iter> DBIter<'iter>,
H: 'static + StorageHasher,
{
fn from(state: &WlState<D, H>) -> Self {
let max_proposal_bytes =
state.pos_queries().get_max_proposal_bytes().get();
let max_block_gas =
namada::parameters::get_max_block_gas(state).unwrap();
let user_gas = TxBin::init(max_block_gas);
let txs_bin = TxBin::init(max_proposal_bytes);
Self { user_gas, txs_bin }
}
}
impl<D, H> Shell<D, H>
where
D: DB + for<'iter> DBIter<'iter> + Sync + 'static,
H: StorageHasher + Sync + 'static,
{
/// INVARIANT: This method must be stateless.
pub fn verify_header(
&self,
_req: shim::request::VerifyHeader,
) -> shim::response::VerifyHeader {
Default::default()
}
/// Check all the txs in a block. Some txs may be incorrect,
/// but we only reject the entire block if the order of the
/// included txs violates the order decided upon in the previous
/// block.
pub fn process_proposal(
&self,
req: RequestProcessProposal,
) -> (ProcessProposal, Vec<TxResult>) {
tracing::info!(
proposer = ?HEXUPPER.encode(&req.proposer_address),
height = req.height,
hash = ?HEXUPPER.encode(&req.hash),
n_txs = req.txs.len(),
"Received block proposal",
);
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",
)
};
let tx_results = self.process_txs(
&req.txs,
req.time
.expect("Missing timestamp in proposed block")
.try_into()
.expect("Failed conversion of Comet timestamp"),
&native_block_proposer_address,
);
// Erroneous transactions were detected when processing
// the leader's proposal. We allow txs that are invalid at runtime
// (wasm) to reach FinalizeBlock.
let invalid_txs = tx_results.iter().any(|res| {
let error = ResultCode::from_u32(res.code).expect(
"All error codes returned from process_single_tx are valid",
);
!error.is_recoverable()
});
if invalid_txs {
tracing::warn!(
proposer = ?HEXUPPER.encode(&req.proposer_address),
height = req.height,
hash = ?HEXUPPER.encode(&req.hash),
"Found invalid transactions, proposed block will be rejected"
);
}
(
if invalid_txs {
ProcessProposal::Reject
} else {
ProcessProposal::Accept
},
tx_results,
)
}
/// Evaluates the corresponding [`TxResult`] for each tx in the
/// proposal. Additionally, counts the number of digest
/// txs and the bytes used by encrypted txs in the proposal.
///
/// `ProcessProposal` should be able to make a decision on whether a
/// proposed block is acceptable or not based solely on what this
/// function returns.
pub fn process_txs(
&self,
txs: &[TxBytes],
block_time: DateTimeUtc,
block_proposer: &Address,
) -> Vec<TxResult> {
let mut temp_state = self.state.with_temp_write_log();
let mut metadata = ValidationMeta::from(self.state.read_only());
let mut vp_wasm_cache = self.vp_wasm_cache.clone();
let mut tx_wasm_cache = self.tx_wasm_cache.clone();
let tx_results: Vec<_> = txs
.iter()
.map(|tx_bytes| {
let result = self.check_proposal_tx(
tx_bytes,
&mut metadata,
&mut temp_state,
block_time,
&mut vp_wasm_cache,
&mut tx_wasm_cache,
block_proposer,
);
let error_code = ResultCode::from_u32(result.code).unwrap();
if let ResultCode::Ok = error_code {
temp_state.write_log_mut().commit_tx();
} else {
tracing::info!(
"Process proposal rejected an invalid tx. Error code: \
{:?}, info: {}",
error_code,
result.info
);
temp_state.write_log_mut().drop_tx();
}
result
})
.collect();
tx_results
}
/// Checks if the Tx can be deserialized from bytes. Checks the fees and
/// signatures of the fee payer for a transaction if it is a wrapper tx.
///
/// Checks validity of a decrypted tx or that a tx marked un-decryptable
/// is in fact so. Also checks that decrypted txs were submitted in
/// correct order.
///
/// Error codes:
/// 0: Ok
/// 1: Invalid tx
/// 2: Tx is invalidly signed
/// 3: Wasm runtime error
/// 4: Invalid order of decrypted txs
/// 5. More decrypted txs than expected
/// 6. A transaction could not be decrypted
/// 7. An error in the vote extensions included in the proposal
/// 8. Not enough block space was available for some tx
/// 9. Replay attack
///
/// INVARIANT: Any changes applied in this method must be reverted if the
/// proposal is rejected (unless we can simply overwrite them in the
/// next block).
#[allow(clippy::too_many_arguments)]
pub fn check_proposal_tx<CA>(
&self,
tx_bytes: &[u8],
metadata: &mut ValidationMeta,
temp_state: &mut TempWlState<'_, D, H>,
block_time: DateTimeUtc,
vp_wasm_cache: &mut VpCache<CA>,
tx_wasm_cache: &mut TxCache<CA>,
block_proposer: &Address,
) -> TxResult
where
CA: 'static + WasmCacheAccess + Sync,
{
// check tx bytes
//
// NB: always keep this as the first tx check,
// as it is a pretty cheap one
if !validate_tx_bytes(&self.state, tx_bytes.len())
.expect("Failed to get max tx bytes param from storage")
{
return TxResult {
code: ResultCode::TooLarge.into(),
info: "Tx too large".into(),
};
}
// try to allocate space for this tx
if let Err(e) = metadata.txs_bin.try_dump(tx_bytes) {
return TxResult {
code: ResultCode::AllocationError.into(),
info: match e {
AllocFailure::Rejected { .. } => {
"No more space left in the block"
}
AllocFailure::OverflowsBin { .. } => {
"The given tx is larger than the max configured \
proposal size"
}
}
.into(),
};
}
let maybe_tx = Tx::try_from(tx_bytes).map_or_else(
|err| {
tracing::debug!(
?err,
"Couldn't deserialize transaction received during \
PrepareProposal"
);
Err(TxResult {
code: ResultCode::InvalidTx.into(),
info: "The submitted transaction was not deserializable"
.into(),
})
},
|tx| {
let tx_chain_id = tx.header.chain_id.clone();
let tx_expiration = tx.header.expiration;
if let Err(err) = tx.validate_tx() {
// This occurs if the wrapper / protocol tx signature is
// invalid
return Err(TxResult {
code: ResultCode::InvalidSig.into(),
info: err.to_string(),
});
}
Ok((tx_chain_id, tx_expiration, tx))
},
);
let (tx_chain_id, tx_expiration, tx) = match maybe_tx {
Ok(tx) => tx,
Err(tx_result) => return tx_result,
};
if let Err(err) = tx.validate_tx() {
return TxResult {
code: ResultCode::InvalidSig.into(),
info: err.to_string(),
};
}
match tx.header().tx_type {
// If it is a raw transaction, we do no further validation
TxType::Raw => TxResult {
code: ResultCode::InvalidTx.into(),
info: "Transaction rejected: Non-encrypted transactions are \
not supported"
.into(),
},
TxType::Protocol(protocol_tx) => {
// Tx chain id
if tx_chain_id != self.chain_id {
return TxResult {
code: ResultCode::InvalidChainId.into(),
info: format!(
"Tx carries a wrong chain id: expected {}, found \
{}",
self.chain_id, tx_chain_id
),
};
}
// Tx expiration
if let Some(exp) = tx_expiration {
if block_time > exp {
return TxResult {
code: ResultCode::ExpiredTx.into(),
info: format!(
"Tx expired at {:#?}, block time: {:#?}",
exp, block_time
),
};
}
}
match protocol_tx.tx {
ProtocolTxType::EthEventsVext => {
ethereum_tx_data_variants::EthEventsVext::try_from(&tx)
.map_err(|err| err.to_string())
.and_then(|ext| {
validate_eth_events_vext(
&self.state,
&ext.0,
self.state.in_mem().get_last_block_height(),
)
.map(|_| TxResult {
code: ResultCode::Ok.into(),
info: "Process Proposal accepted this \
transaction"
.into(),
})
.map_err(|err| err.to_string())
})
.unwrap_or_else(|err| TxResult {
code: ResultCode::InvalidVoteExtension.into(),
info: format!(
"Process proposal rejected this proposal \
because one of the included Ethereum \
events vote extensions was invalid: {err}"
),
})
}
ProtocolTxType::BridgePoolVext => {
ethereum_tx_data_variants::BridgePoolVext::try_from(&tx)
.map_err(|err| err.to_string())
.and_then(|ext| {
validate_bp_roots_vext(
&self.state,
&ext.0,
self.state.in_mem().get_last_block_height(),
)
.map(|_| TxResult {
code: ResultCode::Ok.into(),
info: "Process Proposal accepted this \
transaction"
.into(),
})
.map_err(|err| err.to_string())
})
.unwrap_or_else(|err| TxResult {
code: ResultCode::InvalidVoteExtension.into(),
info: format!(
"Process proposal rejected this proposal \
because one of the included Bridge pool \
root's vote extensions was invalid: {err}"
),
})
}
ProtocolTxType::ValSetUpdateVext => {
ethereum_tx_data_variants::ValSetUpdateVext::try_from(
&tx,
)
.map_err(|err| err.to_string())
.and_then(|ext| {
validate_valset_upd_vext(
&self.state,
&ext,
// n.b. only accept validator set updates
// issued at
// the current epoch (signing off on the
// validators
// of the next epoch)
self.state.in_mem().get_current_epoch().0,
)
.map(|_| TxResult {
code: ResultCode::Ok.into(),
info: "Process Proposal accepted this \
transaction"
.into(),
})
.map_err(|err| err.to_string())
})
.unwrap_or_else(|err| {
TxResult {
code: ResultCode::InvalidVoteExtension.into(),
info: format!(
"Process proposal rejected this proposal \
because one of the included validator \
set update vote extensions was invalid: \
{err}"
),
}
})
}
ProtocolTxType::EthereumEvents
| ProtocolTxType::BridgePool
| ProtocolTxType::ValidatorSetUpdate => TxResult {
code: ResultCode::InvalidVoteExtension.into(),
info: "Process proposal rejected this proposal \
because one of the included vote extensions \
was invalid: ABCI++ code paths are unreachable \
in Namada"
.to_string(),
},
}
}
TxType::Wrapper(wrapper) => {
// Validate wrapper first
// Account for the tx's resources
let allocated_gas =
metadata.user_gas.try_dump(u64::from(wrapper.gas_limit));
let gas_scale = match get_gas_scale(temp_state) {
Ok(scale) => scale,
Err(_) => {
return TxResult {
code: ResultCode::TxGasLimit.into(),
info: "Failed to get gas scale".to_owned(),
};
}
};
let gas_limit = match wrapper.gas_limit.as_scaled_gas(gas_scale)
{
Ok(value) => value,
Err(_) => {
return TxResult {
code: ResultCode::InvalidTx.into(),
info: "The wrapper gas limit overflowed gas \
representation"
.to_owned(),
};
}
};
let mut tx_gas_meter = TxGasMeter::new(gas_limit);
if tx_gas_meter.add_wrapper_gas(tx_bytes).is_err()
|| allocated_gas.is_err()
{
return TxResult {
code: ResultCode::TxGasLimit.into(),
info: "Wrapper transactions exceeds its gas limit"
.to_string(),
};
}
// ChainId check
if tx_chain_id != self.chain_id {
return TxResult {
code: ResultCode::InvalidChainId.into(),
info: format!(
"Tx carries a wrong chain id: expected {}, found \
{}",
self.chain_id, tx_chain_id
),
};
}
// Tx expiration
if let Some(exp) = tx_expiration {
if block_time > exp {
return TxResult {
code: ResultCode::ExpiredTx.into(),
info: format!(
"Tx expired at {:#?}, block time: {:#?}",
exp, block_time
),
};
}
}
// Replay protection checks
if let Err(e) = super::replay_protection_checks(&tx, temp_state)
{
return TxResult {
code: ResultCode::ReplayTx.into(),
info: e.to_string(),
};
}
// Check that the fee payer has sufficient balance.
if let Err(e) = process_proposal_fee_check(
&wrapper,
tx.header_hash(),
block_proposer,
&mut ShellParams::new(
&RefCell::new(tx_gas_meter),
temp_state,
vp_wasm_cache,
tx_wasm_cache,
),
) {
return TxResult {
code: ResultCode::FeeError.into(),
info: e.to_string(),
};
}
for cmt in tx.commitments() {
// Tx allowlist
if let Err(err) =
check_tx_allowed(&tx.batch_ref_tx(cmt), &self.state)
{
return TxResult {
code: ResultCode::TxNotAllowlisted.into(),
info: format!(
"Tx code didn't pass the allowlist check: {}",
err
),
};
}
}
TxResult {
code: ResultCode::Ok.into(),
info: "Process proposal accepted this transaction".into(),
}
}
}
}
pub fn revert_proposal(
&mut self,
_req: shim::request::RevertProposal,
) -> shim::response::RevertProposal {
Default::default()
}
}
// TODO(namada#2597): check masp fee payment if required
fn process_proposal_fee_check<D, H, CA>(
wrapper: &WrapperTx,
wrapper_tx_hash: Hash,
proposer: &Address,
shell_params: &mut ShellParams<'_, TempWlState<'_, D, H>, D, H, CA>,
) -> Result<()>
where
D: DB + for<'iter> DBIter<'iter> + Sync + 'static,
H: StorageHasher + Sync + 'static,
CA: 'static + WasmCacheAccess + Sync,
{
let minimum_gas_price = namada::ledger::parameters::read_gas_cost(
shell_params.state,
&wrapper.fee.token,
)
.expect("Must be able to read gas cost parameter")
.ok_or(Error::TxApply(protocol::Error::FeeError(format!(
"The provided {} token is not allowed for fee payment",
wrapper.fee.token
))))?;
fee_data_check(wrapper, minimum_gas_price, shell_params)?;
protocol::transfer_fee(
shell_params.state,
proposer,
wrapper,
wrapper_tx_hash,
)
.map_err(Error::TxApply)
}
/// We test the failure cases of [`process_proposal`]. The happy flows
/// are covered by the e2e tests.
// TODO(namada#3249): write tests for validator set update vote extensions in
// process proposals
#[cfg(test)]
mod test_process_proposal {
use namada::core::key::*;
use namada::eth_bridge::storage::eth_bridge_queries::{
is_bridge_comptime_enabled, EthBridgeQueries,
};
use namada::state::StorageWrite;
use namada::token::{read_denom, Amount, DenominatedAmount};
use namada::tx::data::Fee;
use namada::tx::{Authorization, Code, Data, Signed};
use namada::vote_ext::{
bridge_pool_roots, ethereum_events, validator_set_update,
};
use namada::{address, replay_protection};
use namada_apps_lib::wallet;
use super::*;
use crate::shell::test_utils::{
deactivate_bridge, gen_keypair, get_bp_bytes_to_sign, ProcessProposal,
TestError, TestShell,
};
use crate::shims::abcipp_shim_types::shim::request::ProcessedTx;
const GAS_LIMIT_MULTIPLIER: u64 = 100_000;
/// Check that we reject a validator set update protocol tx
/// if the bridge is not active.
#[test]
fn check_rejected_valset_upd_bridge_inactive() {
if is_bridge_comptime_enabled() {
// NOTE: validator set updates are always signed
// when the bridge is enabled at compile time
return;
}
let (shell, _, _, _) = test_utils::setup_at_height(3);
let ext = {
let eth_hot_key =
shell.mode.get_eth_bridge_keypair().expect("Test failed");
let signing_epoch = shell.state.in_mem().get_current_epoch().0;
let next_epoch = signing_epoch.next();
let voting_powers = shell
.state
.ethbridge_queries()
.get_consensus_eth_addresses(Some(next_epoch))
.iter()
.map(|(eth_addr_book, _, voting_power)| {
(eth_addr_book, voting_power)
})
.collect();
let validator_addr = shell
.mode
.get_validator_address()
.expect("Test failed")
.clone();
let ext = validator_set_update::Vext {
voting_powers,
validator_addr,
signing_epoch,
};
ext.sign(eth_hot_key)
};
let request = {
let protocol_key =
shell.mode.get_protocol_key().expect("Test failed");
let tx = EthereumTxData::ValSetUpdateVext(ext)
.sign(protocol_key, shell.chain_id.clone())
.to_bytes();
ProcessProposal { txs: vec![tx] }
};
let response = if let Err(TestError::RejectProposal(resp)) =
shell.process_proposal(request)
{
if let [resp] = resp.as_slice() {
resp.clone()
} else {
panic!("Test failed")
}
} else {
panic!("Test failed")
};
assert_eq!(
response.result.code,
u32::from(ResultCode::InvalidVoteExtension)
);
}
/// Check that we reject an eth events protocol tx
/// if the bridge is not active.
#[test]
fn check_rejected_eth_events_bridge_inactive() {
let (mut shell, _, _, _) = test_utils::setup_at_height(3);
let protocol_key = shell.mode.get_protocol_key().expect("Test failed");
let addr = shell.mode.get_validator_address().expect("Test failed");
let event = EthereumEvent::TransfersToNamada {
nonce: 0u64.into(),
transfers: vec![],
};
let ext = ethereum_events::Vext {
validator_addr: addr.clone(),
block_height: shell.state.in_mem().get_last_block_height(),
ethereum_events: vec![event],
}
.sign(protocol_key);
let tx = EthereumTxData::EthEventsVext(ext.into())
.sign(protocol_key, shell.chain_id.clone())
.to_bytes();
let request = ProcessProposal { txs: vec![tx] };
if is_bridge_comptime_enabled() {
let [resp]: [ProcessedTx; 1] = shell
.process_proposal(request.clone())
.expect("Test failed")
.try_into()
.expect("Test failed");
assert_eq!(resp.result.code, u32::from(ResultCode::Ok));
deactivate_bridge(&mut shell);
}
let response = if let Err(TestError::RejectProposal(resp)) =
shell.process_proposal(request)
{
if let [resp] = resp.as_slice() {
resp.clone()
} else {
panic!("Test failed")
}
} else {
panic!("Test failed")
};
assert_eq!(
response.result.code,
u32::from(ResultCode::InvalidVoteExtension)
);
}
/// Check that we reject an bp roots protocol tx
/// if the bridge is not active.
#[test]
fn check_rejected_bp_roots_bridge_inactive() {
let (mut shell, _a, _b, _c) = test_utils::setup_at_height(1);
shell.state.in_mem_mut().block.height =
shell.state.in_mem().get_last_block_height();
shell.commit();
let protocol_key = shell.mode.get_protocol_key().expect("Test failed");
let addr = shell.mode.get_validator_address().expect("Test failed");
let to_sign = get_bp_bytes_to_sign();
let sig = Signed::<_, SignableEthMessage>::new(
shell.mode.get_eth_bridge_keypair().expect("Test failed"),
to_sign,
)
.sig;
let vote_ext = bridge_pool_roots::Vext {
block_height: shell.state.in_mem().get_last_block_height(),
validator_addr: addr.clone(),
sig,
}
.sign(shell.mode.get_protocol_key().expect("Test failed"));
let tx = EthereumTxData::BridgePoolVext(vote_ext)
.sign(protocol_key, shell.chain_id.clone())
.to_bytes();
let request = ProcessProposal { txs: vec![tx] };
if is_bridge_comptime_enabled() {
let [resp]: [ProcessedTx; 1] = shell
.process_proposal(request.clone())
.expect("Test failed")
.try_into()
.expect("Test failed");
assert_eq!(resp.result.code, u32::from(ResultCode::Ok));
deactivate_bridge(&mut shell);
}
let response = if let Err(TestError::RejectProposal(resp)) =
shell.process_proposal(request)
{
if let [resp] = resp.as_slice() {
resp.clone()
} else {
panic!("Test failed")
}
} else {
panic!("Test failed")
};
assert_eq!(
response.result.code,
u32::from(ResultCode::InvalidVoteExtension)
);
}
fn check_rejected_eth_events(
shell: &mut TestShell,
vote_extension: ethereum_events::SignedVext,
protocol_key: common::SecretKey,
) {
let tx = EthereumTxData::EthEventsVext(vote_extension)
.sign(&protocol_key, shell.chain_id.clone())
.to_bytes();
let request = ProcessProposal { txs: vec![tx] };
let response = if let Err(TestError::RejectProposal(resp)) =
shell.process_proposal(request)
{
if let [resp] = resp.as_slice() {
resp.clone()
} else {
panic!("Test failed")
}
} else {
panic!("Test failed")
};
assert_eq!(
response.result.code,
u32::from(ResultCode::InvalidVoteExtension)
);
}
/// Test that if a proposal contains Ethereum events with
/// invalid validator signatures, we reject it.
#[test]
fn test_drop_vext_with_invalid_sigs() {
const LAST_HEIGHT: BlockHeight = BlockHeight(2);
let (mut shell, _recv, _, _) = test_utils::setup_at_height(LAST_HEIGHT);
let (protocol_key, _) = wallet::defaults::validator_keys();
let addr = wallet::defaults::validator_address();
let event = EthereumEvent::TransfersToNamada {
nonce: 0u64.into(),
transfers: vec![],
};
let ext = {
// generate a valid signature
#[allow(clippy::redundant_clone)]
let mut ext = ethereum_events::Vext {
validator_addr: addr.clone(),
block_height: LAST_HEIGHT,
ethereum_events: vec![event.clone()],
}
.sign(&protocol_key);
assert!(ext.verify(&protocol_key.ref_to()).is_ok());
// modify this signature such that it becomes invalid
ext.sig = test_utils::invalidate_signature(ext.sig);
ext
};
check_rejected_eth_events(&mut shell, ext.into(), protocol_key);
}
/// Test that if a proposal contains Ethereum events with
/// invalid block heights, we reject it.
#[test]
fn test_drop_vext_with_invalid_bheights() {
const LAST_HEIGHT: BlockHeight = BlockHeight(3);
const INVALID_HEIGHT: BlockHeight = BlockHeight(LAST_HEIGHT.0 + 1);
let (mut shell, _recv, _, _) = test_utils::setup_at_height(LAST_HEIGHT);
let (protocol_key, _) = wallet::defaults::validator_keys();
let addr = wallet::defaults::validator_address();
let event = EthereumEvent::TransfersToNamada {
nonce: 0u64.into(),
transfers: vec![],
};
let ext = {
#[allow(clippy::redundant_clone)]
let ext = ethereum_events::Vext {
validator_addr: addr.clone(),
block_height: INVALID_HEIGHT,
ethereum_events: vec![event.clone()],
}
.sign(&protocol_key);
assert!(ext.verify(&protocol_key.ref_to()).is_ok());
ext
};
check_rejected_eth_events(&mut shell, ext.into(), protocol_key);
}
/// Test that if a proposal contains Ethereum events with
/// invalid validators, we reject it.
#[test]
fn test_drop_vext_with_invalid_validators() {
const LAST_HEIGHT: BlockHeight = BlockHeight(2);
let (mut shell, _recv, _, _) = test_utils::setup_at_height(LAST_HEIGHT);
let (addr, protocol_key) = {
let bertha_key = wallet::defaults::bertha_keypair();
let bertha_addr = wallet::defaults::bertha_address();
(bertha_addr, bertha_key)
};
let event = EthereumEvent::TransfersToNamada {
nonce: 0u64.into(),
transfers: vec![],
};
let ext = {
#[allow(clippy::redundant_clone)]
let ext = ethereum_events::Vext {
validator_addr: addr.clone(),
block_height: LAST_HEIGHT,
ethereum_events: vec![event.clone()],
}
.sign(&protocol_key);
assert!(ext.verify(&protocol_key.ref_to()).is_ok());
ext
};
check_rejected_eth_events(&mut shell, ext.into(), protocol_key);
}
/// Test that if a wrapper tx is not signed, the block is rejected
/// by [`process_proposal`].
#[test]
fn test_unsigned_wrapper_rejected() {
let (shell, _recv, _, _) = test_utils::setup_at_height(3u64);
let keypair = gen_keypair();
let public_key = keypair.ref_to();
let mut outer_tx =
Tx::from_type(TxType::Wrapper(Box::new(WrapperTx::new(
Fee {
amount_per_gas_unit: DenominatedAmount::native(
Default::default(),
),
token: shell.state.in_mem().native_token.clone(),
},
public_key,
GAS_LIMIT_MULTIPLIER.into(),
))));
outer_tx.header.chain_id = shell.chain_id.clone();
outer_tx.set_code(Code::new("wasm_code".as_bytes().to_owned(), None));
outer_tx.set_data(Data::new("transaction data".as_bytes().to_owned()));
let tx = outer_tx.to_bytes();
let response = {
let request = ProcessProposal { txs: vec![tx] };
if let Err(TestError::RejectProposal(resp)) =
shell.process_proposal(request)
{
if let [resp] = resp.as_slice() {
resp.clone()
} else {
panic!("Test failed")
}
} else {
panic!("Test failed")
}
};
println!("{}", response.result.info);
assert_eq!(response.result.code, u32::from(ResultCode::InvalidSig));
assert_eq!(
response.result.info,
String::from(
"WrapperTx signature verification failed: The wrapper \
signature is invalid."
)
);
}
/// Test that a block including a wrapper tx with invalid signature is
/// rejected
#[test]
fn test_wrapper_bad_signature_rejected() {
let (shell, _recv, _, _) = test_utils::setup_at_height(3u64);
let keypair = gen_keypair();
let mut outer_tx =
Tx::from_type(TxType::Wrapper(Box::new(WrapperTx::new(
Fee {
amount_per_gas_unit: DenominatedAmount::native(
Amount::from_uint(100, 0).expect("Test failed"),
),
token: shell.state.in_mem().native_token.clone(),
},
keypair.ref_to(),
GAS_LIMIT_MULTIPLIER.into(),
))));
outer_tx.header.chain_id = shell.chain_id.clone();
outer_tx.set_code(Code::new("wasm_code".as_bytes().to_owned(), None));
outer_tx.set_data(Data::new("transaction data".as_bytes().to_owned()));
outer_tx.add_section(Section::Authorization(Authorization::new(
outer_tx.sechashes(),
[(0, keypair)].into_iter().collect(),
None,
)));
let mut new_tx = outer_tx.clone();
if let TxType::Wrapper(wrapper) = &mut new_tx.header.tx_type {
// we mount a malleability attack to try and remove the fee
wrapper.fee.amount_per_gas_unit =
DenominatedAmount::native(Default::default());
} else {
panic!("Test failed")
};
let request = ProcessProposal {
txs: vec![new_tx.to_bytes()],
};
match shell.process_proposal(request) {
Ok(_) => panic!("Test failed"),
Err(TestError::RejectProposal(response)) => {
let response = if let [response] = response.as_slice() {
response.clone()
} else {
panic!("Test failed")
};
let expected_error = "WrapperTx signature verification \
failed: The wrapper signature is \
invalid.";
assert_eq!(
response.result.code,
u32::from(ResultCode::InvalidSig)
);
assert!(
response.result.info.contains(expected_error),
"Result info {} doesn't contain the expected error {}",
response.result.info,
expected_error
);
}
}
}
/// Test that if the account submitting the tx is not known and the fee is
/// non-zero, [`process_proposal`] rejects that block
#[test]
fn test_wrapper_unknown_address() {
let (mut shell, _recv, _, _) = test_utils::setup_at_height(3u64);
let keypair = gen_keypair();
// reduce address balance to match the 100 token min fee
let balance_key = token::storage_key::balance_key(
&shell.state.in_mem().native_token,
&Address::from(&keypair.ref_to()),
);
shell
.state
.write(&balance_key, Amount::native_whole(99))
.unwrap();
let keypair = gen_keypair();
let mut outer_tx =
Tx::from_type(TxType::Wrapper(Box::new(WrapperTx::new(
Fee {
amount_per_gas_unit: DenominatedAmount::native(
Amount::from_uint(1, 0).expect("Test failed"),