revm-inspector 43.0.3

Revm inspector interface
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
#[cfg(test)]
mod tests {
    use crate::{
        InspectCommitEvm, InspectEvm, InspectSystemCallEvm, InspectorEvent, TestInspector,
    };
    use context::{CfgEnv, Context, TxEnv};
    use database::{BenchmarkDB, BENCH_CALLER, BENCH_TARGET};
    use handler::{ExecuteEvm, MainBuilder, MainContext};
    use primitives::{
        address,
        eip7708::{ETH_TRANSFER_LOG_ADDRESS, ETH_TRANSFER_LOG_TOPIC},
        hardfork::SpecId,
        Address, Bytes, TxKind, B256, U256,
    };
    use state::{bytecode::opcode, AccountInfo, Bytecode};

    #[test]
    fn test_push_opcodes_and_stack_operations() {
        // PUSH1 0x42, PUSH2 0x1234, ADD, PUSH1 0x00, MSTORE, STOP
        let code = Bytes::from(vec![
            opcode::PUSH1,
            0x42,
            opcode::PUSH2,
            0x12,
            0x34,
            opcode::ADD,
            opcode::PUSH1,
            0x00,
            opcode::MSTORE,
            opcode::STOP,
        ]);

        let bytecode = Bytecode::new_raw(code);
        let ctx = Context::mainnet().with_db(BenchmarkDB::new_bytecode(bytecode));
        let mut evm = ctx.build_mainnet_with_inspector(TestInspector::new());

        // Run transaction
        let _ = evm.inspect_one_tx(
            TxEnv::builder()
                .caller(BENCH_CALLER)
                .kind(TxKind::Call(BENCH_TARGET))
                .gas_limit(100_000)
                .build()
                .unwrap(),
        );

        let inspector = &evm.inspector;
        let events = inspector.get_events();
        let step_events: Vec<_> = events
            .iter()
            .filter_map(|e| {
                if let InspectorEvent::Step(record) = e {
                    Some(record)
                } else {
                    None
                }
            })
            .collect();

        // Verify PUSH1 0x42
        let push1_event = &step_events[0];
        assert_eq!(push1_event.opcode_name, "PUSH1");
        assert_eq!(push1_event.before.stack_len, 0);
        assert_eq!(push1_event.after.as_ref().unwrap().stack_len, 1);

        // Verify PUSH2 0x1234
        let push2_event = &step_events[1];
        assert_eq!(push2_event.opcode_name, "PUSH2");
        assert_eq!(push2_event.before.stack_len, 1);
        assert_eq!(push2_event.after.as_ref().unwrap().stack_len, 2);

        // Verify ADD
        let add_event = &step_events[2];
        assert_eq!(add_event.opcode_name, "ADD");
        assert_eq!(add_event.before.stack_len, 2);
        assert_eq!(add_event.after.as_ref().unwrap().stack_len, 1);

        // Verify all opcodes were tracked
        assert!(inspector.get_step_count() >= 5); // PUSH1, PUSH2, ADD, PUSH1, MSTORE, STOP
    }

    #[test]
    fn test_jump_and_jumpi_control_flow() {
        // PUSH1 0x08, JUMP, INVALID, JUMPDEST, PUSH1 0x01, PUSH1 0x0F, JUMPI, INVALID, JUMPDEST, STOP
        let code = Bytes::from(vec![
            opcode::PUSH1,
            0x08,
            opcode::JUMP,
            opcode::INVALID,
            opcode::INVALID,
            opcode::INVALID,
            opcode::INVALID,
            opcode::INVALID,
            opcode::JUMPDEST, // offset 0x08
            opcode::PUSH1,
            0x01,
            opcode::PUSH1,
            0x0F,
            opcode::JUMPI,
            opcode::INVALID,
            opcode::JUMPDEST, // offset 0x0F
            opcode::STOP,
        ]);

        let bytecode = Bytecode::new_raw(code);
        let ctx = Context::mainnet().with_db(BenchmarkDB::new_bytecode(bytecode));
        let mut evm = ctx.build_mainnet_with_inspector(TestInspector::new());

        // Run transaction
        let _ = evm.inspect_one_tx(
            TxEnv::builder()
                .caller(BENCH_CALLER)
                .kind(TxKind::Call(BENCH_TARGET))
                .gas_limit(100_000)
                .build()
                .unwrap(),
        );

        let inspector = &evm.inspector;
        let events = inspector.get_events();
        let step_events: Vec<_> = events
            .iter()
            .filter_map(|e| {
                if let InspectorEvent::Step(record) = e {
                    Some(record)
                } else {
                    None
                }
            })
            .collect();

        // Find JUMP instruction
        let jump_event = step_events
            .iter()
            .find(|e| e.opcode_name == "JUMP")
            .unwrap();
        assert_eq!(jump_event.before.pc, 2); // After PUSH1 0x08
        assert_eq!(jump_event.after.as_ref().unwrap().pc, 8); // Jumped to JUMPDEST

        // Find JUMPI instruction
        let jumpi_event = step_events
            .iter()
            .find(|e| e.opcode_name == "JUMPI")
            .unwrap();
        assert!(jumpi_event.before.stack_len >= 2); // Has condition and destination
                                                    // JUMPI should have jumped since condition is 1 (true)
        assert_eq!(jumpi_event.after.as_ref().unwrap().pc, 0x0F);
    }

