revm_primitives/
bytecode.rs

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
pub mod eof;
pub mod legacy;

pub use eof::{Eof, EOF_MAGIC, EOF_MAGIC_BYTES, EOF_MAGIC_HASH};
pub use legacy::{JumpTable, LegacyAnalyzedBytecode};

use crate::{
    eip7702::bytecode::Eip7702DecodeError, keccak256, Bytes, Eip7702Bytecode, B256,
    EIP7702_MAGIC_BYTES, KECCAK_EMPTY,
};
use alloy_primitives::Address;
use core::fmt::Debug;
use eof::EofDecodeError;
use std::{fmt, sync::Arc};

/// State of the [`Bytecode`] analysis.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Bytecode {
    /// No analysis has been performed.
    LegacyRaw(Bytes),
    /// The bytecode has been analyzed for valid jump destinations.
    LegacyAnalyzed(LegacyAnalyzedBytecode),
    /// Ethereum Object Format
    Eof(Arc<Eof>),
    /// EIP-7702 delegated bytecode
    Eip7702(Eip7702Bytecode),
}

impl Default for Bytecode {
    #[inline]
    fn default() -> Self {
        // Creates a new legacy analyzed [`Bytecode`] with exactly one STOP opcode.
        Self::new()
    }
}

impl Bytecode {
    // Creates a new legacy analyzed [`Bytecode`] with exactly one STOP opcode.
    #[inline]
    pub fn new() -> Self {
        Self::LegacyAnalyzed(LegacyAnalyzedBytecode::default())
    }

    /// Return jump table if bytecode is analyzed
    #[inline]
    pub fn legacy_jump_table(&self) -> Option<&JumpTable> {
        match &self {
            Self::LegacyAnalyzed(analyzed) => Some(analyzed.jump_table()),
            _ => None,
        }
    }

    /// Calculate hash of the bytecode.
    pub fn hash_slow(&self) -> B256 {
        if self.is_empty() {
            KECCAK_EMPTY
        } else {
            keccak256(self.original_byte_slice())
        }
    }

    /// Return reference to the EOF if bytecode is EOF.
    #[inline]
    pub const fn eof(&self) -> Option<&Arc<Eof>> {
        match self {
            Self::Eof(eof) => Some(eof),
            _ => None,
        }
    }

    /// Returns true if bytecode is EOF.
    #[inline]
    pub const fn is_eof(&self) -> bool {
        matches!(self, Self::Eof(_))
    }

    /// Returns true if bytecode is EIP-7702.
    pub const fn is_eip7702(&self) -> bool {
        matches!(self, Self::Eip7702(_))
    }

    /// Creates a new legacy [`Bytecode`].
    #[inline]
    pub fn new_legacy(raw: Bytes) -> Self {
        Self::LegacyRaw(raw)
    }

    /// Creates a new raw [`Bytecode`].
    ///
    /// # Panics
    ///
    /// Panics if bytecode is in incorrect format.
    #[inline]
    pub fn new_raw(bytecode: Bytes) -> Self {
        Self::new_raw_checked(bytecode).expect("Expect correct EOF bytecode")
    }

    /// Creates a new EIP-7702 [`Bytecode`] from [`Address`].
    #[inline]
    pub fn new_eip7702(address: Address) -> Self {
        Self::Eip7702(Eip7702Bytecode::new(address))
    }

    /// Creates a new raw [`Bytecode`].
    ///
    /// Returns an error on incorrect Bytecode format.
    #[inline]
    pub fn new_raw_checked(bytecode: Bytes) -> Result<Self, BytecodeDecodeError> {
        let prefix = bytecode.get(..2);
        match prefix {
            Some(prefix) if prefix == &EOF_MAGIC_BYTES => {
                let eof = Eof::decode(bytecode)?;
                Ok(Self::Eof(Arc::new(eof)))
            }
            Some(prefix) if prefix == &EIP7702_MAGIC_BYTES => {
                let eip7702 = Eip7702Bytecode::new_raw(bytecode)?;
                Ok(Self::Eip7702(eip7702))
            }
            _ => Ok(Self::LegacyRaw(bytecode)),
        }
    }

