Skip to content

chore: introduce GrevmError to record the transaction id that caused the error #57

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 17 additions & 14 deletions src/async_commit.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use crate::{storage::ParallelBundleState, ParallelState};
use crate::{storage::ParallelBundleState, GrevmError, ParallelState, TxId};
use revm::{
db::{states::bundle_state::BundleRetention, BundleState},
TransitionState,
};
use revm_primitives::{
db::{Database, DatabaseCommit, DatabaseRef},
AccountInfo, Address, EVMError, ExecutionResult, InvalidTransaction, ResultAndState, TxEnv,
Address, EVMError, ExecutionResult, InvalidTransaction, ResultAndState, TxEnv,
};
use std::cmp::Ordering;

Expand All @@ -16,7 +16,7 @@ where
coinbase: Address,
results: Vec<ExecutionResult>,
state: &'a ParallelState<DB>,
commit_result: Result<(), EVMError<DB::Error>>,
commit_result: Result<(), GrevmError<DB::Error>>,
}

impl<'a, DB> StateAsyncCommit<'a, DB>
Expand Down Expand Up @@ -58,11 +58,11 @@ where
self.state_mut().take_bundle()
}

pub fn commit_result(&self) -> &Result<(), EVMError<DB::Error>> {
pub fn commit_result(&self) -> &Result<(), GrevmError<DB::Error>> {
&self.commit_result
}

pub fn commit(&mut self, tx_env: TxEnv, result_and_state: ResultAndState) {
pub fn commit(&mut self, txid: TxId, tx_env: &TxEnv, result_and_state: ResultAndState) {
// check nonce
if let Some(tx) = tx_env.nonce {
match self.state.basic_ref(tx_env.caller) {
Expand All @@ -71,25 +71,28 @@ where
let state = info.nonce;
match tx.cmp(&state) {
Ordering::Greater => {
self.commit_result =
Err(EVMError::Transaction(InvalidTransaction::NonceTooHigh {
tx,
state,
}));
self.commit_result = Err(GrevmError {
txid,
error: EVMError::Transaction(
InvalidTransaction::NonceTooHigh { tx, state },
),
});
}
Ordering::Less => {
self.commit_result =
Err(EVMError::Transaction(InvalidTransaction::NonceTooLow {
self.commit_result = Err(GrevmError {
txid,
error: EVMError::Transaction(InvalidTransaction::NonceTooLow {
tx,
state,
}));
}),
});
}
_ => {}
}
}
}
Err(e) => {
self.commit_result = Err(EVMError::Database(e));
self.commit_result = Err(GrevmError { txid, error: EVMError::Database(e) })
}
}
}
Expand Down
13 changes: 11 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ mod utils;
use ahash::{AHashMap as HashMap, AHashSet as HashSet};
use lazy_static::lazy_static;
use rayon::prelude::{IntoParallelIterator, ParallelIterator};
use revm_primitives::{AccountInfo, Address, Bytecode, EVMResult, B256, U256};
use revm_primitives::{AccountInfo, Address, Bytecode, EVMError, EVMResult, B256, U256};
use std::{cmp::min, thread};

lazy_static! {
Expand Down Expand Up @@ -45,7 +45,7 @@ struct TxVersion {
}

impl TxVersion {
pub fn new(txid: TxId, incarnation: usize) -> Self {
pub(crate) fn new(txid: TxId, incarnation: usize) -> Self {
Self { txid, incarnation }
}
}
Expand Down Expand Up @@ -123,6 +123,15 @@ enum AbortReason {
FallbackSequential,
}

/// Grevm error type.
#[derive(Debug, Clone)]
pub struct GrevmError<DBError> {
/// The transaction id that caused the error.
pub txid: TxId,
/// The error that occurred.
pub error: EVMError<DBError>,
}

/// Utility function for parallel execution using fork-join pattern.
///
/// This function divides the work into partitions and executes the provided closure `f`
Expand Down
34 changes: 18 additions & 16 deletions src/scheduler.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,30 @@
use crate::{
async_commit::StateAsyncCommit, hint::ParallelExecutionHints, storage::CacheDB,
tx_dependency::TxDependency, utils::LockFreeQueue, AbortReason, LocationAndType, MemoryEntry,
ParallelState, ReadVersion, Task, TransactionResult, TransactionStatus, TxId, TxState,
TxVersion, CONCURRENT_LEVEL,
tx_dependency::TxDependency, utils::LockFreeQueue, AbortReason, GrevmError, LocationAndType,
MemoryEntry, ParallelState, ReadVersion, Task, TransactionResult, TransactionStatus, TxId,
TxState, TxVersion, CONCURRENT_LEVEL,
};
use ahash::{AHashMap as HashMap, AHashSet as HashSet};
use auto_impl::auto_impl;
use dashmap::DashMap;
use metrics::histogram;
use parking_lot::{Mutex, RwLock};
use revm::{Evm, EvmBuilder, StateBuilder};
use parking_lot::Mutex;
use revm::{Evm, EvmBuilder};
use revm_primitives::{
db::{DatabaseCommit, DatabaseRef},
EVMError, Env, ExecutionResult, SpecId, TxEnv, TxKind,
EVMError, Env, ExecutionResult, SpecId, TxEnv,
};
use std::{
cmp::max,
collections::BTreeMap,
fmt::Display,
sync::{
atomic::{AtomicBool, AtomicUsize, Ordering},
Arc, OnceLock,
},
thread,
time::Instant,
};
use tracing::*;

pub type MVMemory = DashMap<LocationAndType, BTreeMap<TxId, MemoryEntry>>;

Expand Down Expand Up @@ -210,7 +211,7 @@ where
let tx = self.tx_results[num_commit].lock();
let result = tx.as_ref().unwrap().execute_result.clone();
let Ok(result) = result else { panic!("Commit error tx: {}", num_commit) };
commiter.commit(self.txs[num_commit].clone(), result);
commiter.commit(num_commit, &self.txs[num_commit], result);
if commiter.commit_result().is_err() {
self.abort(AbortReason::EvmError);
return;
Expand Down Expand Up @@ -269,12 +270,12 @@ where
pub fn parallel_execute(
&self,
concurrency_level: Option<usize>,
) -> Result<(), EVMError<DB::Error>> {
) -> Result<(), GrevmError<DB::Error>> {
self.metrics.total_tx_cnt.store(self.block_size, Ordering::Relaxed);
let concurrency_level = concurrency_level.unwrap_or(*CONCURRENT_LEVEL);
let task_queue = LockFreeQueue::new(concurrency_level * 4);
let commiter = Mutex::new(StateAsyncCommit::new(self.env.block.coinbase, &self.state));
commiter.lock().init().map_err(|e| EVMError::Database(e))?;
commiter.lock().init().map_err(|e| GrevmError { txid: 0, error: EVMError::Database(e) })?;
let dependency_distance = histogram!("grevm.dependency_distance");
thread::scope(|scope| {
scope.spawn(|| {
Expand Down Expand Up @@ -324,16 +325,16 @@ where
Ok(())
}

fn post_execute(&self) -> Result<(), EVMError<DB::Error>> {
fn post_execute(&self) -> Result<(), GrevmError<DB::Error>> {
if self.abort.load(Ordering::Relaxed) {
if let Some(abort_reason) = self.abort_reason.get() {
match abort_reason {
AbortReason::EvmError => {
let result =
self.tx_results[self.finality_idx.load(Ordering::Relaxed)].lock();
let txid = self.finality_idx.load(Ordering::Relaxed);
let result = self.tx_results[txid].lock();
if let Some(result) = result.as_ref() {
if let Err(e) = &result.execute_result {
return Err(e.clone());
return Err(GrevmError { txid, error: e.clone() });
}
}
panic!("Wrong abort transaction")
Expand All @@ -347,7 +348,7 @@ where
Ok(())
}

pub fn fallback_sequential(&self) -> Result<(), EVMError<DB::Error>> {
pub fn fallback_sequential(&self) -> Result<(), GrevmError<DB::Error>> {
let mut results = self.results.lock();
let num_commit = results.len();
if num_commit == self.block_size {
Expand All @@ -364,7 +365,8 @@ where
.build();
for txid in num_commit..self.block_size {
*evm.tx_mut() = self.txs[txid].clone();
let result_and_state = evm.transact()?;
let result_and_state =
evm.transact().map_err(|e| GrevmError { txid, error: e.clone() })?;
evm.db_mut().commit(result_and_state.state);
sequential_results.push(result_and_state.result);
self.metrics.execution_cnt.fetch_add(1, Ordering::Relaxed);
Expand Down
2 changes: 1 addition & 1 deletion tests/common/execute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use revm_primitives::{EnvWithHandlerCfg, ResultAndState};
use std::{
cmp::min,
collections::{BTreeMap, HashMap},
fmt::Debug,
fmt::{Debug, Display},
fs::{self, File},
io::{BufReader, BufWriter},
sync::Arc,
Expand Down
4 changes: 2 additions & 2 deletions tests/ethereum/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,8 +168,8 @@ fn run_test_unit(path: &Path, unit: TestUnit) {
}
// Remaining tests that expect execution to fail -> match error
(Some(exception), Err(error)) => {
println!("Error-Error: {}: {:?}", exception, error.to_string());
let error = error.to_string();
println!("Error-Error: {}: {:?}", exception, error);
let error = error.error.to_string();
assert!(match exception {
"TransactionException.INSUFFICIENT_ACCOUNT_FUNDS|TransactionException.INTRINSIC_GAS_TOO_LOW" => error == "transaction validation error: call gas cost exceeds the gas limit",
"TransactionException.INSUFFICIENT_ACCOUNT_FUNDS" => error.contains("lack of funds"),
Expand Down
Loading