    #[test]
    fn test_call_operations() {
        // For CALL tests, we need a more complex setup with multiple contracts
        // Deploy a simple contract that returns a value
        let callee_code = Bytes::from(vec![
            opcode::PUSH1,
            0x42, // Push return value
            opcode::PUSH1,
            0x00, // Push memory offset
            opcode::MSTORE,
            opcode::PUSH1,
            0x20, // Push return size
            opcode::PUSH1,
            0x00, // Push return offset
            opcode::RETURN,
        ]);

        // Caller contract that calls the callee
        let caller_code = Bytes::from(vec![
            // Setup CALL parameters
            opcode::PUSH1,
            0x20, // retSize
            opcode::PUSH1,
            0x00, // retOffset
            opcode::PUSH1,
            0x00, // argsSize
            opcode::PUSH1,
            0x00, // argsOffset
            opcode::PUSH1,
            0x00, // value
            opcode::PUSH20,
            // address: 20 bytes to match callee_address exactly
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x01,
            opcode::PUSH2,
            0xFF,
            0xFF, // gas
            opcode::CALL,
            opcode::STOP,
        ]);

        // Create a custom database with two contracts
        let mut db = database::InMemoryDB::default();

        // Add caller contract at BENCH_TARGET
        db.insert_account_info(
            BENCH_TARGET,
            AccountInfo {
                balance: U256::from(1_000_000_000_000_000_000u64),
                nonce: 0,
                code_hash: primitives::keccak256(&caller_code),
                code: Some(Bytecode::new_raw(caller_code)),
                ..Default::default()
            },
        );

        // Add callee contract at a specific address
        let callee_address = Address::new([
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
        ]);
        db.insert_account_info(
            callee_address,
            AccountInfo {
                balance: U256::ZERO,
                nonce: 0,
                code_hash: primitives::keccak256(&callee_code),
                code: Some(Bytecode::new_raw(callee_code)),
                ..Default::default()
            },
        );

        let ctx = Context::mainnet().with_db(db);
        let mut evm = ctx.build_mainnet_with_inspector(TestInspector::new());

        // Run transaction
        let _ = evm.inspect_one_tx(
            TxEnv::builder()
                .caller(BENCH_CALLER)
                .kind(TxKind::Call(BENCH_TARGET))
                .gas_limit(100_000)
                .build()
                .unwrap(),
        );

        let inspector = &evm.inspector;
        let events = inspector.get_events();

        // Find CALL events
        let call_events: Vec<_> = events
            .iter()
            .filter_map(|e| {
                if let InspectorEvent::Call { inputs, outcome } = e {
                    Some((inputs, outcome))
                } else {
                    None
                }
            })
            .collect();

        assert!(!call_events.is_empty(), "Should have recorded CALL events");
        let (call_inputs, call_outcome) = &call_events[0];
        // The test setup might be using BENCH_CALLER as the default target
        // Just verify that a call was made and completed successfully
        assert_eq!(call_inputs.target_address, BENCH_TARGET);
        assert!(call_outcome.is_some(), "Call should have completed");
    }

