forked from lambdaclass/ethrex
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheip8141_tests.rs
More file actions
3455 lines (3208 loc) · 124 KB
/
Copy patheip8141_tests.rs
File metadata and controls
3455 lines (3208 loc) · 124 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
//! EIP-8141: Frame Transactions
//!
//! Shared test harness for frame-transaction execution plus regression tests
//! for the per-tx state-rollback invariant:
//!
//! `VM::execute()` returning `Err` => `db.current_accounts_state` is
//! unchanged from before the tx, exactly like non-frame txs.
//!
//! The helpers in this module (`run_frame_tx`, `assert_db_cache_unchanged`,
//! `frame_tx_with_frames`, and the bytecode constants) are reused by the
//! later EIP-8141 task tests.
use bytes::Bytes;
use ethrex_blockchain::vm::StoreVmDatabase;
use ethrex_common::types::{
Account, BlockHeader, Code, FRAME_RECEIPT_STATUS_SUCCESS, Fork, Frame, FrameMode,
FrameTransaction, Transaction,
};
use ethrex_common::{Address, H256, U256, constants::EMPTY_TRIE_HASH};
use ethrex_crypto::NativeCrypto;
use ethrex_levm::db::gen_db::GeneralizedDatabase;
use ethrex_levm::environment::{EVMConfig, Environment};
use ethrex_levm::errors::TxResult;
use ethrex_levm::errors::{ExecutionReport, VMError};
use ethrex_levm::tracing::LevmCallTracer;
use ethrex_levm::vm::{VM, VMType};
use ethrex_storage::Store;
use ethrex_vm::DynVmDatabase;
use rustc_hash::FxHashMap;
use std::sync::Arc;
// ==================== Harness constants ====================
/// Chain id used by every harness-built frame transaction.
const HARNESS_CHAIN_ID: u64 = 1;
/// Fixed, funded sender for frame txs built via `frame_tx_with_frames`.
/// Must be non-zero to pass `validate_static_constraints`.
const FUNDED_SENDER: Address = Address::repeat_byte(0xAA);
/// Balance used when `run_frame_tx` auto-seeds the sender (i.e. when the caller
/// did not pass the sender in `accounts`). Kept as a constant so the rollback
/// assertion can verify the sender against the exact value it was seeded with.
const AUTO_SEED_SENDER_BALANCE: U256 = U256::MAX;
/// Harness base fee. `frame_tx_with_frames` sets `max_fee_per_gas` well above it.
const HARNESS_BASE_FEE: u64 = 1;
/// Coinbase used by the harness env (the `..Default::default()` zero address).
/// Fee tests read its post-execution balance to assert value conservation.
#[allow(dead_code)]
const COINBASE_ADDR: Address = Address::zero();
// Bytecodes used by frame-tx tests (shared with later tasks).
/// SSTORE 1@0; APPROVE(scope=3).
#[allow(dead_code)]
const WALLET_APPROVE_CODE: &[u8] = &[
0x60, 0x01, 0x60, 0x00, 0x55, 0x60, 0x03, 0x60, 0x00, 0x60, 0x00, 0xAA,
];
/// SSTORE 1@0; REVERT.
#[allow(dead_code)]
const SSTORE_THEN_REVERT_CODE: &[u8] =
&[0x60, 0x01, 0x60, 0x00, 0x55, 0x60, 0x00, 0x60, 0x00, 0xFD];
/// SSTORE 1@0; STOP.
const SSTORE_THEN_STOP_CODE: &[u8] = &[0x60, 0x01, 0x60, 0x00, 0x55, 0x00];
/// APPROVE(scope=2) -- sender (execution) approval. Must run in a frame whose
/// target IS the tx sender, otherwise scope 2 reverts (frame_target != sender).
#[allow(dead_code)]
const APPROVE_EXECUTION_CODE: &[u8] = &[0x60, 0x02, 0x60, 0x00, 0x60, 0x00, 0xAA];
/// APPROVE(scope=1) -- payment approval. The frame's target becomes the payer.
#[allow(dead_code)]
const APPROVE_PAYMENT_CODE: &[u8] = &[0x60, 0x01, 0x60, 0x00, 0x60, 0x00, 0xAA];
/// APPROVE(scope=3) only (no SSTORE) -- sets sender_approved AND payer when the
/// frame target is the tx sender. Safe to run in a static VERIFY frame.
#[allow(dead_code)]
const APPROVE_BOTH_CODE: &[u8] = &[0x60, 0x03, 0x60, 0x00, 0x60, 0x00, 0xAA];
/// PUSH1 0; PUSH1 0; REVERT -- a clean revert with no state op (so it reverts
/// even inside a static VERIFY frame, rather than halting on a static violation).
#[allow(dead_code)]
const PURE_REVERT_CODE: &[u8] = &[0x60, 0x00, 0x60, 0x00, 0xFD];
// ==================== Harness helpers ====================
/// A seeded account spec: (address, balance, nonce, code).
type SeededAccount = (Address, U256, u64, Bytes);
/// Build a `GeneralizedDatabase` whose cache is seeded with `accounts`.
fn seeded_db(accounts: &[SeededAccount]) -> GeneralizedDatabase {
// The store type doesn't matter: every account we touch lives in the cache.
let in_memory_db = Store::new("", ethrex_storage::EngineType::InMemory).unwrap();
let header = BlockHeader {
state_root: *EMPTY_TRIE_HASH,
..Default::default()
};
let store: DynVmDatabase = Box::new(StoreVmDatabase::new(in_memory_db, header).unwrap());
let mut cache: FxHashMap<Address, Account> = FxHashMap::default();
for (address, balance, nonce, code) in accounts {
cache.insert(
*address,
Account::new(
*balance,
Code::from_bytecode(code.clone(), &NativeCrypto),
*nonce,
FxHashMap::default(),
),
);
}
GeneralizedDatabase::new_with_account_state(Arc::new(store), cache)
}
/// Build the execution `Environment` for a frame tx at Hegota.
fn frame_tx_env(tx: &FrameTransaction) -> Environment {
Environment {
origin: tx.sender,
gas_limit: tx.total_gas_limit(),
block_gas_limit: (i64::MAX - 1) as u64,
config: EVMConfig::new(Fork::Hegota, EVMConfig::canonical_values(Fork::Hegota)),
chain_id: U256::from(HARNESS_CHAIN_ID),
base_fee_per_gas: U256::from(HARNESS_BASE_FEE),
// NOTE: gas_price here is max_fee_per_gas, NOT the effective price.
// Fine for tests that don't assert on fee amounts. Tests that check
// payer balances MUST use `run_frame_tx_with_fees`, which derives the
// effective price min(base+priority, max_fee) like production.
gas_price: U256::from(tx.max_fee_per_gas),
tx_nonce: tx.nonce,
..Default::default()
}
}
/// Build a frame transaction wrapping `frames`, with sane harness defaults:
/// harness chain id, nonce 0, sender = `FUNDED_SENDER`, fees above the harness
/// base fee, and an empty signature list.
fn frame_tx_with_frames(frames: Vec<Frame>) -> FrameTransaction {
FrameTransaction {
chain_id: HARNESS_CHAIN_ID,
nonce: 0,
sender: FUNDED_SENDER,
frames,
signatures: Vec::new(),
max_priority_fee_per_gas: 1,
max_fee_per_gas: HARNESS_BASE_FEE + 1_000,
max_fee_per_blob_gas: U256::zero(),
blob_versioned_hashes: Vec::new(),
inner_hash: Default::default(),
cached_canonical: Default::default(),
}
}
/// Seed `accounts`, execute `tx` via a fresh VM at Hegota, and return the
/// execution result together with the (post-execution) database so callers can
/// inspect `current_accounts_state` (balances, nonces, storage).
///
/// The sender is auto-seeded with a large balance and nonce 0 if it is not
/// already present in `accounts`, so frame txs that do not exercise the sender
/// account still pass nonce/fee validation.
fn run_frame_tx(
accounts: &[SeededAccount],
tx: FrameTransaction,
) -> (Result<ExecutionReport, VMError>, GeneralizedDatabase) {
let mut seeded: Vec<SeededAccount> = accounts.to_vec();
if !seeded.iter().any(|(addr, ..)| *addr == tx.sender) {
seeded.push((tx.sender, AUTO_SEED_SENDER_BALANCE, tx.nonce, Bytes::new()));
}
let mut db = seeded_db(&seeded);
let env = frame_tx_env(&tx);
let transaction = Transaction::FrameTransaction(tx);
let result = {
let mut vm = VM::new(
env,
&mut db,
&transaction,
LevmCallTracer::disabled(),
VMType::L1,
&NativeCrypto,
)
.expect("VM::new should succeed for a frame tx");
vm.execute()
};
(result, db)
}
/// Like `run_frame_tx`, but builds the env with the given block `base_fee`
/// instead of `HARNESS_BASE_FEE`. The env's effective `gas_price` is derived
/// from the tx the same way production does (`calculate_gas_price_for_tx`):
/// `min(base_fee + max_priority_fee_per_gas, max_fee_per_gas)`. Used by fee
/// tests that need a real base-fee/effective-price spread.
fn run_frame_tx_with_fees(
accounts: &[SeededAccount],
tx: FrameTransaction,
base_fee: u64,
) -> (Result<ExecutionReport, VMError>, GeneralizedDatabase) {
let mut seeded: Vec<SeededAccount> = accounts.to_vec();
if !seeded.iter().any(|(addr, ..)| *addr == tx.sender) {
seeded.push((tx.sender, AUTO_SEED_SENDER_BALANCE, tx.nonce, Bytes::new()));
}
let mut db = seeded_db(&seeded);
let mut env = frame_tx_env(&tx);
env.base_fee_per_gas = U256::from(base_fee);
// Effective gas price, matching production `calculate_gas_price_for_tx`.
let effective = base_fee
.saturating_add(tx.max_priority_fee_per_gas)
.min(tx.max_fee_per_gas);
env.gas_price = U256::from(effective);
let transaction = Transaction::FrameTransaction(tx);
let result = {
let mut vm = VM::new(
env,
&mut db,
&transaction,
LevmCallTracer::disabled(),
VMType::L1,
&NativeCrypto,
)
.expect("VM::new should succeed for a frame tx");
vm.execute()
};
(result, db)
}
/// Read the current balance of `addr` from the post-execution cache.
#[allow(dead_code)]
fn balance_of(db: &GeneralizedDatabase, addr: Address) -> U256 {
db.current_accounts_state
.get(&addr)
.map(|account| account.info.balance)
.unwrap_or_default()
}
/// Read the current nonce of `addr` from the post-execution cache.
#[allow(dead_code)]
fn nonce_of(db: &GeneralizedDatabase, addr: Address) -> u64 {
db.current_accounts_state
.get(&addr)
.map(|account| account.info.nonce)
.unwrap_or_default()
}
/// A VERIFY frame targeting `target` (gas_limit 100_000, no value, no data).
/// The target's code runs and may call APPROVE.
///
/// flags 0x03 permits scopes 1/2/3 so the frame's APPROVE code can grant
/// execution and/or payment; flags 0 (APPROVE_SCOPE_NONE) would correctly halt
/// every APPROVE (see `approve_halts_when_frame_scope_is_none`).
#[allow(dead_code)]
fn verify_frame(target: Address) -> Frame {
Frame {
mode: u8::from(FrameMode::Verify),
flags: 0x03,
target: Some(target),
gas_limit: 100_000,
value: U256::zero(),
data: Bytes::new(),
}
}
/// Assert that no seeded account's info (balance/nonce/code) or storage in
/// `db.current_accounts_state` differs from its seeded value. This is THE rollback
/// invariant: after an invalid tx the shared cache must show no residue.
///
/// The sender (`FUNDED_SENDER`) is ALWAYS verified, even when the caller does
/// not list it in `accounts`: `run_frame_tx` auto-seeds it, and a leaked sender
/// nonce/balance on the invalid-tx path (e.g. an APPROVE nonce bump that was not
/// rolled back) is exactly the kind of residue this invariant must prevent. When the caller
/// passes the sender explicitly, those values are used; otherwise the auto-seed
/// defaults (`AUTO_SEED_SENDER_BALANCE`, nonce 0) are checked.
///
/// Slot 0 of each seeded account is checked explicitly because the harness
/// bytecodes write slot 0; a leftover `1` there is the rollback regression signature.
fn assert_db_cache_unchanged(db: &GeneralizedDatabase, accounts: &[SeededAccount]) {
// Always include the auto-seeded sender so a leaked sender balance/nonce is
// caught, mirroring `run_frame_tx`'s auto-seed.
let mut checked: Vec<SeededAccount> = accounts.to_vec();
if !checked.iter().any(|(addr, ..)| *addr == FUNDED_SENDER) {
checked.push((FUNDED_SENDER, AUTO_SEED_SENDER_BALANCE, 0, Bytes::new()));
}
for (address, balance, nonce, code) in &checked {
let current = db
.current_accounts_state
.get(address)
.unwrap_or_else(|| panic!("seeded account {address:?} missing from cache"));
assert_eq!(
current.info.balance, *balance,
"balance of {address:?} changed after invalid tx",
);
assert_eq!(
current.info.nonce, *nonce,
"nonce of {address:?} changed after invalid tx",
);
assert_eq!(
current.info.code_hash,
Code::from_bytecode(code.clone(), &NativeCrypto).hash,
"code of {address:?} changed after invalid tx",
);
// Every storage slot present in the cache for this account must be its
// seeded value (the seeded accounts start with empty storage, so any
// non-zero value is residue). Slot 0 is the one the harness bytecodes
// touch, so a residual `1` here is the rollback regression signature.
for (slot, value) in current.storage.iter() {
assert!(
value.is_zero(),
"storage residue at {address:?} slot {slot:?} = {value:?} after invalid tx",
);
}
}
}
// ==================== Invalid-tx rollback ====================
#[test]
fn invalid_frame_tx_leaves_db_cache_clean() {
// One DEFAULT frame to a contract that SSTOREs and succeeds, but NO APPROVE
// anywhere -> payer is None -> tx invalid AFTER the frame committed state.
let target = Address::from_low_u64_be(0xC0);
let accounts = [(
target,
U256::zero(),
0u64,
Bytes::from(SSTORE_THEN_STOP_CODE.to_vec()),
)];
let tx = frame_tx_with_frames(vec![Frame {
mode: u8::from(FrameMode::Default),
flags: 0,
target: Some(target),
gas_limit: 100_000,
value: U256::zero(),
data: Bytes::new(),
}]);
let (result, db) = run_frame_tx(&accounts, tx);
assert!(
matches!(
result,
Err(VMError::TxValidation(
ethrex_levm::errors::TxValidationError::InvalidFrameTransaction
))
),
"expected InvalidFrameTransaction, got {result:?}",
);
// Slot 0 of target must NOT be 1 — the frame's SSTORE must have been rolled back.
assert_db_cache_unchanged(&db, &accounts);
}
// ==================== Reverting SENDER frame must not leak value ====================
#[test]
fn reverting_sender_frame_returns_value() {
let target = Address::from_low_u64_be(0xC1); // contract that SSTOREs then REVERTs
let wallet = Address::from_low_u64_be(0xC2); // separate payer
let value = U256::from(1_000_000u64);
// Frame 0: VERIFY to the sender -> APPROVE scope 2 (sender_approved).
// Scope 2 requires frame_target == tx.sender, so it must target
// FUNDED_SENDER and run from FUNDED_SENDER's code.
// Frame 1: VERIFY to the wallet -> APPROVE scope 1 (payer = wallet), so the
// sender pays no gas and its balance is untouched except for the
// (to-be-reverted) value transfer.
// Frame 2: SENDER to a reverting contract carrying `value`.
let tx = frame_tx_with_frames(vec![
verify_frame(FUNDED_SENDER),
verify_frame(wallet),
Frame {
mode: u8::from(FrameMode::Sender),
flags: 0,
target: Some(target),
gas_limit: 100_000,
value,
data: Bytes::new(),
},
]);
let (result, db) = run_frame_tx(
&[
// Sender carries the execution-approval code; pass it explicitly so
// its balance equals AUTO_SEED_SENDER_BALANCE for the assertion.
(
FUNDED_SENDER,
AUTO_SEED_SENDER_BALANCE,
0,
Bytes::from(APPROVE_EXECUTION_CODE.to_vec()),
),
(
wallet,
U256::from(10u64).pow(U256::from(18u64)),
0,
Bytes::from(APPROVE_PAYMENT_CODE.to_vec()),
),
(
target,
U256::zero(),
0,
Bytes::from(SSTORE_THEN_REVERT_CODE.to_vec()),
),
],
tx,
);
let report = result.expect("tx is valid (payer approved); only the SENDER frame failed");
// The reverting frame must NOT have delivered value: target keeps nothing,
// and the value is returned to the sender (sender pays no gas — wallet is payer).
assert_eq!(
balance_of(&db, target),
U256::zero(),
"reverted frame leaked value to target"
);
assert_eq!(
balance_of(&db, FUNDED_SENDER),
AUTO_SEED_SENDER_BALANCE,
"sender did not get value back"
);
// The SENDER frame (index 2) must be reported as a failure.
let frame_results = report
.frame_results
.expect("frame tx report must carry per-frame results");
assert_eq!(
frame_results[2].0,
ethrex_common::types::FRAME_RECEIPT_STATUS_FAILURE,
"SENDER frame should be reported as failure"
);
}
// ==================== Payer charged at effective price (no burn) ====================
#[test]
fn payer_pays_effective_price_no_burn() {
// base_fee = 10 gwei, priority = 2, max_fee = 100 gwei (huge headroom).
// effective = base + priority = 12 gwei. The (100-12) spread must NOT burn.
let wallet = Address::from_low_u64_be(0xD2);
let stop_contract = Address::from_low_u64_be(0xD3);
let wallet_initial = U256::from(10u64).pow(U256::from(18u64)); // 1 ETH
let mut tx = frame_tx_with_frames(vec![
verify_frame(FUNDED_SENDER), // runs APPROVE_EXECUTION_CODE -> seed below
verify_frame(wallet), // runs APPROVE_PAYMENT_CODE -> seed below
Frame {
mode: u8::from(FrameMode::Sender),
flags: 0,
target: Some(stop_contract),
gas_limit: 30_000,
value: U256::zero(),
data: Bytes::new(),
},
]);
tx.max_fee_per_gas = 100_000_000_000; // 100 gwei
tx.max_priority_fee_per_gas = 2_000_000_000; // 2 gwei
let (result, db) = run_frame_tx_with_fees(
&[
(
FUNDED_SENDER,
AUTO_SEED_SENDER_BALANCE,
0,
Bytes::from(APPROVE_EXECUTION_CODE.to_vec()),
),
(
wallet,
wallet_initial,
0,
Bytes::from(APPROVE_PAYMENT_CODE.to_vec()),
),
(stop_contract, U256::zero(), 0, Bytes::from(vec![0x00u8])), // STOP
],
tx,
10_000_000_000, // base fee 10 gwei
);
let report = result.expect("valid: sender approved, payer set");
let effective = U256::from(12_000_000_000u64);
let total_gas_used = U256::from(report.gas_used);
// Net payer cost == effective * total_gas_used (no max-vs-effective burn).
let payer_delta = wallet_initial - balance_of(&db, wallet);
assert_eq!(
payer_delta,
effective * total_gas_used,
"payer overcharged/undercharged"
);
// Conservation: payer's loss == coinbase gain + base-fee burn (nothing vanishes).
let coinbase_gain = balance_of(&db, COINBASE_ADDR);
let base_burn = U256::from(10_000_000_000u64) * total_gas_used;
assert_eq!(
payer_delta,
coinbase_gain + base_burn,
"value silently burned"
);
}
// ==================== FRAMEPARAM stack operand order ====================
/// FRAMEPARAM(param=0x01, frameIndex=0) → gas_limit of frame[0], then SSTORE at slot 0.
/// Bytecode: PUSH1 0x01 (param), PUSH1 0x00 (frameIndex — top), FRAMEPARAM (0xB3),
/// PUSH1 0x00 (slot key), SSTORE (0x55), STOP (0x00).
const FRAMEPARAM_READ_FRAME0_GASLIMIT: &[u8] =
&[0x60, 0x01, 0x60, 0x00, 0xB3, 0x60, 0x00, 0x55, 0x00];
/// Read storage `key` of `addr` from the post-execution cache.
fn storage_slot(db: &GeneralizedDatabase, addr: Address, key: ethrex_common::H256) -> U256 {
db.current_accounts_state
.get(&addr)
.and_then(|acc| acc.storage.get(&key).copied())
.unwrap_or_default()
}
#[test]
fn frameparam_reads_frame_index_from_stack_top() {
let wallet = Address::from_low_u64_be(0xE2);
let reader = Address::from_low_u64_be(0xE3);
let mut frames = vec![
verify_frame(FUNDED_SENDER), // frame[0]: VERIFY, runs APPROVE_EXECUTION_CODE
verify_frame(wallet), // frame[1]: VERIFY, runs APPROVE_PAYMENT_CODE
Frame {
mode: u8::from(FrameMode::Default),
flags: 0,
target: Some(reader),
// EIP-8037 (active at Hegota): the new-slot SSTORE spills
// STATE_BYTES_PER_STORAGE_SET * cost_per_state_byte (~98k) into
// the frame's regular gas, so the budget must cover it.
gas_limit: 300_000,
value: U256::zero(),
data: Bytes::new(),
},
];
// Set a distinctive gas_limit on frame[0] that FRAMEPARAM(param=1, frameIndex=0) must read.
frames[0].gas_limit = 77_777;
let tx = frame_tx_with_frames(frames);
let (result, db) = run_frame_tx(
&[
(
FUNDED_SENDER,
AUTO_SEED_SENDER_BALANCE,
0,
Bytes::from(APPROVE_EXECUTION_CODE.to_vec()),
),
(
wallet,
U256::from(10u64).pow(U256::from(18u64)),
0,
Bytes::from(APPROVE_PAYMENT_CODE.to_vec()),
),
(
reader,
U256::zero(),
0,
Bytes::from(FRAMEPARAM_READ_FRAME0_GASLIMIT.to_vec()),
),
],
tx,
);
result.expect("valid tx (sender approved, payer set)");
// After the fix: FRAMEPARAM pops frameIndex=0 (top) and param=1 (second),
// reads frame[0].gas_limit = 77_777, SSTOREs it at slot 0 of `reader`.
// With the bug: pops param=0 (top) and frameIndex=1, reads frame[1].target
// (the wallet address) — so the assertion below catches the swap.
let stored = storage_slot(&db, reader, ethrex_common::H256::zero());
assert_eq!(
stored,
U256::from(77_777u64),
"FRAMEPARAM read the wrong operand order (stored {stored:#x}, expected 77_777)"
);
}
// ==================== APPROVE scope-0 bypass ====================
#[test]
fn approve_halts_when_frame_scope_is_none() {
// flags=0 (APPROVE_SCOPE_NONE). The frame targets the sender and runs
// APPROVE(scope=3). Pre-fix the scope-0 bypass lets it succeed (payer=sender,
// tx valid); post-fix allowed_scope==0 must halt -> no payer -> invalid tx.
//
// Bytecode: APPROVE_BOTH_CODE (PUSH1 3; PUSH1 0; PUSH1 0; APPROVE 0xAA)
let tx = frame_tx_with_frames(vec![Frame {
mode: u8::from(FrameMode::Default),
flags: 0x00,
target: Some(FUNDED_SENDER),
gas_limit: 100_000,
value: U256::zero(),
data: Bytes::new(),
}]);
let accounts = [(
FUNDED_SENDER,
AUTO_SEED_SENDER_BALANCE,
0,
Bytes::from(APPROVE_BOTH_CODE.to_vec()),
)];
let (result, db) = run_frame_tx(&accounts, tx);
assert!(
matches!(
result,
Err(VMError::TxValidation(
ethrex_levm::errors::TxValidationError::InvalidFrameTransaction
))
),
"APPROVE with allowed_scope==0 must halt, leaving the tx invalid; got {result:?}"
);
assert_db_cache_unchanged(&db, &accounts);
}
// ==================== Batched VERIFY revert invalidates tx ====================
#[test]
fn batched_verify_revert_invalidates_tx() {
let reverter = Address::from_low_u64_be(0xF1);
let stop_ct = Address::from_low_u64_be(0xF2);
// frame0: VERIFY -> sender, runs APPROVE(3) -> sets payer=sender (tx would be valid).
// frame1: VERIFY with ATOMIC_BATCH_FLAG -> a contract that REVERTs.
// frame2: DEFAULT batch terminator (no flag) -> needed so the batch flag isn't on the last frame.
let tx = frame_tx_with_frames(vec![
verify_frame(FUNDED_SENDER), // flags 0x03; FUNDED_SENDER seeded with APPROVE_BOTH_CODE
Frame {
mode: u8::from(FrameMode::Verify),
flags: 0x04,
target: Some(reverter),
gas_limit: 60_000,
value: U256::zero(),
data: Bytes::new(),
},
Frame {
mode: u8::from(FrameMode::Default),
flags: 0x00,
target: Some(stop_ct),
gas_limit: 30_000,
value: U256::zero(),
data: Bytes::new(),
},
]);
let accounts = [
(
FUNDED_SENDER,
AUTO_SEED_SENDER_BALANCE,
0,
Bytes::from(APPROVE_BOTH_CODE.to_vec()),
),
(
reverter,
U256::zero(),
0,
Bytes::from(PURE_REVERT_CODE.to_vec()),
),
(stop_ct, U256::zero(), 0, Bytes::from(vec![0x00u8])), // STOP
];
let (result, db) = run_frame_tx(&accounts, tx);
assert!(
matches!(
result,
Err(VMError::TxValidation(
ethrex_levm::errors::TxValidationError::InvalidFrameTransaction
))
),
"a batched VERIFY revert must invalidate the tx; got {result:?}"
);
assert_db_cache_unchanged(&db, &accounts);
}
// ============== I10: APPROVE_PAYMENT must NOT precede APPROVE_EXECUTION ==============
#[test]
fn payment_approval_before_execution_approval_reverts() {
// EIP-8141: APPROVE_PAYMENT (scope 1) must revert the frame while
// sender_approved == false. Frame 0 is a paymaster VERIFY frame calling
// APPROVE(APPROVE_PAYMENT) BEFORE the sender has approved execution -> the
// frame reverts -> the VERIFY prefix reverts -> the tx is invalid.
let paymaster = Address::from_low_u64_be(0x9A);
let stop_ct = Address::from_low_u64_be(0x9B);
let tx = frame_tx_with_frames(vec![
// frame0: paymaster approves PAYMENT first (scope 1) -> must revert.
verify_frame(paymaster),
// frame1: sender approves EXECUTION (scope 2).
verify_frame(FUNDED_SENDER),
// frame2: a SENDER frame that just STOPs.
Frame {
mode: u8::from(FrameMode::Sender),
flags: 0,
target: Some(stop_ct),
gas_limit: 30_000,
value: U256::zero(),
data: Bytes::new(),
},
]);
let accounts = [
(
paymaster,
U256::from(10u64).pow(U256::from(18u64)),
0,
Bytes::from(APPROVE_PAYMENT_CODE.to_vec()),
),
(
FUNDED_SENDER,
AUTO_SEED_SENDER_BALANCE,
0,
Bytes::from(APPROVE_EXECUTION_CODE.to_vec()),
),
(stop_ct, U256::zero(), 0, Bytes::from(vec![0x00u8])), // STOP
];
let (result, db) = run_frame_tx(&accounts, tx);
assert!(
matches!(
result,
Err(VMError::TxValidation(
ethrex_levm::errors::TxValidationError::InvalidFrameTransaction
))
),
"APPROVE_PAYMENT before the sender's execution approval must revert the \
frame and invalidate the tx; got {result:?}"
);
assert_db_cache_unchanged(&db, &accounts);
}
// ==================== SENDER/DEFAULT default code returns success ====================
#[test]
fn sender_frame_transfers_value_to_eoa() {
let eoa = Address::from_low_u64_be(0xE0A); // code-less; NOT seeded with code
let value = U256::from(5_000_000u64);
let tx = frame_tx_with_frames(vec![
// frame0: VERIFY on the sender -> APPROVE(3) -> payer=sender, sender_approved.
verify_frame(FUNDED_SENDER),
// frame1: SENDER frame delivering value to a code-less EOA.
Frame {
mode: u8::from(FrameMode::Sender),
flags: 0,
target: Some(eoa),
gas_limit: 50_000,
value,
data: Bytes::new(),
},
]);
let accounts = [(
FUNDED_SENDER,
AUTO_SEED_SENDER_BALANCE,
0,
Bytes::from(APPROVE_BOTH_CODE.to_vec()),
)];
let (result, db) = run_frame_tx(&accounts, tx);
let report = result.expect("plain EOA transfer must be a VALID, SUCCESSFUL tx");
// frame[1] (the SENDER frame) succeeded:
let frame_results = report.frame_results.expect("frame results present");
assert_eq!(
frame_results[1].0,
ethrex_common::types::FRAME_RECEIPT_STATUS_SUCCESS,
"SENDER frame to a code-less EOA must succeed (default code = success)"
);
// The EOA actually received the value:
assert_eq!(balance_of(&db, eoa), value, "value not delivered to EOA");
}
#[test]
fn sender_frame_to_eoa_emits_transfer_log() {
// EIP-7708 (active at Amsterdam, and Hegota >= Amsterdam): an ETH transfer
// to an EOA via a SENDER frame must emit the Transfer log in the frame
// receipt. The default-code branch must capture the substate log rather than
// drop it — otherwise frame_receipts[i].logs (which is committed to the
// receipts-trie root) omits a log a spec-compliant client includes, forking
// the chain on the most basic frame-tx operation.
use ethrex_common::constants::SYSTEM_ADDRESS;
use ethrex_levm::constants::TRANSFER_EVENT_TOPIC;
let eoa = Address::from_low_u64_be(0xE0B); // code-less recipient
let value = U256::from(7_000_000u64);
let tx = frame_tx_with_frames(vec![
verify_frame(FUNDED_SENDER), // APPROVE(3): payer=sender, sender_approved
Frame {
mode: u8::from(FrameMode::Sender),
flags: 0,
target: Some(eoa),
gas_limit: 50_000,
value,
data: Bytes::new(),
},
]);
let accounts = [(
FUNDED_SENDER,
AUTO_SEED_SENDER_BALANCE,
0,
Bytes::from(APPROVE_BOTH_CODE.to_vec()),
)];
let (result, _db) = run_frame_tx(&accounts, tx);
let report = result.expect("EOA transfer must be a valid, successful tx");
let is_transfer_log = |l: ðrex_common::types::Log| {
l.address == SYSTEM_ADDRESS && l.topics.first() == Some(&TRANSFER_EVENT_TOPIC)
};
// The EIP-7708 Transfer log must be in the SENDER frame's per-frame receipt
// (frame index 1) — that's what the consensus receipts-root commits to.
let frame_results = report
.frame_results
.as_ref()
.expect("frame results present");
assert!(
frame_results[1].2.iter().any(is_transfer_log),
"EIP-7708 transfer log missing from frame_receipts[1].logs: {:?}",
frame_results[1].2
);
// ...and in the aggregated report logs (eth_getLogs / RPC).
assert!(
report.logs.iter().any(is_transfer_log),
"EIP-7708 transfer log missing from report.logs"
);
}
// ==================== Happy-path E2E: SSTORE + LOG0 ====================
/// Bytecode: PUSH1 0x2a, PUSH1 0x00, SSTORE, PUSH1 0x00 (size), PUSH1 0x00 (offset), LOG0, STOP.
/// Writes 0x2a to slot 0, then emits an empty-data LOG0, then halts successfully.
const SSTORE_AND_LOG_CODE: &[u8] = &[
0x60, 0x2a, // PUSH1 0x2a
0x60, 0x00, // PUSH1 0x00 (slot key)
0x55, // SSTORE
0x60, 0x00, // PUSH1 0x00 (size = 0)
0x60, 0x00, // PUSH1 0x00 (offset = 0)
0xA0, // LOG0
0x00, // STOP
];
#[test]
fn frame_tx_happy_path_sstore_and_log() {
let worker = Address::from_low_u64_be(0xC0FFEE);
// Frame 0: VERIFY targeting the funded sender — runs APPROVE_BOTH_CODE (scope 3),
// setting payer = sender and sender_approved in one shot.
// Frame 1: SENDER to the worker contract — executes SSTORE + LOG0.
let tx = frame_tx_with_frames(vec![
verify_frame(FUNDED_SENDER),
Frame {
mode: u8::from(FrameMode::Sender),
flags: 0,
target: Some(worker),
// EIP-8037 (active at Hegota): the new-slot SSTORE spills
// STATE_BYTES_PER_STORAGE_SET * cost_per_state_byte (~98k) into
// the frame's regular gas, so the budget must cover it.
gas_limit: 300_000,
value: U256::zero(),
data: Bytes::new(),
},
]);
let accounts = [
(
FUNDED_SENDER,
AUTO_SEED_SENDER_BALANCE,
0,
Bytes::from(APPROVE_BOTH_CODE.to_vec()),
),
(
worker,
U256::zero(),
0,
Bytes::from(SSTORE_AND_LOG_CODE.to_vec()),
),
];
let (result, db) = run_frame_tx(&accounts, tx);
let report = result.expect("happy-path frame tx must succeed");
// 1. Overall transaction result is Success.
assert!(
matches!(report.result, TxResult::Success),
"expected TxResult::Success, got {:?}",
report.result
);
// 2. Storage written by the SENDER frame: slot 0 of worker == 0x2a.
assert_eq!(
storage_slot(&db, worker, H256::zero()),
U256::from(0x2au64),
"SSTORE did not write 0x2a to slot 0 of worker"
);
// 3. The LOG0 appears in the aggregated report.logs (logs collected).
assert!(
report.logs.iter().any(|l| l.address == worker),
"log from worker missing from aggregated report.logs"
);
// 4. Per-frame isolation: frame_results[1] is success and carries the log;
// frame_results[0] (the VERIFY/approve frame) has no logs.
let frame_results = report
.frame_results
.expect("frame tx report must carry per-frame results");
assert_eq!(
frame_results[1].0, FRAME_RECEIPT_STATUS_SUCCESS,
"SENDER frame (index 1) must be reported as success"
);
assert!(
frame_results[1].2.iter().any(|l| l.address == worker),
"log from worker missing from frame_results[1].logs"
);
assert!(
frame_results[0].2.is_empty(),
"approve VERIFY frame (index 0) must have no logs; isolation violated"
);
// 5. Sender nonce incremented exactly once by APPROVE (scope 3 bumps nonce once).
assert_eq!(
nonce_of(&db, FUNDED_SENDER),
1,
"sender nonce must be 1 after APPROVE (scope 3 increments nonce once)"
);
}
// ============ Regression: per-frame log isolation across contract frames ============
/// PUSH1 0x00 (size), PUSH1 0x00 (offset), LOG0, STOP — emits one empty LOG0 at
/// the executing contract's own address, then halts successfully.
const LOG0_CODE: &[u8] = &[
0x60, 0x00, // PUSH1 0x00 (size = 0)
0x60, 0x00, // PUSH1 0x00 (offset = 0)
0xA0, // LOG0
0x00, // STOP
];
/// Two SENDER frames, each targeting a *different* log-emitting contract, must
/// each carry only their own log in `frame_receipts[i].logs`, and the aggregate
/// `report.logs` must contain each log exactly once.
///
/// Regression for the double-commit bug (PR #6326, iovoid review): the CallFrame
/// branch pushed a substate backup and let `run_execution` commit it (the inner
/// frame is the initial call frame, so it commits via `handle_state_backup`), but
/// then ALSO called `commit_backup` a second time and read `current_logs()` after
/// that commit — pulling the first frame's already-merged log into the second
/// frame's receipt and duplicating it in the aggregate (a receipts-root /
/// logs-bloom divergence). With only one log-emitting frame the bug is invisible,
/// so this test uses two.
#[test]
fn multiple_contract_frames_do_not_duplicate_logs() {
let worker_a = Address::from_low_u64_be(0xAAA0);
let worker_b = Address::from_low_u64_be(0xBBB0);
let tx = frame_tx_with_frames(vec![
// Frame 0: VERIFY on the funded sender — APPROVE_BOTH (emits no logs).
verify_frame(FUNDED_SENDER),
// Frame 1: SENDER to worker_a — emits LOG0 at worker_a.
Frame {
mode: u8::from(FrameMode::Sender),
flags: 0,
target: Some(worker_a),
gas_limit: 100_000,
value: U256::zero(),
data: Bytes::new(),
},
// Frame 2: SENDER to worker_b — emits LOG0 at worker_b.
Frame {
mode: u8::from(FrameMode::Sender),
flags: 0,
target: Some(worker_b),
gas_limit: 100_000,
value: U256::zero(),
data: Bytes::new(),
},
]);
let accounts = [
(
FUNDED_SENDER,
AUTO_SEED_SENDER_BALANCE,
0,
Bytes::from(APPROVE_BOTH_CODE.to_vec()),
),
(worker_a, U256::zero(), 0, Bytes::from(LOG0_CODE.to_vec())),
(worker_b, U256::zero(), 0, Bytes::from(LOG0_CODE.to_vec())),
];
let (result, _db) = run_frame_tx(&accounts, tx);
let report = result.expect("multi-frame log tx must succeed");
assert!(
matches!(report.result, TxResult::Success),
"expected TxResult::Success, got {:?}",
report.result
);
let frame_results = report
.frame_results
.expect("frame tx report must carry per-frame results");
// Per-frame isolation: each SENDER frame carries exactly its own log.
assert_eq!(
frame_results[1].2.len(),
1,
"worker_a frame must carry exactly one log, got {:?}",
frame_results[1].2
);
assert!(
frame_results[1].2.iter().all(|l| l.address == worker_a),
"worker_a frame receipt must contain only worker_a's log"
);
assert_eq!(
frame_results[2].2.len(),
1,
"worker_b frame must carry exactly one log (the bug leaked worker_a's log \
in here), got {:?}",
frame_results[2].2
);
assert!(
frame_results[2].2.iter().all(|l| l.address == worker_b),
"worker_b frame receipt must contain only worker_b's log; worker_a's log leaked in"
);
// Aggregate: each worker's log appears exactly once.
assert_eq!(
report.logs.iter().filter(|l| l.address == worker_a).count(),
1,
"worker_a log must appear exactly once in report.logs (the bug duplicated it), got {:?}",