revm_interpreter/
interpreter_types.rs

1use crate::{CallInput, InstructionResult, InterpreterAction};
2use core::cell::Ref;
3use core::ops::{Deref, Range};
4use primitives::{hardfork::SpecId, Address, Bytes, B256, U256};
5
6/// Helper function to read immediates data from the bytecode
7pub trait Immediates {
8    /// Reads next 16 bits as signed integer from the bytecode.
9    #[inline]
10    fn read_i16(&self) -> i16 {
11        self.read_u16() as i16
12    }
13    /// Reads next 16 bits as unsigned integer from the bytecode.
14    fn read_u16(&self) -> u16;
15
16    /// Reads next 8 bits as signed integer from the bytecode.
17    #[inline]
18    fn read_i8(&self) -> i8 {
19        self.read_u8() as i8
20    }
21
22    /// Reads next 8 bits as unsigned integer from the bytecode.
23    fn read_u8(&self) -> u8;
24
25    /// Reads next 16 bits as signed integer from the bytecode at given offset.
26    #[inline]
27    fn read_offset_i16(&self, offset: isize) -> i16 {
28        self.read_offset_u16(offset) as i16
29    }
30
31    /// Reads next 16 bits as unsigned integer from the bytecode at given offset.
32    fn read_offset_u16(&self, offset: isize) -> u16;
33
34    /// Reads next `len` bytes from the bytecode.
35    ///
36    /// Used by PUSH opcode.
37    fn read_slice(&self, len: usize) -> &[u8];
38}
39
40/// Trait for fetching inputs of the call.
41pub trait InputsTr {
42    /// Returns target address of the call.
43    fn target_address(&self) -> Address;
44    /// Returns bytecode address of the call. For DELEGATECALL this address will be different from target address.
45    /// And if initcode is called this address will be [`None`].
46    fn bytecode_address(&self) -> Option<&Address>;
47    /// Returns caller address of the call.
48    fn caller_address(&self) -> Address;
49    /// Returns input of the call.
50    fn input(&self) -> &CallInput;
51    /// Returns call value of the call.
52    fn call_value(&self) -> U256;
53}
54
55/// Trait needed for legacy bytecode.
56///
57/// Used in [`bytecode::opcode::CODECOPY`] and [`bytecode::opcode::CODESIZE`] opcodes.
58pub trait LegacyBytecode {
59    /// Returns current bytecode original length. Used in [`bytecode::opcode::CODESIZE`] opcode.
60    fn bytecode_len(&self) -> usize;
61    /// Returns current bytecode original slice. Used in [`bytecode::opcode::CODECOPY`] opcode.
62    fn bytecode_slice(&self) -> &[u8];
63}
64
65/// Trait for Interpreter to be able to jump
66pub trait Jumps {
67    /// Relative jumps does not require checking for overflow.
68    fn relative_jump(&mut self, offset: isize);
69    /// Absolute jumps require checking for overflow and if target is a jump destination
70    /// from jump table.
71    fn absolute_jump(&mut self, offset: usize);
72    /// Check legacy jump destination from jump table.
73    fn is_valid_legacy_jump(&mut self, offset: usize) -> bool;
74    /// Returns current program counter.
75    fn pc(&self) -> usize;
76    /// Returns instruction opcode.
77    fn opcode(&self) -> u8;
78}
79
80/// Trait for Interpreter memory operations.
81pub trait MemoryTr {
82    /// Sets memory data at given offset from data with a given data_offset and len.
83    ///
84    /// # Panics
85    ///
86    /// Panics if range is out of scope of allocated memory.
87    fn set_data(&mut self, memory_offset: usize, data_offset: usize, len: usize, data: &[u8]);
88
89    /// Inner clone part of memory from global context to local context.
90    /// This is used to clone calldata to memory.
91    ///
92    /// # Panics
93    ///
94    /// Panics if range is out of scope of allocated memory.
95    fn set_data_from_global(
96        &mut self,
97        memory_offset: usize,
98        data_offset: usize,
99        len: usize,
100        data_range: Range<usize>,
101    );
102
103    /// Memory slice with global range. This range
104    ///
105    /// # Panics
106    ///
107    /// Panics if range is out of scope of allocated memory.
108    fn global_slice(&self, range: Range<usize>) -> Ref<'_, [u8]>;
109
110    /// Offset of local context of memory.
111    fn local_memory_offset(&self) -> usize;
112
113    /// Sets memory data at given offset.
114    ///
115    /// # Panics
116    ///
117    /// Panics if range is out of scope of allocated memory.
118    fn set(&mut self, memory_offset: usize, data: &[u8]);
119
120    /// Returns memory size.
121    fn size(&self) -> usize;
122
123    /// Copies memory data from source to destination.
124    ///
125    /// # Panics
126    /// Panics if range is out of scope of allocated memory.
127    fn copy(&mut self, destination: usize, source: usize, len: usize);
128
129    /// Memory slice with range
130    ///
131    /// # Panics
132    ///
133    /// Panics if range is out of scope of allocated memory.
134    fn slice(&self, range: Range<usize>) -> Ref<'_, [u8]>;
135
136    /// Memory slice len
137    ///
138    /// Uses [`slice`][MemoryTr::slice] internally.
139    fn slice_len(&self, offset: usize, len: usize) -> impl Deref<Target = [u8]> + '_ {
140        self.slice(offset..offset + len)
141    }
142
143    /// Resizes memory to new size
144    ///
145    /// # Note
146    ///
147    /// It checks memory limits.
148    fn resize(&mut self, new_size: usize) -> bool;
149}
150
151/// Functions needed for Interpreter Stack operations.
152pub trait StackTr {
153    /// Returns stack length.
154    fn len(&self) -> usize;
155
156    /// Returns `true` if stack is empty.
157    fn is_empty(&self) -> bool {
158        self.len() == 0
159    }
160
161    /// Clears the stack.
162    fn clear(&mut self);
163
164    /// Pushes values to the stack.
165    ///
166    /// Returns `true` if push was successful, `false` if stack overflow.
167    ///
168    /// # Note
169    /// Error is internally set in interpreter.
170    #[must_use]
171    fn push(&mut self, value: U256) -> bool;
172
173    /// Pushes B256 value to the stack.
174    ///
175    /// Internally converts B256 to U256 and then calls [`StackTr::push`].
176    #[must_use]
177    fn push_b256(&mut self, value: B256) -> bool {
178        self.push(value.into())
179    }
180
181    /// Pops value from the stack.
182    #[must_use]
183    fn popn<const N: usize>(&mut self) -> Option<[U256; N]>;
184
185    /// Pop N values from the stack and return top value.
186    #[must_use]
187    fn popn_top<const POPN: usize>(&mut self) -> Option<([U256; POPN], &mut U256)>;
188
189    /// Returns top value from the stack.
190    #[must_use]
191    fn top(&mut self) -> Option<&mut U256> {
192        self.popn_top::<0>().map(|(_, top)| top)
193    }
194
195    /// Pops one value from the stack.
196    #[must_use]
197    fn pop(&mut self) -> Option<U256> {
198        self.popn::<1>().map(|[value]| value)
199    }
200
201    /// Pops address from the stack.
202    ///
203    /// Internally call [`StackTr::pop`] and converts [`U256`] into [`Address`].
204    #[must_use]
205    fn pop_address(&mut self) -> Option<Address> {
206        self.pop().map(|value| Address::from(value.to_be_bytes()))
207    }
208
209    /// Exchanges two values on the stack.
210    ///
211    /// Indexes are based from the top of the stack.
212    ///
213    /// Returns `true` if swap was successful, `false` if stack underflow.
214    #[must_use]
215    fn exchange(&mut self, n: usize, m: usize) -> bool;
216
217    /// Duplicates the `N`th value from the top of the stack.
218    ///
219    /// Index is based from the top of the stack.
220    ///
221    /// Returns `true` if duplicate was successful, `false` if stack underflow.
222    #[must_use]
223    fn dup(&mut self, n: usize) -> bool;
224}
225
226/// Returns return data.
227pub trait ReturnData {
228    /// Returns return data.
229    fn buffer(&self) -> &Bytes;
230
231    /// Sets return buffer.
232    fn set_buffer(&mut self, bytes: Bytes);
233
234    /// Clears return buffer.
235    fn clear(&mut self) {
236        self.set_buffer(Bytes::new());
237    }
238}
239
240/// Trait controls execution of the loop.
241pub trait LoopControl {
242    /// Returns `true` if the loop should continue.
243    #[inline]
244    fn is_not_end(&self) -> bool {
245        !self.is_end()
246    }
247    /// Is end of the loop.
248    fn is_end(&self) -> bool;
249    /// Reverts to previous instruction pointer.
250    ///
251    /// After the loop is finished, the instruction pointer is set to the previous one.
252    fn revert_to_previous_pointer(&mut self);
253    /// Set return action and set instruction pointer to null. Preserve previous pointer
254    ///
255    /// Previous pointer can be restored by calling [`LoopControl::revert_to_previous_pointer`].
256    fn set_action(&mut self, action: InterpreterAction);
257    /// Takes next action.
258    fn action(&mut self) -> &mut Option<InterpreterAction>;
259    /// Returns instruction result
260    #[inline]
261    fn instruction_result(&mut self) -> Option<InstructionResult> {
262        self.action()
263            .as_ref()
264            .and_then(|action| action.instruction_result())
265    }
266}
267
268/// Runtime flags that control interpreter execution behavior.
269pub trait RuntimeFlag {
270    /// Returns true if the current execution context is static (read-only).
271    fn is_static(&self) -> bool;
272    /// Returns the current EVM specification ID.
273    fn spec_id(&self) -> SpecId;
274}
275
276/// Trait for interpreter execution.
277pub trait Interp {
278    /// The instruction type.
279    type Instruction;
280    /// The action type returned after execution.
281    type Action;
282
283    /// Runs the interpreter with the given instruction table.
284    fn run(&mut self, instructions: &[Self::Instruction; 256]) -> Self::Action;
285}
286
287/// Trait defining the component types used by an interpreter implementation.
288pub trait InterpreterTypes {
289    /// Stack implementation type.
290    type Stack: StackTr;
291    /// Memory implementation type.
292    type Memory: MemoryTr;
293    /// Bytecode implementation type.
294    type Bytecode: Jumps + Immediates + LoopControl + LegacyBytecode;
295    /// Return data implementation type.
296    type ReturnData: ReturnData;
297    /// Input data implementation type.
298    type Input: InputsTr;
299    /// Runtime flags implementation type.
300    type RuntimeFlag: RuntimeFlag;
301    /// Extended functionality type.
302    type Extend;
303    /// Output type for execution results.
304    type Output;
305}