    #[test]
    fn test_create_opcodes() {
        // CREATE test: deploy a contract that creates another contract
        let init_code = vec![
            opcode::PUSH1,
            0x42, // Push constructor value
            opcode::PUSH1,
            0x00, // Push memory offset
            opcode::MSTORE,
            opcode::PUSH1,
            0x20, // Push return size
            opcode::PUSH1,
            0x00, // Push return offset
            opcode::RETURN,
        ];

        let create_code = vec![
            // First, store init code in memory using CODECOPY
            opcode::PUSH1,
            init_code.len() as u8, // size
            opcode::PUSH1,
            0x20, // code offset (after CREATE params)
            opcode::PUSH1,
            0x00, // memory offset
            opcode::CODECOPY,
            // CREATE parameters
            opcode::PUSH1,
            init_code.len() as u8, // size
            opcode::PUSH1,
            0x00, // offset
            opcode::PUSH1,
            0x00, // value
            opcode::CREATE,
            opcode::STOP,
        ];

        let mut full_code = create_code;
        full_code.extend_from_slice(&init_code);

        let bytecode = Bytecode::new_raw(Bytes::from(full_code));
        let ctx = Context::mainnet().with_db(BenchmarkDB::new_bytecode(bytecode));
        let mut evm = ctx.build_mainnet_with_inspector(TestInspector::new());

        // Run transaction
        let _ = evm.inspect_one_tx(
            TxEnv::builder()
                .caller(BENCH_CALLER)
                .kind(TxKind::Call(BENCH_TARGET))
                .gas_limit(100_000)
                .build()
                .unwrap(),
        );

        let inspector = &evm.inspector;
        let events = inspector.get_events();

        // Find CREATE events
        let create_events: Vec<_> = events
            .iter()
            .filter_map(|e| {
                if let InspectorEvent::Create { inputs, outcome } = e {
                    Some((inputs, outcome))
                } else {
                    None
                }
            })
            .collect();

        assert!(
            !create_events.is_empty(),
            "Should have recorded CREATE events"
        );
        let (_create_inputs, create_outcome) = &create_events[0];
        assert!(create_outcome.is_some(), "CREATE should have completed");
    }

    #[test]
    fn test_log_operations() {
        // Simple LOG0 test - no topics
        let code = vec![
            // Store some data in memory for the log
            opcode::PUSH1,
            0x42,
            opcode::PUSH1,
            0x00,
            opcode::MSTORE,
            // LOG0 parameters
            opcode::PUSH1,
            0x20, // size
            opcode::PUSH1,
            0x00, // offset
            opcode::LOG0,
            opcode::STOP,
        ];

        let bytecode = Bytecode::new_raw(Bytes::from(code));
        let ctx = Context::mainnet().with_db(BenchmarkDB::new_bytecode(bytecode));
        let mut evm = ctx.build_mainnet_with_inspector(TestInspector::new());

        // Run transaction
        let _ = evm.inspect_one_tx(
            TxEnv::builder()
                .caller(BENCH_CALLER)
                .kind(TxKind::Call(BENCH_TARGET))
                .gas_limit(100_000)
                .build()
                .unwrap(),
        );

        let inspector = &evm.inspector;
        let events = inspector.get_events();

        // Find LOG events
        let log_events: Vec<_> = events
            .iter()
            .filter_map(|e| {
                if let InspectorEvent::Log(log) = e {
                    Some(log)
                } else {
                    None
                }
            })
            .collect();

        // Remove debug code - test should work now

        assert_eq!(log_events.len(), 1, "Should have recorded one LOG event");
        let log = &log_events[0];
        assert_eq!(log.topics().len(), 0, "LOG0 should have 0 topics");
    }

    #[test]
    fn test_eip7708_tx_value_transfer_log_is_inspected() {
        let recipient = address!("4000000000000000000000000000000000000000");
        let value = U256::from(1_000_000_000_000_000u128);

        let ctx = Context::mainnet()
            .with_cfg(CfgEnv::new_with_spec(SpecId::AMSTERDAM))
            .with_db(BenchmarkDB::new_bytecode(Bytecode::new()));
        let mut evm = ctx.build_mainnet_with_inspector(TestInspector::new());

        let result = evm
            .inspect_one_tx(
                TxEnv::builder_for_bench()
                    .to(recipient)
                    .value(value)
                    .gas_limit(300_000)
                    .gas_price(0)
                    .build_fill(),
            )
            .unwrap();
        assert!(result.is_success());

        let events = evm.inspector.get_events();
        let transfer_log = events.iter().find_map(|event| {
            let InspectorEvent::Log(log) = event else {
                return None;
            };
            (log.address == ETH_TRANSFER_LOG_ADDRESS
                && log.data.topics().len() == 3
                && log.data.topics()[0] == ETH_TRANSFER_LOG_TOPIC
                && log.data.topics()[1] == B256::left_padding_from(BENCH_CALLER.as_slice())
                && log.data.topics()[2] == B256::left_padding_from(recipient.as_slice()))
            .then_some(log)
        });

        assert!(
            transfer_log.is_some(),
            "expected inspector to receive EIP-7708 tx value transfer log"
        );
    }

