Skip to content
Closed
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
6 changes: 6 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,11 @@ jobs:
esac
fi

act_checkout=()
if [ "<< parameters.wf >>" = "compact.yml" ]; then
act_checkout=(--no-skip-checkout)
fi

act_env=(--env "RUSTC_WRAPPER=" --env "GITHUB_BASE_REF=${base_ref}")
if [ "<< parameters.wf >>" = "unit.yml" ] && [ "$target_job" = "state" ]; then
# EF tests use Rayon internally, so unrestricted nextest processes multiply
Expand All @@ -165,6 +170,7 @@ jobs:

act "$event_name" -W ".github/workflows/<< parameters.wf >>" \
"${act_job[@]}" \
"${act_checkout[@]}" \
--eventpath "$event_path" \
-P "ubuntu-latest=catthehacker/ubuntu@sha256:b839c14c4410998529ec18f951262bdf87a2b23bc1467304d07b491b9455e074" \
--concurrent-jobs << parameters.concurrent_jobs >> \
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/rpc/rpc-eth-api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ alloy-network.workspace = true
alloy-primitives.workspace = true
alloy-rpc-types-eth.workspace = true
alloy-rpc-types-mev.workspace = true
alloy-rpc-types-trace.workspace = true
alloy-consensus.workspace = true

# rpc
Expand Down

Large diffs are not rendered by default.

42 changes: 42 additions & 0 deletions crates/rpc/rpc-eth-api/src/helpers/trace/replay.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use super::TracingCtx;
use alloy_evm::{Evm, IntoTxEnv};
use revm::DatabaseCommit;

