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 if the memory allocation fits under gas cap.
148    fn resize(&mut self, new_size: usize) -> bool;
149
150    /// Returns `true` if the `new_size` for the current context memory will
151    /// make the shared buffer length exceed the `memory_limit`.
152    #[cfg(feature = "memory_limit")]
153    fn limit_reached(&self, offset: usize, len: usize) -> bool;
154}
155
156/// Functions needed for Interpreter Stack operations.
157pub trait StackTr {
158    /// Returns stack length.
159    fn len(&self) -> usize;
160
161    /// Returns stack content.
162    fn data(&self) -> &[U256];
163
164    /// Returns `true` if stack is empty.
165    fn is_empty(&self) -> bool {
166        self.len() == 0
167    }
168
169    /// Clears the stack.
170    fn clear(&mut self);
171
172    /// Pushes values to the stack.
173    ///
174    /// Returns `true` if push was successful, `false` if stack overflow.
175    ///
176    /// # Note
177    /// Error is internally set in interpreter.
178    #[must_use]
179    fn push(&mut self, value: U256) -> bool;
180
181    /// Pushes slice to the stack.
182    ///
183    /// Returns `true` if push was successful, `false` if stack overflow.
184    ///
185    /// # Note
186    /// Error is internally set in interpreter.
187    fn push_slice(&mut self, slice: &[u8]) -> bool;
188
189    /// Pushes B256 value to the stack.
190    ///
191    /// Internally converts B256 to U256 and then calls [`StackTr::push`].
192    #[must_use]
193    fn push_b256(&mut self, value: B256) -> bool {
194        self.push(value.into())
195    }
196
197    /// Pops value from the stack.
198    #[must_use]
199    fn popn<const N: usize>(&mut self) -> Option<[U256; N]>;
200
201    /// Pop N values from the stack and return top value.
202    #[must_use]
203    fn popn_top<const POPN: usize>(&mut self) -> Option<([U256; POPN], &mut U256)>;
204
205    /// Returns top value from the stack.
206    #[must_use]
207    fn top(&mut self) -> Option<&mut U256> {
208        self.popn_top().map(|([], top)| top)
209    }
210
211    /// Pops one value from the stack.
212    #[must_use]
213    fn pop(&mut self) -> Option<U256> {
214        self.popn::<1>().map(|[value]| value)
215    }
216
217    /// Pops address from the stack.
218    ///
219    /// Internally call [`StackTr::pop`] and converts [`U256`] into [`Address`].
220    #[must_use]
221    fn pop_address(&mut self) -> Option<Address> {
222        self.pop().map(|value| Address::from(value.to_be_bytes()))
223    }
224
225    /// Exchanges two values on the stack.
226    ///
227    /// Indexes are based from the top of the stack.
228    ///
229    /// Returns `true` if swap was successful, `false` if stack underflow.
230    #[must_use]
231    fn exchange(&mut self, n: usize, m: usize) -> bool;
232
233    /// Duplicates the `N`th value from the top of the stack.
234    ///
235    /// Index is based from the top of the stack.
236    ///
237    /// Returns `true` if duplicate was successful, `false` if stack underflow.
238    #[must_use]
239    fn dup(&mut self, n: usize) -> bool;
240}
241
242/// Returns return data.
243pub trait ReturnData {
244    /// Returns return data.
245    fn buffer(&self) -> &Bytes;
246
247    /// Sets return buffer.
248    fn set_buffer(&mut self, bytes: Bytes);
249
250    /// Clears return buffer.
251    fn clear(&mut self) {
252        self.set_buffer(Bytes::new());
253    }
254}
255
256/// Trait controls execution of the loop.
257pub trait LoopControl {
258    /// Returns `true` if the loop should continue.
259    fn is_not_end(&self) -> bool;
260    /// Is end of the loop.
261    #[inline]
262    fn is_end(&self) -> bool {
263        !self.is_not_end()
264    }
265    /// Sets the `end` flag internally. Action should be taken after.
266    fn reset_action(&mut self);
267    /// Set return action.
268    fn set_action(&mut self, action: InterpreterAction);
269    /// Returns the current action.
270    fn action(&mut self) -> &mut Option<InterpreterAction>;
271    /// Returns instruction result
272    #[inline]
273    fn instruction_result(&mut self) -> Option<InstructionResult> {
274        self.action()
275            .as_ref()
276            .and_then(|action| action.instruction_result())
277    }
278}
279
280/// Runtime flags that control interpreter execution behavior.
281pub trait RuntimeFlag {
282    /// Returns true if the current execution context is static (read-only).
283    fn is_static(&self) -> bool;
284    /// Returns the current EVM specification ID.
285    fn spec_id(&self) -> SpecId;
286}
287
288/// Trait for interpreter execution.
289pub trait Interp {
290    /// The instruction type.
291    type Instruction;
292    /// The action type returned after execution.
293    type Action;
294
295    /// Runs the interpreter with the given instruction table.
296    fn run(&mut self, instructions: &[Self::Instruction; 256]) -> Self::Action;
297}
298
299/// Trait defining the component types used by an interpreter implementation.
300pub trait InterpreterTypes {
301    /// Stack implementation type.
302    type Stack: StackTr;
303    /// Memory implementation type.
304    type Memory: MemoryTr;
305    /// Bytecode implementation type.
306    type Bytecode: Jumps + Immediates + LoopControl + LegacyBytecode;
307    /// Return data implementation type.
308    type ReturnData: ReturnData;
309    /// Input data implementation type.
310    type Input: InputsTr;
311    /// Runtime flags implementation type.
312    type RuntimeFlag: RuntimeFlag;
313    /// Extended functionality type.
314    type Extend;
315    /// Output type for execution results.
316    type Output;
317}