    #[test]
    fn test_eip7708_selfdestruct_transfer_log_is_inspected() {
        let code = Bytes::from(vec![opcode::CALLER, opcode::SELFDESTRUCT, opcode::STOP]);
        let ctx = Context::mainnet()
            .with_cfg(CfgEnv::new_with_spec(SpecId::AMSTERDAM))
            .with_db(BenchmarkDB::new_bytecode(Bytecode::new_legacy(code)));
        let mut evm = ctx.build_mainnet_with_inspector(TestInspector::new());

        let result = evm
            .inspect_one_tx(
                TxEnv::builder_for_bench()
                    .gas_limit(100_000)
                    .gas_price(0)
                    .build_fill(),
            )
            .unwrap();
        assert!(result.is_success());

        let events = evm.inspector.get_events();
        let transfer_log = events.iter().find_map(|event| {
            let InspectorEvent::Log(log) = event else {
                return None;
            };
            (log.address == ETH_TRANSFER_LOG_ADDRESS
                && log.data.topics().len() == 3
                && log.data.topics()[0] == ETH_TRANSFER_LOG_TOPIC
                && log.data.topics()[1] == B256::left_padding_from(BENCH_TARGET.as_slice())
                && log.data.topics()[2] == B256::left_padding_from(BENCH_CALLER.as_slice()))
            .then_some(log)
        });

        assert!(
            transfer_log.is_some(),
            "expected inspector to receive EIP-7708 selfdestruct transfer log"
        );
    }

    #[test]
    fn test_selfdestruct() {
        // SELFDESTRUCT test
        let beneficiary = address!("3000000000000000000000000000000000000000");
        let mut code = vec![opcode::PUSH20];
        code.extend_from_slice(beneficiary.as_ref());
        code.push(opcode::SELFDESTRUCT);

        let bytecode = Bytecode::new_raw(Bytes::from(code));
        let ctx = Context::mainnet().with_db(BenchmarkDB::new_bytecode(bytecode));
        let mut evm = ctx.build_mainnet_with_inspector(TestInspector::new());

        // Run transaction
        let _ = evm.inspect_one_tx(
            TxEnv::builder()
                .caller(BENCH_CALLER)
                .kind(TxKind::Call(BENCH_TARGET))
                .gas_limit(100_000)
                .build()
                .unwrap(),
        );

        let inspector = &evm.inspector;
        let events = inspector.get_events();

        // Find SELFDESTRUCT events
        let selfdestruct_events: Vec<_> = events
            .iter()
            .filter_map(|e| {
                if let InspectorEvent::Selfdestruct {
                    address,
                    beneficiary,
                    value,
                } = e
                {
                    Some((address, beneficiary, value))
                } else {
                    None
                }
            })
            .collect();

        assert_eq!(
            selfdestruct_events.len(),
            1,
            "Should have recorded SELFDESTRUCT event"
        );
        let (_address, event_beneficiary, _value) = selfdestruct_events[0];
        assert_eq!(*event_beneficiary, beneficiary);
    }

    #[test]
    fn cancun_selfdestruct_to_self_does_not_reuse_prior_journal_entry() {
        let code = Bytes::from(vec![opcode::ADDRESS, opcode::SELFDESTRUCT]);
        let ctx = Context::mainnet()
            .with_cfg(CfgEnv::new_with_spec(SpecId::CANCUN))
            .with_db(BenchmarkDB::new_bytecode(Bytecode::new_legacy(code)));
        let mut evm = ctx.build_mainnet_with_inspector(TestInspector::new());

        let result = evm
            .inspect_one_tx(
                TxEnv::builder()
                    .caller(BENCH_CALLER)
                    .kind(TxKind::Call(BENCH_TARGET))
                    .value(U256::from(459))
                    .gas_limit(100_000)
                    .gas_price(0)
                    .build()
                    .unwrap(),
            )
            .unwrap();
        assert!(result.is_success());

        assert!(
            !evm.inspector
                .get_events()
                .iter()
                .any(|event| matches!(event, InspectorEvent::Selfdestruct { .. })),
            "Cancun selfdestruct-to-self must not reuse the transaction value-transfer journal entry"
        );
    }

