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 Internal(#[from] InternalError),
14 TxValidation(#[from] TxValidationError),
16 ExceptionalHalt(#[from] ExceptionalHalt),
18 RevertOpcode,
20}
21
22impl VMError {
23 pub fn should_propagate(&self) -> bool {
26 matches!(self, VMError::Internal(_))
27 }
28
29 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
47impl 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#[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 #[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 #[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 #[error("EXECUTE: stateless validation failed")]
235 ExecuteValidationFailed,
236 #[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 pub gas_used: u64,
267 pub gas_spent: u64,
272 pub gas_refunded: u64,
273 pub state_gas_used: u64,
276 pub output: Bytes,
277 pub logs: Vec<Log>,
278 pub payer_address: Option<Address>,
280 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 pub gas_used: u64,
297 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 pub fn is_collision(&self) -> bool {
309 matches!(
310 self.result,
311 TxResult::Revert(VMError::ExceptionalHalt(
312 ExceptionalHalt::AddressAlreadyOccupied
313 ))
314 )
315 }
316
317 pub fn is_revert_opcode(&self) -> bool {
321 matches!(self.result, TxResult::Revert(VMError::RevertOpcode))
322 }
323}