/// Executes `transactions` on `evm` in order and invokes `callback` with each one's index, the
/// transaction and its [`TracingCtx`].
///
/// `inspector_setup` provides the inspector for the next transaction once the previous one is
/// handed to the callback. Iteration stops at the first transaction that fails to execute, and
/// the state of the last executed transaction is not committed.
pub(super) fn trace_transactions<E, Setup, Transactions, F, R, Error>(
mut evm: E,
transactions: Transactions,
mut inspector_setup: Setup,
mut callback: F,
) -> Result<Vec<R>, Error>
where
E: Evm<DB: DatabaseCommit>,
Setup: FnMut() -> E::Inspector,
Transactions: IntoIterator<Item: Clone + IntoTxEnv<E::Tx>>,
F: FnMut(usize, Transactions::Item, TracingCtx<'_, E::Inspector, E>) -> Result<R, Error>,
{
let mut results = Vec::new();
let mut transactions = transactions.into_iter().enumerate().peekable();
while let Some((index, transaction)) = transactions.next() {
let Ok(result) = evm.transact(transaction.clone()) else {
break;
};
let (database, inspector, _) = evm.components_mut();
let inspector = core::mem::replace(inspector, inspector_setup());
let output = callback(
index,
transaction,
TracingCtx { result: &result, db: &mut *database, inspector },
);
if transactions.peek().is_some() {
database.commit(result.state);
}
results.push(output?);
}
Ok(results)
}
169 changes: 169 additions & 0 deletions crates/rpc/rpc-eth-api/src/helpers/trace/replay_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
use super::replay::trace_transactions;
use alloy_evm::{
eth::{EthEvm, EthEvmFactory},
tracing::TxTracer,
EvmEnv, EvmFactory,
};
use alloy_primitives::{Address, Bytes, TxKind};
use revm::{
bytecode::Bytecode,
context::TxEnv,
context_interface::result::{ExecutionResult, HaltReason},
database::{CacheDB, EmptyDB},
interpreter::Interpreter,
state::{AccountInfo, EvmState},
Database, Inspector,
};

const CALLER: Address = Address::repeat_byte(0x11);
const CONTRACT: Address = Address::repeat_byte(0x22);

type TestDatabase = CacheDB<EmptyDB>;
type Snapshot = (ExecutionResult<HaltReason>, EvmState, usize);

#[derive(Clone, Debug, Default)]
struct CountingInspector {
calls: usize,
id: usize,
}

impl<Context> Inspector<Context> for CountingInspector {
fn initialize_interp(&mut self, _interpreter: &mut Interpreter, _context: &mut Context) {
self.calls += 1;
}
}

fn database() -> TestDatabase {
let mut database = CacheDB::new(EmptyDB::default());
database.insert_account_info(
CONTRACT,
AccountInfo::default().with_code(Bytecode::new_legacy(Bytes::from_static(&[0x00]))),
);
database
}

fn evm(
database: &mut TestDatabase,
inspector: CountingInspector,
) -> EthEvm<&mut TestDatabase, CountingInspector, alloy_evm::precompiles::PrecompilesMap> {
EthEvmFactory::default().create_evm_with_inspector(database, EvmEnv::default(), inspector)
}

fn transaction(nonce: u64) -> TxEnv {
TxEnv {
caller: CALLER,
gas_limit: 100_000,
kind: TxKind::Call(CONTRACT),
nonce,
..Default::default()
}
}

fn assert_replay_matches_tx_tracer(transaction_count: u64, take_inspector: bool) {
let transactions = (0..transaction_count).map(transaction).collect::<Vec<_>>();
let mut expected_database = database();
let mut tracer = TxTracer::new(evm(&mut expected_database, CountingInspector::default()));
let expected = tracer
.trace_many(transactions.clone(), |mut context| {
let calls = if take_inspector {
context.take_inspector().calls
} else {
context.inspector.calls
};
(context.result, context.state.clone(), calls)
})
.collect::<Result<Vec<Snapshot>, _>>()
.unwrap();

let mut actual_database = database();
let actual: Result<Vec<Snapshot>, ()> = trace_transactions(
evm(&mut actual_database, CountingInspector::default()),
transactions,
CountingInspector::default,
|_, _, context| {
let result = context.result.result.clone();
let state = context.result.state.clone();
let calls = if take_inspector {
context.take_inspector().calls
} else {
context.inspector.calls
};
Ok((result, state, calls))
},
);
assert_eq!(actual.unwrap(), expected);
assert_eq!(actual_database.basic(CALLER).unwrap(), expected_database.basic(CALLER).unwrap());
assert_eq!(
actual_database.basic(CALLER).unwrap().unwrap_or_default().nonce,
transaction_count.saturating_sub(1),
);
assert!(expected.iter().all(|snapshot| snapshot.2 == 1));
}

#[test]
fn replay_matches_tx_tracer_for_empty_input() {
assert_replay_matches_tx_tracer(0, false);
}

#[test]
fn replay_matches_tx_tracer_for_multiple_transactions() {
assert_replay_matches_tx_tracer(3, false);
}

#[test]
fn replay_matches_tx_tracer_for_single_transaction() {
assert_replay_matches_tx_tracer(1, false);
}

#[test]
fn replay_matches_tx_tracer_with_taken_inspector() {
assert_replay_matches_tx_tracer(3, true);
}

#[test]
fn each_transaction_receives_the_inspector_set_up_for_it() {
let mut database = database();
let mut created = 0;
let ids: Result<Vec<usize>, ()> = trace_transactions(
evm(&mut database, CountingInspector { calls: 0, id: 1 }),
(0..3).map(transaction),
move || {
created += 1;
CountingInspector { calls: 0, id: created + 1 }
},
|_, _, context| Ok(context.take_inspector().id),
);
assert_eq!(ids, Ok(vec![1, 2, 3]));
}

#[test]
fn callback_failure_preserves_legacy_commit_order() {
let mut database = database();
let result: Result<Vec<()>, usize> = trace_transactions(
evm(&mut database, CountingInspector::default()),
(0..3).map(transaction),
CountingInspector::default,
|index, _, _| {
if index == 1 {
Err(index)
} else {
Ok(())
}
},
);
assert_eq!(result, Err(1));
assert_eq!(database.basic(CALLER).unwrap().unwrap().nonce, 2);
}

#[test]
fn transaction_failure_preserves_legacy_truncation() {
let mut database = database();
let result: Result<Vec<usize>, ()> = trace_transactions(
evm(&mut database, CountingInspector::default()),
[transaction(0), transaction(7), transaction(2)],
CountingInspector::default,
|index, _, _| Ok(index),
);
assert_eq!(result, Ok(vec![0]));
assert_eq!(database.basic(CALLER).unwrap().unwrap().nonce, 1);
}
Loading