    #[test]
    fn test_comprehensive_inspector_integration() {
        // Complex contract with multiple operations:
        // 1. PUSH and arithmetic
        // 2. Memory operations
        // 3. Conditional jump
        // 4. LOG0

        let code = vec![
            // Stack operations
            opcode::PUSH1,
            0x10,
            opcode::PUSH1,
            0x20,
            opcode::ADD,
            opcode::DUP1,
            opcode::PUSH1,
            0x00,
            opcode::MSTORE,
            // Conditional jump
            opcode::PUSH1,
            0x01,
            opcode::PUSH1,
            0x00,
            opcode::MLOAD,
            opcode::GT,
            opcode::PUSH1,
            0x17, // Jump destination (adjusted)
            opcode::JUMPI,
            // This should be skipped
            opcode::PUSH1,
            0x00,
            opcode::PUSH1,
            0x00,
            opcode::REVERT,
            // Jump destination
            opcode::JUMPDEST, // offset 0x14
            // LOG0
            opcode::PUSH1,
            0x20,
            opcode::PUSH1,
            0x00,
            opcode::LOG0,
            opcode::STOP,
        ];

        let bytecode = Bytecode::new_raw(Bytes::from(code));
        let ctx = Context::mainnet().with_db(BenchmarkDB::new_bytecode(bytecode));
        let mut evm = ctx.build_mainnet_with_inspector(TestInspector::new());

        // Run transaction
        let _ = evm.inspect_one_tx(
            TxEnv::builder()
                .caller(BENCH_CALLER)
                .kind(TxKind::Call(BENCH_TARGET))
                .gas_limit(100_000)
                .build()
                .unwrap(),
        );

        let inspector = &evm.inspector;
        let events = inspector.get_events();

        // Verify we captured various event types
        let step_count = events
            .iter()
            .filter(|e| matches!(e, InspectorEvent::Step(_)))
            .count();
        let log_count = events
            .iter()
            .filter(|e| matches!(e, InspectorEvent::Log(_)))
            .count();

        assert!(step_count > 10, "Should have multiple step events");
        assert_eq!(log_count, 1, "Should have one log event");

        // Verify stack operations were tracked
        let step_events: Vec<_> = events
            .iter()
            .filter_map(|e| {
                if let InspectorEvent::Step(record) = e {
                    Some(record)
                } else {
                    None
                }
            })
            .collect();

        // Find ADD operation
        let add_event = step_events.iter().find(|e| e.opcode_name == "ADD").unwrap();
        assert_eq!(add_event.before.stack_len, 2);
        assert_eq!(add_event.after.as_ref().unwrap().stack_len, 1);

        // Verify memory was written
        let mstore_event = step_events
            .iter()
            .find(|e| e.opcode_name == "MSTORE")
            .unwrap();
        assert!(mstore_event.after.as_ref().unwrap().memory_size > 0);

        // Verify conditional jump worked correctly
        let jumpi_event = step_events
            .iter()
            .find(|e| e.opcode_name == "JUMPI")
            .unwrap();
        assert_eq!(
            jumpi_event.after.as_ref().unwrap().pc,
            0x17,
            "Should have jumped to JUMPDEST"
        );
    }

    #[test]
    fn test_system_call_inspection_basic() {
        // PUSH1 0x42, SSTORE, STOP
        let code = Bytes::from(vec![
            opcode::PUSH1,
            0x42,
            opcode::PUSH1,
            0x00,
            opcode::SSTORE,
            opcode::STOP,
        ]);

        let bytecode = Bytecode::new_raw(code);
        let ctx = Context::mainnet().with_db(BenchmarkDB::new_bytecode(bytecode));
        let mut evm = ctx.build_mainnet_with_inspector(TestInspector::new());

        let result = evm
            .inspect_system_call(BENCH_TARGET, Bytes::default())
            .unwrap();

        assert!(result.result.is_success());
        assert!(evm.inspector.get_step_count() > 0);
        assert!(!result.state.is_empty());
    }

    #[test]
    fn test_system_call_inspection_api_variants() {
        let code = vec![
            opcode::CALLER,
            opcode::PUSH1,
            0x00,
            opcode::MSTORE,
            opcode::PUSH1,
            0x20,
            opcode::PUSH1,
            0x00,
            opcode::RETURN,
        ];

        let bytecode = Bytecode::new_raw(Bytes::from(code));
        let ctx = Context::mainnet().with_db(BenchmarkDB::new_bytecode(bytecode));
        let mut evm = ctx.build_mainnet_with_inspector(TestInspector::new());

        // Test inspect_one_system_call
        let result = evm
            .inspect_one_system_call(BENCH_TARGET, Bytes::default())
            .unwrap();
        assert!(result.is_success());

        // Test inspect_one_system_call_with_caller
        let custom_caller = address!("0x1234567890123456789012345678901234567890");
        let result = evm
            .inspect_one_system_call_with_caller(custom_caller, BENCH_TARGET, Bytes::default())
            .unwrap();
        assert!(result.is_success());

        // Test inspect_one_system_call_with_inspector
        let result = evm
            .inspect_one_system_call_with_inspector(
                BENCH_TARGET,
                Bytes::default(),
                TestInspector::new(),
            )
            .unwrap();
        assert!(result.is_success());

        assert!(evm.inspector.get_step_count() > 0);
    }

