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