Repository navigation
Expand file tree
/
Copy pathevm.rs
More file actions
8526 lines (7679 loc) · 339 KB
/
Copy pathevm.rs
File metadata and controls
8526 lines (7679 loc) · 339 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
// Copyright 2025 Circle Internet Group, Inc. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate alloc;
use crate::assembler::ArcBlockAssembler;
use crate::executor::ArcBlockExecutor;
use crate::frame_result::{create_frame_result, create_oog_frame_result, BeforeFrameInitResult};
use crate::log::create_eip7708_transfer_log;
use alloc::sync::Arc;
use alloy_evm::eth::EthEvmContext;
use alloy_evm::{
block::{state::StateDB, BlockExecutorFactory},
eth::EthBlockExecutionCtx,
precompiles::PrecompilesMap,
Evm as AlloyEvmTrait, EvmFactory,
};
use alloy_rpc_types_engine::ExecutionData;
use arc_execution_config::hardforks::{ArcHardfork, ArcHardforkFlags};
use arc_execution_config::native_coin_control::{
compute_is_blocklisted_storage_slot, is_blocklisted_status,
};
use arc_precompiles::helpers::{
ERR_BLOCKED_ADDRESS, ERR_SELFDESTRUCTED_BALANCE_INCREASED, ERR_ZERO_ADDRESS,
};
use arc_precompiles::NATIVE_COIN_CONTROL_ADDRESS;
use core::fmt::Debug;
use reth_ethereum::evm::revm::context::block::BlockEnv;
use reth_ethereum::evm::revm::primitives::U256;
use reth_ethereum::{
evm::{
primitives::{Database, EvmEnv, NextBlockEnvAttributes},
revm::{
context::{Context, ContextTr, JournalTr, TxEnv},
context_interface::result::{EVMError, HaltReason},
db::State,
inspector::{Inspector, NoOpInspector},
interpreter::interpreter::EthInterpreter,
primitives::hardfork::SpecId,
},
EthEvmConfig,
},
node::api::ConfigureEvm,
primitives::{Header, Log, SealedBlock, SealedHeader},
Receipt, TransactionSigned,
};
use reth_evm::execute::BlockBuilder;
use reth_evm::BlockExecutorForEvm;
use reth_evm::{ConfigureEngineEvm, EvmEnvFor, ExecutableTxIterator, ExecutionCtxFor};
use reth_primitives_traits::NodePrimitives;
use revm::bytecode::opcode::SELFDESTRUCT;
use revm::context_interface::result::ResultAndState;
use revm::handler::evm::{ContextDbError, FrameInitResult};
use revm::handler::instructions::InstructionProvider;
use revm::handler::{EvmTr, FrameInitOrResult, FrameResult, FrameTr, Handler, ItemOrResult};
use revm::inspector::{InspectorEvmTr, InspectorHandler, JournalExt};
use revm::state::AccountInfo;
use revm::Database as RevmDatabase;
use revm::ExecuteEvm;
use revm::SystemCallEvm;
use revm::{
context::{
result::{ExecResultAndState, ExecutionResult, InvalidTransaction},
ContextSetters, Evm as RevmEvm,
},
handler::{instructions::EthInstructions, EthFrame, PrecompileProvider},
interpreter::{CallOutcome, Gas, InstructionResult, InterpreterResult},
state::EvmState,
InspectEvm,
};
use revm_context_interface::journaled_state::{JournalCheckpoint, JournalLoadError};
use revm_context_interface::{FrameStack, Transaction};
use revm_handler::SystemCallTx;
use revm_interpreter::interpreter_action::FrameInit;
use revm_interpreter::{CallScheme, CreateScheme, FrameInput, Instruction};
use revm_primitives::{Address, Bytes};
use std::collections::{HashMap, HashSet};
use crate::handler::ArcEvmHandler;
use crate::opcode::{
arc_network_selfdestruct, arc_network_selfdestruct_zero7, arc_network_selfdestruct_zero8,
};
use crate::subcall::{SubcallContinuation, SubcallRegistry};
use arc_execution_config::chainspec::{ArcChainSpec, BlockGasLimitProvider};
use arc_execution_config::protocol_config::{expected_gas_limit, retrieve_fee_params};
use arc_precompiles::call_from::{CallFromPrecompile, CALL_FROM_ADDRESS};
use arc_precompiles::precompile_provider::ArcPrecompileProvider;
use arc_precompiles::subcall::SubcallPrecompile;
use revm::interpreter::interpreter_action::CallInputs;
/// Flat gas cost charged for rejected subcall dispatches (unauthorized caller, wrong scheme,
/// value attached, sender spoofing, init_subcall errors). Charged by `init_subcall_revert`
/// calls. Prevents zero-cost probing of subcall precompile addresses.
const SUBCALL_DISPATCH_COST: u64 = 100;
fn insert_arc_selfdestruct_instruction<DB: Database>(
instruction: &mut EthInstructions<EthInterpreter, EthEvmContext<DB>>,
hardfork_flags: ArcHardforkFlags,
) {
if hardfork_flags.is_active(ArcHardfork::Zero8) {
instruction.insert_instruction(
SELFDESTRUCT,
Instruction::new(arc_network_selfdestruct_zero8, 5000),
);
} else if hardfork_flags.is_active(ArcHardfork::Zero7) {
instruction.insert_instruction(
SELFDESTRUCT,
Instruction::new(arc_network_selfdestruct_zero7, 5000),
);
} else {
instruction.insert_instruction(
SELFDESTRUCT,
Instruction::new(arc_network_selfdestruct, 5000),
);
}
}
/// Construct a revert `FrameResult` for a subcall precompile rejection.
fn init_subcall_revert(message: &str, call_inputs: &CallInputs) -> FrameResult {
let revert_bytes = arc_precompiles::helpers::revert_message_to_bytes(message);
let mut gas = Gas::new(call_inputs.gas_limit);
// Charge a flat dispatch cost. If the caller doesn't have enough gas, consume all of it.
if !gas.record_regular_cost(SUBCALL_DISPATCH_COST) {
gas.spend_all();
}
let result = InterpreterResult::new(InstructionResult::Revert, revert_bytes, gas);
FrameResult::Call(CallOutcome {
result,
memory_offset: call_inputs.return_memory_offset.clone(),
was_precompile_called: true,
precompile_call_logs: Default::default(),
})
}
/// Construct an OOG `FrameResult` for a subcall that exceeded its gas budget.
fn subcall_oog(gas: Gas, return_memory_offset: std::ops::Range<usize>) -> FrameResult {
FrameResult::Call(CallOutcome {
result: InterpreterResult::new(InstructionResult::OutOfGas, Bytes::new(), gas),
memory_offset: return_memory_offset,
was_precompile_called: true,
precompile_call_logs: Default::default(),
})
}
/// Reject a subcall in static context. Mirrors `InstructionResult::CallNotAllowedInsideStatic`
/// halt semantics and the precompile-helper `check_staticcall` path: consume all caller gas.
fn init_subcall_static_revert(call_inputs: &CallInputs) -> FrameResult {
let revert_bytes = arc_precompiles::helpers::revert_message_to_bytes(
"subcall precompiles cannot be invoked in static context",
);
let mut gas = Gas::new(call_inputs.gas_limit);
gas.spend_all();
let result = InterpreterResult::new(InstructionResult::Revert, revert_bytes, gas);
FrameResult::Call(CallOutcome {
result,
memory_offset: call_inputs.return_memory_offset.clone(),
was_precompile_called: true,
precompile_call_logs: Default::default(),
})
}
/// Loads an account with code, recording its EIP-2929 access cost on `gas`.
/// Skips the DB load when the account is cold and `gas` can't cover it,
/// preventing warming as a side-effect of an intentional OOG.
/// Returns `None` on OOG (caller should `spend_all` and return).
fn load_account_with_code_metered<J: JournalTr>(
journal: &mut J,
address: Address,
gas: &mut Gas,
) -> Result<Option<AccountInfo>, <J::Database as revm::database_interface::Database>::Error> {
let skip_cold_load = gas.remaining() < revm_interpreter::gas::COLD_ACCOUNT_ACCESS_COST;
match journal.load_account_info_skip_cold_load(address, true, skip_cold_load) {
Ok(info) => {
let cost = if info.is_cold {
revm_interpreter::gas::COLD_ACCOUNT_ACCESS_COST
} else {
revm_interpreter::gas::WARM_STORAGE_READ_COST
};
if !gas.record_regular_cost(cost) {
return Ok(None);
}
Ok(Some(info.account.into_owned()))
}
Err(JournalLoadError::ColdLoadSkipped) => Ok(None),
Err(JournalLoadError::DBError(err)) => Err(err),
}
}
#[derive(Debug)]
pub struct ArcEvm<CTX, INSP, I, P, F = EthFrame<EthInterpreter>> {
/// Inner EVM type.
pub inner: RevmEvm<CTX, INSP, I, P, F>,
pub inspect: bool,
/// Feature flags for Arc hardforks active at the current block.
pub hardfork_flags: ArcHardforkFlags,
/// Registry of subcall-capable precompiles.
subcall_registry: Arc<SubcallRegistry>,
/// Active subcall continuations, keyed by the precompile call's depth.
subcall_continuations: HashMap<usize, SubcallContinuation>,
}
/// ArcEvm implementation, wrapping an inner revm EVM instance to apply handler
/// 1. Hook frame_init to add the EIP-7708 Transfer event log.
/// 2. Add the blocklist check for each frame.
/// 3. Check static context to the precompiles.
impl<CTX: ContextTr, INSP, P> ArcEvm<CTX, INSP, EthInstructions<EthInterpreter, CTX>, P> {
/// Create a new Arc EVM.
#[allow(clippy::too_many_arguments)]
pub fn new(
ctx: CTX,
inspector: INSP,
precompiles: P,
instruction: EthInstructions<EthInterpreter, CTX>,
inspect: bool,
hardfork_flags: ArcHardforkFlags,
subcall_registry: Arc<SubcallRegistry>,
) -> Self {
Self {
inner: RevmEvm {
ctx,
inspector,
instruction,
precompiles,
frame_stack: FrameStack::new(),
},
inspect,
hardfork_flags,
subcall_registry,
subcall_continuations: HashMap::new(),
}
}
}
/// Extracts transfer parameters (from, to, amount) from a Call frame input.
/// Returns None if the call scheme doesn't involve a value transfer.
fn extract_call_transfer_params(
inputs: &revm_interpreter::CallInputs,
) -> Option<(Address, Address, U256)> {
match inputs.scheme {
CallScheme::DelegateCall | CallScheme::StaticCall | CallScheme::CallCode => None,
CallScheme::Call => Some((
inputs.transfer_from(),
inputs.transfer_to(),
inputs.transfer_value().unwrap_or(U256::ZERO),
)),
}
}
fn frame_gas_limit(frame_input: &FrameInit) -> u64 {
match &frame_input.frame_input {
FrameInput::Call(inputs) => inputs.gas_limit,
FrameInput::Create(inputs) => inputs.gas_limit(),
FrameInput::Empty => 0,
}
}
/// Creates a revert that charges the actual SLOAD gas cost when metered, or OOGs if the
/// frame's gas budget is insufficient.
fn metered_revert(
frame_input: &FrameInit,
meter_sloads: bool,
gas_cost: u64,
reason: &str,
) -> BeforeFrameInitResult {
let gas_spent = if meter_sloads { gas_cost } else { 0 };
if gas_spent > 0 && frame_gas_limit(frame_input) < gas_spent {
BeforeFrameInitResult::Reverted(create_oog_frame_result(frame_input))
} else {
BeforeFrameInitResult::Reverted(create_frame_result(frame_input, reason, gas_spent))
}
}
/// Defensive revert for when a subcall interception fires on a non-Call frame.
/// This should never happen (the caller in `frame_init` checks for Call), but
/// avoids panicking in production.
fn non_call_frame_revert<F, E>(frame_input: &FrameInit) -> Result<ItemOrResult<F, FrameResult>, E> {
Ok(ItemOrResult::Result(create_frame_result(
frame_input,
"internal error: subcall interception on non-Call frame",
0,
)))
}
/// Resolves any `SharedBuffer` call input to concrete `Bytes`.
///
/// # Warning
///
/// Resolve the buffer before calling any child frames that could overwrite it.
///
/// Precompiles receive `CallInputs` but cannot dereference `SharedBuffer` references
/// because they lack access to the EVM context. This must be called before dispatching
/// to a subcall precompile's `init_subcall` method.
fn resolve_shared_buffer(ctx: &impl ContextTr, frame_input: &mut FrameInit) {
if let FrameInput::Call(ref mut inputs) = frame_input.frame_input {
if let revm::interpreter::interpreter_action::CallInput::SharedBuffer(_) = &inputs.input {
let resolved = inputs.input.bytes(ctx);
inputs.input = revm::interpreter::interpreter_action::CallInput::Bytes(resolved);
}
}
}
/// Returns whether a transfer log should be emitted for the given frame init result.
///
/// A log is kept when the call/create completed successfully.
/// CREATE results that succeed but have no address (nonce overflow) are excluded because
/// value was not actually transferred.
fn should_emit_transfer_log_for_result(result: &FrameResult) -> bool {
match result {
FrameResult::Create(create_outcome) => {
create_outcome.instruction_result().is_ok() && create_outcome.address.is_some()
}
FrameResult::Call(call_outcome) => call_outcome.instruction_result().is_ok(),
}
}
/// Returns whether a transfer log should be emitted for the given frame init outcome.
///
/// For `Item` (pending execution), always emit — REVM's internal frame checkpoint will
/// revert it if the frame later fails. For `Result` (synchronous completion), delegate
/// to [`should_emit_transfer_log_for_result`].
fn should_emit_transfer_log<T>(frame_res: &ItemOrResult<T, FrameResult>) -> bool {
match frame_res {
ItemOrResult::Item(_) => true,
ItemOrResult::Result(result) => should_emit_transfer_log_for_result(result),
}
}
/// Returns `true` if `frame_input` targets a precompile address.
///
/// Only CALL frames can target precompiles; CREATE never does.
fn is_precompile_call<CTX: ContextTr>(
frame_input: &FrameInit,
precompiles: &impl PrecompileProvider<CTX, Output = InterpreterResult>,
) -> bool {
match &frame_input.frame_input {
FrameInput::Call(inputs) => precompiles.contains(&inputs.bytecode_address),
_ => false,
}
}
/// Outcome of [`ArcEvm::checked_frame_init`].
///
/// Returning owned data (rather than a `FrameInitResult` reference) resolves borrow-checker
/// conflicts: the caller can reborrow individual fields of `self` after the method returns.
enum FrameInitOutcome {
/// Frame was pushed onto the stack; the execution loop will drive it.
Pushed,
/// Frame completed immediately (e.g. empty bytecode, allowlist rejection).
Immediate(FrameResult),
}
/// Mirrors `Evm::frame_init` from revm-handler, but takes individual field references instead
/// of `&mut self`. This enables borrow splitting at the call site: the returned reference borrows
/// only `frame_stack`, leaving `ctx` and other fields accessible.
///
/// See [`revm::handler::EvmTr::frame_init`] for the original.
fn init_frame<'fs, CTX, P>(
frame_stack: &'fs mut FrameStack<EthFrame<EthInterpreter>>,
ctx: &mut CTX,
precompiles: &mut P,
frame_input: FrameInit,
) -> Result<FrameInitResult<'fs, EthFrame<EthInterpreter>>, ContextDbError<CTX>>
where
CTX: ContextTr,
P: PrecompileProvider<CTX, Output = InterpreterResult>,
{
let is_first_init = frame_stack.index().is_none();
let new_frame = if is_first_init {
frame_stack.start_init()
} else {
frame_stack.get_next()
};
let res = EthFrame::init_with_context(new_frame, ctx, precompiles, frame_input)?;
Ok(res.map_item(|token| {
if is_first_init {
unsafe { frame_stack.end_init(token) };
} else {
unsafe { frame_stack.push(token) };
}
frame_stack.get()
}))
}
fn frame_init_outcome(
frame_res: FrameInitResult<'_, EthFrame<EthInterpreter>>,
) -> FrameInitOutcome {
match frame_res {
ItemOrResult::Item(_) => FrameInitOutcome::Pushed,
ItemOrResult::Result(result) => FrameInitOutcome::Immediate(result),
}
}
/// ArcEvm implementation for customized operations.
impl<CTX: ContextTr, INSP, I, P> ArcEvm<CTX, INSP, I, P> {
/// Checks if an address is blocklisted by reading from the native coin control precompile storage.
///
/// Returns `(is_blocklisted, is_cold)`. The `is_cold` flag, together with the `sload_cost`
/// and `metered_revert` plumbing it feeds, is retained as dormant infrastructure: blocklist
/// SLOADs are currently unmetered (callers pass `meter_sloads = false` and the cost is
/// discarded), but the wiring is kept so re-enabling metering is a single-flag flip rather
/// than a re-architecture.
///
/// Note: This calls `journal.sload()` directly, bypassing the interpreter, so revm does not
/// automatically meter gas for these reads.
fn is_address_blocklisted(
&mut self,
address: Address,
) -> Result<(bool, bool), ContextDbError<CTX>> {
let storage_slot = compute_is_blocklisted_storage_slot(address).into();
// Read blocklist status: non-zero value means blocklisted
let state_load = self
.inner
.ctx
.journal_mut()
.sload(NATIVE_COIN_CONTROL_ADDRESS, storage_slot)?;
Ok((is_blocklisted_status(state_load.data), state_load.is_cold))
}
fn sload_cost(&self, is_cold: bool) -> u64 {
if is_cold {
revm_interpreter::gas::COLD_SLOAD_COST
} else {
revm_interpreter::gas::WARM_STORAGE_READ_COST
}
}
/// Extracts transfer parameters (from, to, amount) from a Create frame input.
///
/// For value-carrying CREATE2 frames, this also normalizes the frame scheme to
/// `CreateScheme::Custom { address }` after deriving the address, so revm reuses
/// the precomputed address during frame initialization instead of hashing initcode again.
///
/// Returns None if value is zero or scheme is already Custom.
fn extract_and_normalize_create_transfer_params(
&mut self,
inputs: &mut revm_interpreter::CreateInputs,
depth: usize,
) -> Result<Option<(Address, Address, U256)>, ContextDbError<CTX>> {
if inputs.value().is_zero() {
return Ok(None);
}
match inputs.scheme() {
CreateScheme::Create => {
let nonce = if depth == 0 {
// First frame: use transaction nonce directly
self.inner.ctx.tx().nonce()
} else {
// Nested frame: look up nonce in journal
self.inner
.ctx
.journal_mut()
.load_account(inputs.caller())?
.info
.nonce
};
Ok(Some((
inputs.caller(),
inputs.created_address(nonce),
inputs.value(),
)))
}
CreateScheme::Create2 { salt: _ } => {
// Nonce doesn't matter for CREATE2
let created_address = inputs.created_address(0);
// Arc needs the created address before revm initializes the create frame
// for blocklist checks and transfer logs. Normalize the frame to a custom
// create so revm reuses the precomputed address instead of hashing the
// initcode a second time. This can be removed after upgrading to a
// revm release containing bluealloy/revm#3664.
inputs.set_scheme(CreateScheme::Custom {
address: created_address,
});
Ok(Some((inputs.caller(), created_address, inputs.value())))
}
CreateScheme::Custom { address: _ } => Ok(None),
}
}
/// Checks blocklist status for transfer participants and returns appropriate result.
fn check_blocklist_and_create_log(
&mut self,
from: Address,
to: Address,
amount: U256,
frame_input: &FrameInit,
) -> Result<BeforeFrameInitResult, ContextDbError<CTX>> {
// Meter SLOAD gas on revert for nested frames (depth > 0).
// Currently SLOAD gas metering is disabled — blocklist checks are unmetered.
let meter_sloads = false;
// Reject CALL/CREATE value transfers involving the zero address.
// This prevents accidental burn/mint semantics at the EVM execution layer.
//
// Note: this check only applies to CALL/CREATE frame value transfers — it does NOT
// affect the NativeCoinAuthority precompile, which legitimately uses Address::ZERO in
// ERC-20 Transfer events for mint (from=0x0) and burn (to=0x0). The precompile operates
// via direct journal balance mutations within its own frame, never triggering frame_init.
if from == Address::ZERO || to == Address::ZERO {
return Ok(BeforeFrameInitResult::Reverted(create_frame_result(
frame_input,
ERR_ZERO_ADDRESS,
0,
)));
}
let (from_blocklisted, from_is_cold) = self.is_address_blocklisted(from)?;
let from_sload_cost = self.sload_cost(from_is_cold);
if from_blocklisted {
return Ok(metered_revert(
frame_input,
meter_sloads,
from_sload_cost,
ERR_BLOCKED_ADDRESS,
));
}
let (to_blocklisted, to_is_cold) = self.is_address_blocklisted(to)?;
let to_sload_cost = self.sload_cost(to_is_cold);
// Both are PRECOMPILE_SLOAD_GAS_COST (2,100); sum fits in u64
#[allow(clippy::arithmetic_side_effects)]
let total_sload_cost = from_sload_cost + to_sload_cost;
if to_blocklisted {
return Ok(metered_revert(
frame_input,
meter_sloads,
total_sload_cost,
ERR_BLOCKED_ADDRESS,
));
}
// Probe inside a checkpoint once the cold-state preserving behavior is active, so this
// unmetered selfdestructed-target check does not leave a previously-cold account warm.
let target_is_selfdestructed = {
let journal = self.inner.journal_mut();
if self.hardfork_flags.is_active(ArcHardfork::Zero7) {
let checkpoint = journal.checkpoint();
let result = journal
.load_account(to)
.map(|target_account| target_account.is_selfdestructed());
journal.checkpoint_revert(checkpoint);
result?
} else {
journal
.load_account(to)
.map(|target_account| target_account.is_selfdestructed())?
}
};
if target_is_selfdestructed {
return Ok(metered_revert(
frame_input,
meter_sloads,
total_sload_cost,
ERR_SELFDESTRUCTED_BALANCE_INCREASED,
));
}
if from == to {
// EIP-7708: self-transfers do not emit a log.
Ok(BeforeFrameInitResult::Checked(total_sload_cost))
} else {
Ok(BeforeFrameInitResult::Log(
create_eip7708_transfer_log(from, to, amount),
total_sload_cost,
))
}
}
pub(crate) fn before_frame_init(
&mut self,
frame_input: &mut FrameInit,
) -> Result<BeforeFrameInitResult, ContextDbError<CTX>> {
// Extract transfer parameters based on frame type
let transfer_params = match &mut frame_input.frame_input {
FrameInput::Empty => None,
FrameInput::Create(inputs) => {
self.extract_and_normalize_create_transfer_params(inputs, frame_input.depth)?
}
FrameInput::Call(inputs) => extract_call_transfer_params(inputs),
};
// Process transfer if present and non-zero
match transfer_params {
Some((from, to, amount)) if !amount.is_zero() => {
self.check_blocklist_and_create_log(from, to, amount, frame_input)
}
_ => Ok(BeforeFrameInitResult::None),
}
}
}
// Implement EvmTr for ArcEvm
// ref: op-revm v12.0.1 implementation https://github.com/bluealloy/revm/blob/v97/crates/op-revm/src/evm.rs#L95
impl<CTX, INSP, I, P> EvmTr for ArcEvm<CTX, INSP, I, P>
where
CTX: ContextTr,
I: InstructionProvider<Context = CTX, InterpreterTypes = EthInterpreter>,
P: PrecompileProvider<CTX, Output = InterpreterResult>,
{
type Context = CTX;
type Instructions = I;
type Precompiles = P;
type Frame = EthFrame<EthInterpreter>;
#[inline]
fn all(
&self,
) -> (
&Self::Context,
&Self::Instructions,
&Self::Precompiles,
&FrameStack<Self::Frame>,
) {
self.inner.all()
}
#[inline]
fn all_mut(
&mut self,
) -> (
&mut Self::Context,
&mut Self::Instructions,
&mut Self::Precompiles,
&mut FrameStack<Self::Frame>,
) {
self.inner.all_mut()
}
/// Initializes the frame for the given frame input. Frame is pushed to the frame stack.
#[inline]
fn frame_init(
&mut self,
mut frame_input: <EthFrame as FrameTr>::FrameInit,
) -> Result<FrameInitResult<'_, Self::Frame>, ContextDbError<CTX>> {
// Subcall precompiles must be checked first: they reject value transfers, so
// the parent's `before_frame_init` is a no-op (no transfer to check). Running
// `checked_frame_init` for the parent would incorrectly push a frame for the
// precompile address onto the stack.
if let FrameInput::Call(ref call_inputs) = frame_input.frame_input {
if let Some((precompile, allowed_callers)) =
self.subcall_registry.get(&call_inputs.target_address)
{
if !allowed_callers.is_allowed(&call_inputs.caller) {
return Ok(ItemOrResult::Result(init_subcall_revert(
"unauthorized caller",
call_inputs,
)));
}
// Clone precompile to release the immutable borrow on self.subcall_registry
// before taking &mut self for before_frame_init.
let precompile = precompile.clone();
// Defense-in-depth: run before_frame_init on the parent frame even though
// subcall precompiles currently reject value transfers (making this a no-op).
// If a future subcall precompile allows value, the log needs to be handled here.
match self.before_frame_init(&mut frame_input)? {
BeforeFrameInitResult::Reverted(res) => {
return Ok(ItemOrResult::Result(res));
}
BeforeFrameInitResult::Log(..)
| BeforeFrameInitResult::Checked(_)
| BeforeFrameInitResult::None => {}
}
return self.init_subcall(frame_input, precompile);
}
}
// Standard path: blocklist checks, revm frame init, transfer log.
match self.checked_frame_init(frame_input)? {
FrameInitOutcome::Pushed => Ok(ItemOrResult::Item(self.inner.frame_stack.get())),
FrameInitOutcome::Immediate(result) => Ok(ItemOrResult::Result(result)),
}
}
/// Run the frame from the top of the stack. Returns the frame init or result.
#[inline]
fn frame_run(&mut self) -> Result<FrameInitOrResult<EthFrame>, ContextDbError<CTX>> {
self.inner.frame_run()
}
/// Returns the result of the frame to the caller. Frame is popped from the frame stack.
///
/// Overrides the default revm behavior to intercept subcall continuations:
/// when a child frame completes and a continuation exists at `depth - 1`,
/// we finalize the subcall via `complete_subcall` instead of returning the raw child result.
#[inline]
fn frame_return_result(
&mut self,
result: <Self::Frame as FrameTr>::FrameResult,
) -> Result<Option<<Self::Frame as FrameTr>::FrameResult>, ContextDbError<Self::Context>> {
let frame_was_finished = self.inner.frame_stack.get().is_finished();
// Capture the finished frame's depth before popping — needed for subcall continuation
// lookup when the pop leaves the stack empty (direct EOA -> precompile calls).
let finished_depth = self.inner.frame_stack.get().depth;
// Pop the finished frame (revm default behavior)
if frame_was_finished {
self.inner.frame_stack.pop();
}
let stack_empty = self.inner.frame_stack.index().is_none();
// Check for a subcall continuation, but ONLY when a frame actually finished execution.
//
// When `frame_was_finished` is true, this result came from a child frame that ran to
// completion. The continuation was stored at the precompile's depth (finished_depth - 1).
//
// When `frame_was_finished` is false, this is an immediate result from `frame_init`
// (e.g., init_subcall already ran complete_subcall for a CallTooDeep).
// The stack top is the still-running parent frame, and `finished_depth` is the parent's
// depth — not the child's. Looking up `finished_depth - 1` would match the grandparent's
// continuation, corrupting state.
if frame_was_finished {
let continuation_key = finished_depth.checked_sub(1);
if let Some(key) = continuation_key {
if let Some(continuation) = self.subcall_continuations.remove(&key) {
let final_result = self.complete_subcall(result, continuation)?;
if stack_empty {
// Direct EOA -> precompile: no parent frame to propagate to.
return Ok(Some(final_result));
}
// Propagate to the parent frame
self.inner
.frame_stack
.get()
.return_result::<_, ContextDbError<CTX>>(
&mut self.inner.ctx,
final_result,
)?;
return Ok(None);
}
}
}
// If stack is empty, this is the top-level result — return it
if stack_empty {
return Ok(Some(result));
}
// Propagate to the parent frame. This covers:
// - Normal (non-subcall) frame returns
// - Immediate results from frame_init (complete_subcall already ran)
self.inner
.frame_stack
.get()
.return_result::<_, ContextDbError<CTX>>(&mut self.inner.ctx, result)?;
Ok(None)
}
}
/// Subcall interception methods and shared frame-stack helpers.
///
/// These are separated from the `EvmTr` impl because they are private helper methods,
/// not trait methods. They share the same trait bounds as the `EvmTr` impl.
impl<CTX, INSP, I, P> ArcEvm<CTX, INSP, I, P>
where
CTX: ContextTr,
I: InstructionProvider<Context = CTX, InterpreterTypes = EthInterpreter>,
P: PrecompileProvider<CTX, Output = InterpreterResult>,
{
/// Runs `before_frame_init` (blocklist checks, transfer log), then initializes the
/// frame via revm's standard machinery and emits the transfer log on success.
///
/// For precompile CALLs, the EIP-7708 Transfer log is pushed before frame init
/// (wrapped in a journal checkpoint) so it precedes precompile-emitted logs. For all
/// other cases, the log is pushed after frame init only on success.
///
/// Returns an owned [`FrameInitOutcome`] so the caller can reborrow `self` fields
/// after the call without borrow-checker conflicts.
fn checked_frame_init(
&mut self,
mut frame_input: FrameInit,
) -> Result<FrameInitOutcome, ContextDbError<CTX>> {
let (maybe_log, _sload_gas) = match self.before_frame_init(&mut frame_input)? {
BeforeFrameInitResult::Reverted(res) => {
return Ok(FrameInitOutcome::Immediate(res));
}
BeforeFrameInitResult::Log(log, gas) => (Some(log), gas),
BeforeFrameInitResult::Checked(gas) => (None, gas),
BeforeFrameInitResult::None => (None, 0),
};
// Log emission strategy for the EIP-7708 Transfer log:
//
// **Precompile CALL**: Push the Transfer log BEFORE init_frame so it
// precedes any logs the precompile emits (EIP-7708 requires the native Transfer
// log to appear before precompile-emitted logs). The precompile runs synchronously
// inside init_with_context and returns a Result, so a journal checkpoint can
// correctly commit/revert based on the outcome.
//
// **All other cases** (non-precompile CALLs/CREATEs): Execute first, then push the log only if the result indicates
// success. For non-precompile frames that return Item (pending execution), REVM's
// internal frame checkpoint already covers this log — if the frame later reverts,
// logs.truncate(log_i) removes it automatically.
if is_precompile_call(&frame_input, &self.inner.precompiles) {
self.init_precompile_frame_with_transfer_log(frame_input, maybe_log)
} else {
self.init_deferred_frame_with_transfer_log(frame_input, maybe_log)
}
}
fn init_precompile_frame_with_transfer_log(
&mut self,
frame_input: FrameInit,
maybe_log: Option<Log>,
) -> Result<FrameInitOutcome, ContextDbError<CTX>> {
// Push the Transfer log before init_frame so it precedes any logs the precompile emits.
let log_checkpoint = if let Some(log) = maybe_log {
let cp = self.inner.ctx.journal_mut().checkpoint();
self.inner.ctx.journal_mut().log(log);
Some(cp)
} else {
None
};
let res = init_frame(
&mut self.inner.frame_stack,
&mut self.inner.ctx,
&mut self.inner.precompiles,
frame_input,
)?;
if let Some(cp) = log_checkpoint {
if should_emit_transfer_log(&res) {
self.inner.ctx.journal_mut().checkpoint_commit();
} else {
self.inner.ctx.journal_mut().checkpoint_revert(cp);
}
}
Ok(frame_init_outcome(res))
}
fn init_deferred_frame_with_transfer_log(
&mut self,
frame_input: FrameInit,
maybe_log: Option<Log>,
) -> Result<FrameInitOutcome, ContextDbError<CTX>> {
let res = init_frame(
&mut self.inner.frame_stack,
&mut self.inner.ctx,
&mut self.inner.precompiles,
frame_input,
)?;
if let Some(log) = maybe_log {
if should_emit_transfer_log(&res) {
self.inner.ctx.journal_mut().log(log);
}
}
Ok(frame_init_outcome(res))
}
/// Intercept a call to a subcall-capable precompile and initialize the child frame.
///
/// Decodes the precompile input via [`SubcallPrecompile::init_subcall`], stores a
/// continuation, and initializes the child frame via [`checked_frame_init`] so that it
/// goes through `before_frame_init` hooks (blocklist checks, transfer log).
fn init_subcall(
&mut self,
mut frame_input: <EthFrame as FrameTr>::FrameInit,
precompile: Arc<dyn SubcallPrecompile>,
) -> Result<FrameInitResult<'_, EthFrame<EthInterpreter>>, ContextDbError<CTX>> {
let call_inputs = match &frame_input.frame_input {
FrameInput::Call(inputs) => inputs.as_ref(),
_ => return non_call_frame_revert(&frame_input),
};
// Reject non-CALL schemes (DELEGATECALL, STATICCALL, CALLCODE).
// Subcall precompiles only support the CALL scheme — other schemes have
// incompatible semantics (e.g. DELEGATECALL runs code in the caller's
// context, STATICCALL prohibits state changes).
if call_inputs.scheme != CallScheme::Call {
return Ok(ItemOrResult::Result(init_subcall_revert(
"subcall precompiles only support CALL scheme",
call_inputs,
)));
}
// Reject static context — even when the scheme is CALL, `is_static` can be true
// if this call is nested inside a STATICCALL frame higher in the call stack.
// Consume all gas to match upstream `CallNotAllowedInsideStatic` halt semantics
// and the standard precompile-helper `check_staticcall` path.
if call_inputs.is_static {
return Ok(ItemOrResult::Result(init_subcall_static_revert(
call_inputs,
)));
}
// Reject calls with value attached. The subcall framework intercepts frame_init,
// bypassing revm's init_with_context for the precompile call itself, so the value
// transfer from caller → precompile address is never executed. Forwarding value to
// the child would require explicit transfer logic that is not yet implemented.
if call_inputs.transfers_value() {
return Ok(ItemOrResult::Result(init_subcall_revert(
"subcall precompiles do not support value transfers",
call_inputs,
)));
}
// Resolve SharedBuffer → Bytes before handing inputs to the precompile, which
// doesn't have access to the EVM context needed to dereference shared memory.
resolve_shared_buffer(&self.inner.ctx, &mut frame_input);
// Re-extract call_inputs after the mutable borrow in resolve_shared_buffer.
let call_inputs = match &frame_input.frame_input {
FrameInput::Call(inputs) => inputs.as_ref(),
_ => return non_call_frame_revert(&frame_input),
};
let init_result = match precompile.init_subcall(call_inputs) {
Ok(result) => result,
Err(err) => {
return Ok(ItemOrResult::Result(init_subcall_revert(
&err.to_string(),
call_inputs,
)));
}
};
// Prevent sender spoofing by contracts: if the precompile changes the caller
// (e.g. callFrom), the new caller must be tx.origin (the signing EOA).
if init_result.child_inputs.caller != call_inputs.caller
&& init_result.child_inputs.caller != self.inner.ctx.tx().caller()
{
return Ok(ItemOrResult::Result(init_subcall_revert(
"sender spoofing requires tx.origin as sender",
call_inputs,
)));
}
let return_memory_offset = call_inputs.return_memory_offset.clone();
// Pre-load the child's caller and target accounts into the journal. The normal EVM
// execution path has these already loaded (caller is the executing frame, target was
// loaded by the CALL opcode handler), but we're constructing a synthetic child frame
// with a potentially-unseen spoofed sender and arbitrary target.
//
// Both must be present in the journal state map before `make_call_frame` calls
// `transfer_loaded`, which panics on missing accounts. The target is loaded with
// code to support EIP-7702 delegation resolution below.
//
// These loads happen BEFORE the checkpoint so that warmups persist regardless of
// outcome (OOG, child revert, or parent rejection). This matches normal EVM CALL
// semantics where target warming is a side-effect of the CALL opcode, not the
// called code.
//
// Note: when caller==target, `load_account(caller)` warms the address first, so
// `target_load.is_cold` is false and only the warm cost (100) is charged.
let mut child_inputs = init_result.child_inputs;
self.inner
.ctx
.journal_mut()
.load_account(child_inputs.caller)?;
// Track gas for the subcall overhead: ABI decode + target access + delegation.
// Access costs are charged explicitly because our pre-loads warm the accounts,
// so revm's internal CALL handler won't charge them.
let mut gas = Gas::new(call_inputs.gas_limit);
if !gas.record_regular_cost(init_result.gas_overhead) {
gas.spend_all();
return Ok(ItemOrResult::Result(subcall_oog(
gas,
call_inputs.return_memory_offset.clone(),
)));
}
let Some(target) = load_account_with_code_metered(
self.inner.ctx.journal_mut(),
child_inputs.target_address,
&mut gas,
)?
else {
gas.spend_all();
return Ok(ItemOrResult::Result(subcall_oog(