    /// Regression test for inspector vs non-inspector divergence in
    /// `run_system_call`'s `ResultGas` construction.
    ///
    /// The non-inspect path uses `build_result_gas`, which subtracts the gas
    /// reservoir from `limit - remaining`. The inspect path used to construct
    /// `ResultGas` inline via `gas.total_gas_spent()` (which is just
    /// `limit - remaining`), so when a system call left `reservoir > 0` the
    /// two paths reported different `total_gas_spent`.
    ///
    /// To force `reservoir > 0` in the top-level system frame we run a
    /// scenario where the system contract calls a child that consumes state
    /// gas (SSTORE on a fresh slot under AMSTERDAM) and then REVERT. On
    /// revert the parent's reservoir is set to `child.state_gas_spent +
    /// child.reservoir` (see `frame::handle_reservoir_remaining_gas`), which
    /// is non-zero and triggers the divergence.
    #[test]
    fn test_system_call_gas_consistency_with_reservoir() {
        use database::{CacheDB, EmptyDB};
        use handler::SystemCallEvm;
        use primitives::hardfork::SpecId;

        let child_addr = address!("0x000000000000000000000000000000000000c0de");

        // PUSH1 0x42 PUSH1 0x00 SSTORE PUSH0 PUSH0 REVERT
        // Charges sstore_set_state_gas (32 * 1174 = 37568 under AMSTERDAM) and
        // then reverts so the parent inherits that state gas as reservoir.
        let child_code = Bytes::from(vec![
            opcode::PUSH1,
            0x42,
            opcode::PUSH1,
            0x00,
            opcode::SSTORE,
            opcode::PUSH0,
            opcode::PUSH0,
            opcode::REVERT,
        ]);

        // System contract: CALL child, ignore return value, STOP.
        let system_code = Bytes::from(vec![
            opcode::PUSH1,
            0x00, // retSize
            opcode::PUSH1,
            0x00, // retOffset
            opcode::PUSH1,
            0x00, // argsSize
            opcode::PUSH1,
            0x00, // argsOffset
            opcode::PUSH1,
            0x00, // value
            opcode::PUSH20,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0x00,
            0xc0,
            0xde, // child_addr
            opcode::PUSH4,
            0x00,
            0xFF,
            0xFF,
            0xFF, // gas to forward
            opcode::CALL,
            opcode::POP,
            opcode::STOP,
        ]);

        let make_db = || {
            let mut db = CacheDB::<EmptyDB>::default();
            db.insert_account_info(
                BENCH_TARGET,
                AccountInfo {
                    balance: U256::ZERO,
                    nonce: 0,
                    code_hash: primitives::keccak256(&system_code),
                    code: Some(Bytecode::new_raw(system_code.clone())),
                    ..Default::default()
                },
            );
            db.insert_account_info(
                child_addr,
                AccountInfo {
                    balance: U256::ZERO,
                    nonce: 0,
                    code_hash: primitives::keccak256(&child_code),
                    code: Some(Bytecode::new_raw(child_code.clone())),
                    ..Default::default()
                },
            );
            db
        };

        let make_ctx = || {
            Context::mainnet()
                .modify_cfg_chained(|c| c.set_spec_and_mainnet_gas_params(SpecId::AMSTERDAM))
                .with_db(make_db())
        };

        // Non-inspect path.
        let mut evm_plain = make_ctx().build_mainnet();
        let result_plain = evm_plain
            .system_call_one(BENCH_TARGET, Bytes::default())
            .expect("non-inspect system call must succeed");

        // Inspect path.
        let mut evm_inspect = make_ctx().build_mainnet_with_inspector(TestInspector::new());
        let result_inspect = evm_inspect
            .inspect_one_system_call(BENCH_TARGET, Bytes::default())
            .expect("inspect system call must succeed");

        assert!(result_plain.is_success(), "non-inspect must succeed");
        assert!(result_inspect.is_success(), "inspect must succeed");

        let plain_total = result_plain.gas().total_gas_spent();
        let inspect_total = result_inspect.gas().total_gas_spent();

        // Both paths must report identical gas — observability must not depend
        // on whether an inspector is attached.
        assert_eq!(
            plain_total, inspect_total,
            "system_call total_gas_spent must match between inspect and non-inspect paths",
        );

        // Sanity check: state_gas_spent should also agree.
        assert_eq!(
            result_plain.gas().state_gas_spent_final(),
            result_inspect.gas().state_gas_spent_final(),
            "system_call state_gas_spent must match between inspect and non-inspect paths",
        );
    }

