Skip to main content

ethrex_levm/
errors.rs

1use bytes::Bytes;
2use derive_more::derive::Display;
3use ethrex_common::{
4    Address, H256, U256,
5    types::{FakeExponentialError, Log},
6};
7use serde::{Deserialize, Serialize};
8use thiserror;
9
10#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, Serialize, Deserialize, Display)]
11pub enum VMError {
12    /// Errors that break execution, they shouldn't ever happen. Contains subcategory `DatabaseError`.
13    Internal(#[from] InternalError),
14    /// Returned when a transaction doesn't pass all validations before executing.
15    TxValidation(#[from] TxValidationError),
16    /// Errors contemplated by the EVM, they revert and consume all gas of the current context.
17    ExceptionalHalt(#[from] ExceptionalHalt),
18    /// Revert Opcode called. It behaves like ExceptionalHalt, except it doesn't consume all gas left.
19    RevertOpcode,
20}
21
22impl VMError {
23    /// These errors are unexpected and indicate critical issues.
24    /// They should not cause a transaction to revert silently but instead fail loudly, propagating the error.
25    pub fn should_propagate(&self) -> bool {
26        matches!(self, VMError::Internal(_))
27    }
28
29    /// Error triggered by revert opcode. This error doesn't consume all gas left in context.
30    pub fn is_revert_opcode(&self) -> bool {
31        matches!(self, VMError::RevertOpcode)
32    }
33}
34
35impl From<DatabaseError> for VMError {
36    fn from(err: DatabaseError) -> Self {
37        VMError::Internal(InternalError::Database(err))
38    }
39}
40
41impl From<PrecompileError> for VMError {
42    fn from(err: PrecompileError) -> Self {
43        VMError::ExceptionalHalt(ExceptionalHalt::Precompile(err))
44    }
45}
46
47/// Useful to use ? in try_into, specially when slicing with known bounds to fixed size arrays,
48/// which is a error that never really happens.
49impl From<std::array::TryFromSliceError> for VMError {
50    fn from(_: std::array::TryFromSliceError) -> Self {
51        VMError::Internal(InternalError::TypeConversion)
52    }
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, Serialize, Deserialize)]
56pub enum ExceptionalHalt {
57    #[error("Stack Underflow")]
58    StackUnderflow,
59    #[error("Stack Overflow")]
60    StackOverflow,
61    #[error("Invalid Jump")]
62    InvalidJump,
63    #[error("Opcode Not Allowed In Static Context")]
64    OpcodeNotAllowedInStaticContext,
65    #[error("Invalid Contract Prefix")]
66    InvalidContractPrefix,
67    #[error("Very Large Number")]
68    VeryLargeNumber,
69    #[error("Invalid Opcode")]
70    InvalidOpcode,
71    #[error("Address Already Occupied")]
72    AddressAlreadyOccupied,
73    #[error("Contract Output Too Big")]
74    ContractOutputTooBig,
75    #[error("Offset out of bounds")]
76    OutOfBounds,
77    #[error("Out Of Gas")]
78    OutOfGas,
79    #[error("Precompile execution error: {0}")]
80    Precompile(#[from] PrecompileError),
81}
82
83// Error strings are attached to execution-spec-tests mapping https://github.com/ethereum/execution-spec-tests
84// If any change is made here without changing the mapper it will break some hive tests.
85#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, Serialize, Deserialize)]
86pub enum TxValidationError {
87    #[error("Sender account {0} shouldn't be a contract")]
88    SenderNotEOA(Address),
89    #[error("Insufficient account funds")]
90    InsufficientAccountFunds,
91    #[error("Nonce is max")]
92    NonceIsMax,
93    #[error("Nonce mismatch: expected {expected}, got {actual}")]
94    NonceMismatch { expected: u64, actual: u64 },
95    #[error("Initcode size exceeded, max size: {max_size}, actual size: {actual_size}")]
96    InitcodeSizeExceeded { max_size: usize, actual_size: usize },
97    #[error("Priority fee {priority_fee} is greater than max fee per gas {max_fee_per_gas}")]
98    PriorityGreaterThanMaxFeePerGas {
99        priority_fee: U256,
100        max_fee_per_gas: U256,
101    },
102    #[error("Transaction gas limit lower than the minimum gas cost to execute the transaction")]
103    IntrinsicGasTooLow,
104    #[error("Transaction gas limit lower than the gas cost floor for calldata tokens")]
105    IntrinsicGasBelowFloorGasCost,
106    /// L2-only. Raised by the L2 hook's `reserve_l1_gas` when the gas limit cannot
107    /// cover the L1 data-availability gas reserved on top of the intrinsic cost or
108    /// the calldata floor. Distinct from [`TxValidationError::IntrinsicGasTooLow`]
109    /// on purpose: the reserved amount is derived from the L1 fee config and the
110    /// block's gas price, so this failure is TRANSIENT — the same transaction can
111    /// succeed in a later block once L1 fees drop. Consumers that classify errors
112    /// as permanent-vs-transient (the payload builders' `is_deterministic_invalid`)
113    /// rely on the two not being conflated.
114    #[error("Transaction gas limit cannot cover the reserved L1 data availability gas")]
115    L1GasReservationTooLow,
116    #[error(
117        "Gas allowance exceeded. Block gas limit: {block_gas_limit}, transaction gas limit: {tx_gas_limit}"
118    )]
119    GasAllowanceExceeded {
120        block_gas_limit: u64,
121        tx_gas_limit: u64,
122    },
123    #[error("Insufficient max fee per gas")]
124    InsufficientMaxFeePerGas,
125    #[error(
126        "Insufficient max fee per blob gas. Expected at least {base_fee_per_blob_gas}, got: {tx_max_fee_per_blob_gas}"
127    )]
128    InsufficientMaxFeePerBlobGas {
129        base_fee_per_blob_gas: U256,
130        tx_max_fee_per_blob_gas: U256,
131    },
132    #[error("Type 1 transactions are not supported before the Berlin fork")]
133    Type1TxPreFork,
134    #[error("Type 2 transactions are not supported before the London fork")]
135    Type2TxPreFork,
136    #[error("Type 3 transactions are not supported before the Cancun fork")]
137    Type3TxPreFork,
138    #[error("Type 3 transaction without blobs")]
139    Type3TxZeroBlobs,
140    #[error("Invalid blob versioned hash")]
141    Type3TxInvalidBlobVersionedHash,
142    #[error(
143        "Blob count exceeded. Max blob count: {max_blob_count}, actual blob count: {actual_blob_count}"
144    )]
145    Type3TxBlobCountExceeded {
146        max_blob_count: usize,
147        actual_blob_count: usize,
148    },
149    #[error("Contract creation in blob transaction")]
150    Type3TxContractCreation,
151    #[error("Type 4 transactions are not supported before the Prague fork")]
152    Type4TxPreFork,
153    #[error("Empty authorization list in type 4 transaction")]
154    Type4TxAuthorizationListIsEmpty,
155    #[error("Contract creation in type 4 transaction")]
156    Type4TxContractCreation,
157    #[error("Frame transactions (EIP-8141) are not supported before the Hegota fork")]
158    FrameTxPreFork,
159    #[error("Gas limit price product overflow")]
160    GasLimitPriceProductOverflow,
161    #[error(
162        "Transaction gas limit exceeds maximum. Transaction hash: {tx_hash}, transaction gas limit: {tx_gas_limit}"
163    )]
164    TxMaxGasLimitExceeded { tx_hash: H256, tx_gas_limit: u64 },
165    #[error("Invalid frame transaction: VERIFY frame did not call APPROVE or payer not approved")]
166    InvalidFrameTransaction,
167}
168
169#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, Serialize, Deserialize)]
170pub enum InternalError {
171    #[error("Arithmetic operation overflowed")]
172    Overflow,
173    #[error("Arithmetic operation underflowed")]
174    Underflow,
175    #[error("Cannot divide by zero")]
176    DivisionByZero,
177    #[error("Tried to convert one type to another")]
178    TypeConversion,
179    #[error("CallFrame not found")]
180    CallFrame,
181    #[error("Tried to slice non-existing data")]
182    Slicing,
183    #[error("Account not found when it should've been in the cache.")]
184    AccountNotFound,
185    #[error("Invalid precompile address. Tried to execute a precompile that does not exist.")]
186    InvalidPrecompileAddress,
187    #[error("Invalid Fork")]
188    InvalidFork,
189    #[error("Account should had been delegated")]
190    AccountNotDelegated,
191    #[error("No recipient found for privileged transaction")]
192    RecipientNotFoundForPrivilegedTransaction,
193    #[error("Memory Size Sverflow")]
194    MemorySizeOverflow,
195    #[error("Custom error: {0}")]
196    Custom(String),
197    /// Unexpected error when accessing the database, used in trait `Database`.
198    #[error("Database access error: {0}")]
199    Database(#[from] DatabaseError),
200    #[error("{0}")]
201    FakeExponentialError(#[from] FakeExponentialError),
202}
203
204impl InternalError {
205    pub fn msg(msg: &'static str) -> Self {
206        Self::Custom(msg.to_owned())
207    }
208}
209
210#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, Serialize, Deserialize)]
211pub enum PrecompileError {
212    #[error("Error while parsing the calldata")]
213    ParsingInputError,
214    #[error("There is not enough gas to execute precompiled contract")]
215    NotEnoughGas,
216    #[error("Invalid point")]
217    InvalidPoint,
218    #[error("The point is not in the subgroup")]
219    PointNotInSubgroup,
220    #[error("The G1 point is not in the curve")]
221    BLS12381G1PointNotInCurve,
222    #[error("The G2 point is not in the curve")]
223    BLS12381G2PointNotInCurve,
224    #[error("Mod-exp base length is too large")]
225    ModExpBaseTooLarge,
226    #[error("Mod-exp exponent length is too large")]
227    ModExpExpTooLarge,
228    #[error("Mod-exp modulus length is too large")]
229    ModExpModulusTooLarge,
230    #[error("Coordinate Exceeds Field Modulus")]
231    CoordinateExceedsFieldModulus,
232    /// EXECUTE precompile: the L1-submitted block failed stateless validation.
233    /// Attacker-controllable: tx continues, forwarded gas is consumed, tx is includable.
234    #[error("EXECUTE: stateless validation failed")]
235    ExecuteValidationFailed,
236    /// EXECUTE precompile: the calldata is malformed or violates L2 constraints.
237    /// Attacker-controllable input: treat as CALL-level failure, not an internal invariant.
238    #[error("EXECUTE: invalid input for native-rollup execution")]
239    ExecuteInvalidInput,
240}
241
242#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, Serialize, Deserialize)]
243pub enum DatabaseError {
244    #[error("{0}")]
245    Custom(String),
246}
247
248#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
249pub enum OpcodeResult {
250    Continue,
251    Halt,
252}
253
254#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
255pub enum TxResult {
256    Success,
257    Revert(VMError),
258}
259
260#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
261pub struct ExecutionReport {
262    pub result: TxResult,
263    /// Gas used before refunds (for block-level accounting).
264    /// Pre-EIP-7778: This is the post-refund gas.
265    /// Post-EIP-7778: This is the pre-refund gas.
266    pub gas_used: u64,
267    /// Gas spent after refunds (what the user actually pays).
268    /// This is always the post-refund gas value.
269    /// Pre-EIP-7778: Same as gas_used.
270    /// Post-EIP-7778: gas_used - refunds (capped).
271    pub gas_spent: u64,
272    pub gas_refunded: u64,
273    /// EIP-8037: State gas portion of gas_used (Amsterdam+).
274    /// Block gas_used = max(sum(regular_gas), sum(state_gas)).
275    pub state_gas_used: u64,
276    pub output: Bytes,
277    pub logs: Vec<Log>,
278    /// For frame transactions: the address that paid for gas
279    pub payer_address: Option<Address>,
280    /// For frame transactions: per-frame results (status, gas_used, logs).
281    /// `status` is a `FRAME_RECEIPT_STATUS_*` code (0 = failure, 1 = success,
282    /// 3 = skipped due to failed atomic batch, per EIP-8141 receipt encoding).
283    pub frame_results: Option<Vec<(u8, u64, Vec<Log>)>>,
284}
285
286impl ExecutionReport {
287    pub fn is_success(&self) -> bool {
288        matches!(self.result, TxResult::Success)
289    }
290}
291
292#[derive(Debug, Clone, PartialEq, Eq)]
293pub struct ContextResult {
294    pub result: TxResult,
295    /// Gas used before refunds (for block-level accounting).
296    pub gas_used: u64,
297    /// Gas spent after refunds (what the user actually pays).
298    pub gas_spent: u64,
299    pub output: Bytes,
300}
301
302impl ContextResult {
303    pub fn is_success(&self) -> bool {
304        matches!(self.result, TxResult::Success)
305    }
306
307    /// Returns true if this result is an address collision error.
308    pub fn is_collision(&self) -> bool {
309        matches!(
310            self.result,
311            TxResult::Revert(VMError::ExceptionalHalt(
312                ExceptionalHalt::AddressAlreadyOccupied
313            ))
314        )
315    }
316
317    /// True if the failure was caused by the REVERT opcode (intentional revert).
318    /// Used to gate behaviour that differs between REVERT and ExceptionalHalt —
319    /// e.g. return data is propagated to the parent on REVERT only.
320    pub fn is_revert_opcode(&self) -> bool {
321        matches!(self.result, TxResult::Revert(VMError::RevertOpcode))
322    }
323}