    /// Create new checked bytecode.
    ///
    /// # Safety
    ///
    /// Bytecode needs to end with STOP (0x00) opcode as checked bytecode assumes
    /// that it is safe to iterate over bytecode without checking lengths.
    pub unsafe fn new_analyzed(
        bytecode: Bytes,
        original_len: usize,
        jump_table: JumpTable,
    ) -> Self {
        Self::LegacyAnalyzed(LegacyAnalyzedBytecode::new(
            bytecode,
            original_len,
            jump_table,
        ))
    }

    /// Returns a reference to the bytecode.
    ///
    /// In case of EOF this will be the first code section.
    #[inline]
    pub fn bytecode(&self) -> &Bytes {
        match self {
            Self::LegacyRaw(bytes) => bytes,
            Self::LegacyAnalyzed(analyzed) => analyzed.bytecode(),
            Self::Eof(eof) => eof
                .body
                .code(0)
                .expect("Valid EOF has at least one code section"),
            Self::Eip7702(code) => code.raw(),
        }
    }

    /// Returns false if bytecode can't be executed in Interpreter.
    pub fn is_execution_ready(&self) -> bool {
        !matches!(self, Self::LegacyRaw(_))
    }

    /// Returns bytes
    #[inline]
    pub fn bytes(&self) -> Bytes {
        match self {
            Self::LegacyAnalyzed(analyzed) => analyzed.bytecode().clone(),
            _ => self.original_bytes(),
        }
    }

    /// Returns bytes slice
    #[inline]
    pub fn bytes_slice(&self) -> &[u8] {
        match self {
            Self::LegacyAnalyzed(analyzed) => analyzed.bytecode(),
            _ => self.original_byte_slice(),
        }
    }

    /// Returns a reference to the original bytecode.
    #[inline]
    pub fn original_bytes(&self) -> Bytes {
        match self {
            Self::LegacyRaw(bytes) => bytes.clone(),
            Self::LegacyAnalyzed(analyzed) => analyzed.original_bytes(),
            Self::Eof(eof) => eof.raw().clone(),
            Self::Eip7702(eip7702) => eip7702.raw().clone(),
        }
    }

    /// Returns the original bytecode as a byte slice.
    #[inline]
    pub fn original_byte_slice(&self) -> &[u8] {
        match self {
            Self::LegacyRaw(bytes) => bytes,
            Self::LegacyAnalyzed(analyzed) => analyzed.original_byte_slice(),
            Self::Eof(eof) => eof.raw(),
            Self::Eip7702(eip7702) => eip7702.raw(),
        }
    }

    /// Returns the length of the original bytes.
    #[inline]
    pub fn len(&self) -> usize {
        self.original_byte_slice().len()
    }

    /// Returns whether the bytecode is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// EOF decode errors.
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum BytecodeDecodeError {
    /// EOF decode error
    Eof(EofDecodeError),
    /// EIP-7702 decode error
    Eip7702(Eip7702DecodeError),
}

impl From<EofDecodeError> for BytecodeDecodeError {
    fn from(error: EofDecodeError) -> Self {
        Self::Eof(error)
    }
}

impl From<Eip7702DecodeError> for BytecodeDecodeError {
    fn from(error: Eip7702DecodeError) -> Self {
        Self::Eip7702(error)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for BytecodeDecodeError {}

impl fmt::Display for BytecodeDecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Eof(e) => fmt::Display::fmt(e, f),
            Self::Eip7702(e) => fmt::Display::fmt(e, f),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Bytecode, Eof};
    use std::sync::Arc;

    #[test]
    fn eof_arc_clone() {
        let eof = Arc::new(Eof::default());
        let bytecode = Bytecode::Eof(Arc::clone(&eof));

        // Cloning the Bytecode should not clone the underlying Eof
        let cloned_bytecode = bytecode.clone();
        if let Bytecode::Eof(original_arc) = bytecode {
            if let Bytecode::Eof(cloned_arc) = cloned_bytecode {
                assert!(Arc::ptr_eq(&original_arc, &cloned_arc));
            } else {
                panic!("Cloned bytecode is not Eof");
            }
        } else {
            panic!("Original bytecode is not Eof");
        }
    }
}