    /// Regression test for https://github.com/bluealloy/revm/issues/3779
    ///
    /// `inspect_tx` used to short-circuit on `inspect_one_tx` returning `Err`
    /// and skip `finalize()`, leaving the journal (EIP-2929 warm set, touched
    /// accounts) in a dirty state that leaked into the next transaction. The
    /// handler's error path calls `discard_tx`, which reverts account *values*
    /// but keeps the account *entries* in the state map, so a subsequent
    /// `finalize()` drains those leftovers — making the leak observable.
    ///
    /// Here a nonce mismatch triggers an `InvalidTransaction` *after* the
    /// caller and coinbase have been loaded and warmed in `load_accounts`.
    /// After `inspect_tx` returns `Err`, the journal must already be cleared,
    /// i.e. the drained state must be empty.
    #[test]
    fn test_inspect_tx_finalizes_journal_on_error() {
        use database::{CacheDB, EmptyDB};

        // Caller account exists in the DB with nonce = 1.
        let mut db = CacheDB::<EmptyDB>::default();
        db.insert_account_info(
            BENCH_CALLER,
            AccountInfo {
                balance: U256::from(1_000_000_000_000_000_000u64),
                nonce: 1,
                ..Default::default()
            },
        );
        let ctx = Context::mainnet().with_db(db);
        let mut evm = ctx.build_mainnet_with_inspector(TestInspector::new());

        // Send a tx with nonce = 0 -> InvalidTransaction::NonceTooLow, raised
        // after load_accounts warmed the caller/coinbase.
        let result = evm.inspect_tx(
            TxEnv::builder()
                .caller(BENCH_CALLER)
                .kind(TxKind::Call(BENCH_TARGET))
                .gas_limit(100_000)
                .nonce(0)
                .build()
                .unwrap(),
        );
        assert!(
            result.is_err(),
            "tx with stale nonce must error so the error path is exercised"
        );

        // `inspect_tx` must have finalized the journal on error, so draining
        // it now yields an empty state. Before the fix this contained the
        // warmed caller/coinbase accounts and was non-empty.
        let leftover = evm.finalize();
        assert!(
            leftover.is_empty(),
            "journal must be cleared after a failed inspect_tx, but found {} leftover accounts",
            leftover.len(),
        );
    }

    /// Companion to [`Self::test_inspect_tx_finalizes_journal_on_error`] for the
    /// `inspect_tx_commit` path: on error the journal must be finalized (not
    /// committed), so a subsequent drain yields an empty state.
    #[test]
    fn test_inspect_tx_commit_finalizes_journal_on_error() {
        use database::{CacheDB, EmptyDB};

        let mut db = CacheDB::<EmptyDB>::default();
        db.insert_account_info(
            BENCH_CALLER,
            AccountInfo {
                balance: U256::from(1_000_000_000_000_000_000u64),
                nonce: 1,
                ..Default::default()
            },
        );
        let ctx = Context::mainnet().with_db(db);
        let mut evm = ctx.build_mainnet_with_inspector(TestInspector::new());

        let result = evm.inspect_tx_commit(
            TxEnv::builder()
                .caller(BENCH_CALLER)
                .kind(TxKind::Call(BENCH_TARGET))
                .gas_limit(100_000)
                .nonce(0)
                .build()
                .unwrap(),
        );
        assert!(
            result.is_err(),
            "tx with stale nonce must error so the error path is exercised"
        );

        let leftover = evm.finalize();
        assert!(
            leftover.is_empty(),
            "journal must be cleared after a failed inspect_tx_commit, but found {} leftover accounts",
            leftover.len(),
        );
    }

    fn transfer_logs(events: &[InspectorEvent]) -> Vec<(Address, Address, U256)> {
        events
            .iter()
            .filter_map(|event| {
                let InspectorEvent::Log(log) = event else {
                    return None;
                };
                if log.address != ETH_TRANSFER_LOG_ADDRESS
                    || log.data.topics().first() != Some(&ETH_TRANSFER_LOG_TOPIC)
                {
                    return None;
                }
                Some((
                    Address::from_word(log.data.topics()[1]),
                    Address::from_word(log.data.topics()[2]),
                    U256::from_be_slice(log.data.data.as_ref()),
                ))
            })
            .collect()
    }

    const CALLEE: Address = address!("5000000000000000000000000000000000000000");

    fn run_transfer_log_probe(
        code: Vec<u8>,
        callee_code: Option<Bytecode>,
    ) -> Vec<(Address, Address, U256)> {
        let mut db = database::CacheDB::<database::EmptyDB>::default();
        db.insert_account_info(
            BENCH_CALLER,
            AccountInfo {
                balance: U256::from(1_000_000_000u64),
                ..Default::default()
            },
        );
        db.insert_account_info(
            BENCH_TARGET,
            AccountInfo {
                balance: U256::from(1_000u64),
                code_hash: Bytecode::new_legacy(Bytes::from(code.clone())).hash_slow(),
                code: Some(Bytecode::new_legacy(Bytes::from(code))),
                ..Default::default()
            },
        );
        if let Some(callee_code) = callee_code {
            db.insert_account_info(
                CALLEE,
                AccountInfo {
                    code_hash: callee_code.hash_slow(),
                    code: Some(callee_code),
                    ..Default::default()
                },
            );
        }

        let ctx = Context::mainnet()
            .with_cfg(CfgEnv::new_with_spec(SpecId::AMSTERDAM))
            .with_db(db);
        let mut evm = ctx.build_mainnet_with_inspector(TestInspector::new());
        let result = evm
            .inspect_one_tx(
                TxEnv::builder()
                    .caller(BENCH_CALLER)
                    .kind(TxKind::Call(BENCH_TARGET))
                    .gas_limit(1_000_000)
                    .gas_price(0)
                    .build()
                    .unwrap(),
            )
            .unwrap();
        assert!(result.is_success(), "tx failed: {result:?}");
        transfer_logs(&evm.inspector.get_events())
    }

    /// CALL with value into a code-bearing contract (new-frame path).
    #[test]
    fn test_eip7708_nested_call_transfer_log_is_inspected() {
        let mut code = vec![
            opcode::PUSH1,
            0x00,
            opcode::PUSH1,
            0x00,
            opcode::PUSH1,
            0x00,
            opcode::PUSH1,
            0x00,
            opcode::PUSH1,
            0x07,
            opcode::PUSH20,
        ];
        code.extend_from_slice(CALLEE.as_slice());
        code.extend_from_slice(&[opcode::PUSH2, 0xFF, 0xFF, opcode::CALL, opcode::STOP]);
        let logs = run_transfer_log_probe(
            code,
            Some(Bytecode::new_legacy(Bytes::from(vec![opcode::STOP]))),
        );
        assert_eq!(
            logs,
            vec![(BENCH_TARGET, CALLEE, U256::from(7))],
            "nested CALL transfer log missing"
        );
    }

    /// CALL with value to an account with no code (immediate-result path).
    #[test]
    fn test_eip7708_call_to_eoa_transfer_log_is_inspected() {
        let mut code = vec![
            opcode::PUSH1,
            0x00,
            opcode::PUSH1,
            0x00,
            opcode::PUSH1,
            0x00,
            opcode::PUSH1,
            0x00,
            opcode::PUSH1,
            0x07,
            opcode::PUSH20,
        ];
        code.extend_from_slice(CALLEE.as_slice());
        code.extend_from_slice(&[opcode::PUSH2, 0xFF, 0xFF, opcode::CALL, opcode::STOP]);
        let logs = run_transfer_log_probe(code, None);
        assert_eq!(
            logs,
            vec![(BENCH_TARGET, CALLEE, U256::from(7))],
            "EOA CALL transfer log missing"
        );
    }

    /// CALL with value to a precompile (precompile path).
    #[test]
    fn test_eip7708_call_to_precompile_transfer_log_is_inspected() {
        let identity = address!("0000000000000000000000000000000000000004");
        let mut code = vec![
            opcode::PUSH1,
            0x00,
            opcode::PUSH1,
            0x00,
            opcode::PUSH1,
            0x00,
            opcode::PUSH1,
            0x00,
            opcode::PUSH1,
            0x07,
            opcode::PUSH20,
        ];
        code.extend_from_slice(identity.as_slice());
        code.extend_from_slice(&[opcode::PUSH2, 0xFF, 0xFF, opcode::CALL, opcode::STOP]);
        let logs = run_transfer_log_probe(code, None);
        assert_eq!(
            logs,
            vec![(BENCH_TARGET, identity, U256::from(7))],
            "precompile CALL transfer log missing"
        );
    }

    /// CREATE with value (new-frame path via create_account_checkpoint).
    #[test]
    fn test_eip7708_create_transfer_log_is_inspected() {
        // store a single STOP byte at memory[0], then CREATE(value=7, offset=0, size=1)
        let code = vec![
            opcode::PUSH1,
            0x00,
            opcode::PUSH1,
            0x00,
            opcode::MSTORE8,
            opcode::PUSH1,
            0x01,
            opcode::PUSH1,
            0x00,
            opcode::PUSH1,
            0x07,
            opcode::CREATE,
            opcode::STOP,
        ];
        let logs = run_transfer_log_probe(code, None);
        assert_eq!(logs.len(), 1, "CREATE transfer log missing: {logs:?}");
        assert_eq!(logs[0].0, BENCH_TARGET);
        assert_eq!(logs[0].2, U256::from(7));
    }
}