1use std::sync::Arc;
2
3use alloy_consensus::transaction::TransactionInfo;
4use alloy_rpc_types_trace::geth::CallFrame;
5use alloy_rpc_types_trace::geth::FourByteFrame;
6use alloy_rpc_types_trace::geth::GethDebugBuiltInTracerType;
7use alloy_rpc_types_trace::geth::GethDebugTracerType;
8use alloy_rpc_types_trace::geth::GethTrace;
9use alloy_rpc_types_trace::geth::NoopFrame;
10use alloy_rpc_types_trace::geth::call::FlatCallFrame;
11use alloy_rpc_types_trace::geth::mux::MuxFrame;
12use anyhow::anyhow;
13use itertools::Itertools;
14use log::log_enabled;
15use revm::Context;
16use revm::Database;
17use revm::DatabaseRef;
18use revm::ExecuteCommitEvm;
19use revm::ExecuteEvm;
20use revm::InspectEvm;
21use revm::Journal;
22use revm::context::BlockEnv;
23use revm::context::CfgEnv;
24use revm::context::Evm as RevmEvm;
25use revm::context::TransactTo;
26use revm::context::TxEnv;
27use revm::context::result::EVMError;
28use revm::context::result::ExecutionResult as RevmExecutionResult;
29use revm::context::result::InvalidTransaction;
30use revm::context::result::ResultAndState;
31use revm::database::CacheDB;
32use revm::handler::EthFrame;
33use revm::handler::EthPrecompiles;
34use revm::handler::instructions::EthInstructions;
35use revm::interpreter::interpreter::EthInterpreter;
36use revm::primitives::B256;
37use revm::primitives::U256;
38use revm::primitives::hardfork::SpecId;
39use revm::state::AccountInfo;
40use revm::state::EvmState;
41use revm_inspectors::tracing::FourByteInspector;
42use revm_inspectors::tracing::MuxInspector;
43use revm_inspectors::tracing::TracingInspector;
44use revm_inspectors::tracing::TracingInspectorConfig;
45use revm_inspectors::tracing::js::JsInspector;
46
47use super::evm_input::InspectorInput;
48use crate::alias::RevmAddress;
49use crate::alias::RevmBytecode;
50use crate::eth::codegen;
51use crate::eth::executor::EvmExecutionResult;
52use crate::eth::executor::EvmInput;
53use crate::eth::executor::ExecutorConfig;
54use crate::eth::primitives::Account;
55use crate::eth::primitives::Address;
56use crate::eth::primitives::BlockFilter;
57use crate::eth::primitives::Bytes;
58use crate::eth::primitives::EvmExecution;
59use crate::eth::primitives::EvmExecutionMetrics;
60use crate::eth::primitives::ExecutionAccountChanges;
61use crate::eth::primitives::ExecutionChanges;
62use crate::eth::primitives::ExecutionResult;
63use crate::eth::primitives::Gas;
64use crate::eth::primitives::Log;
65use crate::eth::primitives::MinedData;
66use crate::eth::primitives::PointInTime;
67use crate::eth::primitives::Slot;
68use crate::eth::primitives::SlotIndex;
69use crate::eth::primitives::StorageError;
70use crate::eth::primitives::StratusError;
71use crate::eth::primitives::TransactionError;
72use crate::eth::primitives::TransactionExecution;
73use crate::eth::storage::StratusStorage;
74use crate::ext::OptionExt;
75#[cfg(feature = "metrics")]
76use crate::infra::metrics;
77
78#[cfg(feature = "dev")]
80const GAS_MAX_LIMIT: u64 = 1_000_000_000;
81#[cfg(not(feature = "dev"))]
82const GAS_MAX_LIMIT: u64 = 100_000_000;
83
84type ContextWithDB = Context<BlockEnv, TxEnv, CfgEnv, RevmSession, Journal<RevmSession>>;
85type GeneralRevm<DB> =
86 RevmEvm<Context<BlockEnv, TxEnv, CfgEnv, DB>, (), EthInstructions<EthInterpreter<()>, Context<BlockEnv, TxEnv, CfgEnv, DB>>, EthPrecompiles, EthFrame>;
87
88pub struct Evm {
90 evm: RevmEvm<ContextWithDB, (), EthInstructions<EthInterpreter, ContextWithDB>, EthPrecompiles, EthFrame>,
91 kind: EvmKind,
92}
93
94#[derive(Clone, Copy)]
95pub enum EvmKind {
96 Transaction,
97 Call,
98}
99
100impl Evm {
101 pub fn new(storage: Arc<StratusStorage>, config: ExecutorConfig, kind: EvmKind) -> Self {
103 tracing::info!(?config, "creating revm");
104
105 let chain_id = config.executor_chain_id;
107
108 Self {
109 evm: Self::create_evm(chain_id, config.executor_evm_spec, RevmSession::new(storage, config.clone()), kind),
110 kind,
111 }
112 }
113
114 pub fn execute(&mut self, input: EvmInput) -> Result<EvmExecutionResult, StratusError> {
116 #[cfg(feature = "metrics")]
117 let start = metrics::now();
118
119 self.evm.journaled_state.database.reset(input.clone());
121
122 self.evm.fill_env(input);
123
124 if log_enabled!(log::Level::Debug) {
125 let block_env_log = self.evm.block.clone();
126 let tx_env_log = self.evm.tx.clone();
127 tracing::debug!(block_env = ?block_env_log, tx_env = ?tx_env_log, "executing transaction in revm");
129 }
130
131 let tx = std::mem::take(&mut self.evm.tx);
132 let evm_result = self.evm.transact(tx);
133
134 let session = &mut self.evm.journaled_state.database;
136 let session_input = std::mem::take(&mut session.input);
137 let session_storage_changes = std::mem::take(&mut session.storage_changes);
138 let session_metrics = std::mem::take(&mut session.metrics);
139 #[cfg(feature = "metrics")]
140 let session_point_in_time = session.input.point_in_time;
141
142 let execution = match evm_result {
144 Ok(result) => Ok(parse_revm_execution(result, session_input, session_storage_changes)?),
146
147 Err(EVMError::Transaction(InvalidTransaction::NonceTooHigh { tx, state })) => Err(TransactionError::Nonce {
149 transaction: tx.into(),
150 account: state.into(),
151 }
152 .into()),
153 Err(EVMError::Transaction(InvalidTransaction::NonceTooLow { tx, state })) => Err(TransactionError::Nonce {
154 transaction: tx.into(),
155 account: state.into(),
156 }
157 .into()),
158
159 Err(EVMError::Database(e)) => {
161 tracing::warn!(reason = ?e, "evm storage error");
162 Err(e)
163 }
164
165 Err(e) => {
167 tracing::warn!(reason = ?e, "evm transaction error");
168 Err(TransactionError::EvmFailed(e.to_string()).into())
169 }
170 };
171
172 #[cfg(feature = "metrics")]
174 {
175 metrics::inc_evm_execution(start.elapsed(), session_point_in_time, execution.is_ok());
176 metrics::inc_evm_execution_account_reads(session_metrics.account_reads);
177 }
178
179 execution.map(|execution| EvmExecutionResult {
180 execution,
181 metrics: session_metrics,
182 })
183 }
184
185 fn create_evm<DB: Database>(chain_id: u64, spec: SpecId, db: DB, kind: EvmKind) -> GeneralRevm<DB> {
186 let ctx = Context::new(db, spec)
187 .modify_cfg_chained(|cfg_env| {
188 cfg_env.chain_id = chain_id;
189 cfg_env.disable_nonce_check = matches!(kind, EvmKind::Call);
190 cfg_env.disable_eip3607 = matches!(kind, EvmKind::Call);
191 cfg_env.limit_contract_code_size = Some(usize::MAX);
192 })
193 .modify_block_chained(|block_env: &mut BlockEnv| {
194 block_env.beneficiary = Address::COINBASE.into();
195 })
196 .modify_tx_chained(|tx_env: &mut TxEnv| {
197 tx_env.gas_priority_fee = None;
198 });
199
200 RevmEvm::new(ctx, EthInstructions::new_mainnet(), EthPrecompiles::default())
201 }
202
203 pub fn inspect(&mut self, input: InspectorInput) -> Result<GethTrace, StratusError> {
205 let InspectorInput {
206 tx_hash,
207 opts,
208 trace_unsuccessful_only,
209 } = input;
210 let tracer_type = opts.tracer.ok_or_else(|| anyhow!("no tracer type provided"))?;
211
212 if matches!(tracer_type, GethDebugTracerType::BuiltInTracer(GethDebugBuiltInTracerType::NoopTracer)) {
213 return Ok(NoopFrame::default().into());
214 }
215
216 let (tx, mined_data): (TransactionExecution, Option<MinedData>) = self
217 .evm
218 .journaled_state
219 .database
220 .storage
221 .read_transaction(tx_hash)?
222 .ok_or_else(|| anyhow!("transaction not found: {tx_hash}"))?
223 .into();
224
225 if tx.result.execution.deployed_contract_address.is_none() && trace_unsuccessful_only && matches!(tx.result.execution.result, ExecutionResult::Success)
227 {
228 return Ok(default_trace(tracer_type, tx));
229 }
230
231 let block = self
232 .evm
233 .journaled_state
234 .database
235 .storage
236 .read_block(BlockFilter::Number(tx.evm_input.block_number))?
237 .ok_or_else(|| {
238 StratusError::Storage(StorageError::BlockNotFound {
239 filter: BlockFilter::Number(tx.evm_input.block_number),
240 })
241 })?;
242
243 let tx_info = TransactionInfo {
244 block_hash: Some(block.hash().0.0.into()),
245 hash: Some(tx_hash.0.0.into()),
246 index: mined_data.map(|data| data.index.into()),
247 block_number: Some(block.number().as_u64()),
248 base_fee: None,
249 };
250 let inspect_input: EvmInput = tx.evm_input;
251 self.evm.journaled_state.database.reset(EvmInput {
252 point_in_time: PointInTime::MinedPast(inspect_input.block_number.prev().unwrap_or_default()),
253 ..Default::default()
254 });
255
256 let spec = self.evm.cfg.spec;
257
258 let mut cache_db = CacheDB::new(&self.evm.journaled_state.database);
259 let mut evm = Self::create_evm(inspect_input.chain_id.unwrap_or_default().into(), spec, &mut cache_db, self.kind);
260
261 for tx in block.transactions.into_iter() {
263 if tx.info.hash == tx_hash {
264 break;
265 }
266 let tx_input: EvmInput = tx.execution.evm_input;
267
268 evm.fill_env(tx_input);
270 let tx = std::mem::take(&mut evm.tx);
271 evm.transact_commit(tx)?;
272 }
273
274 let trace_result: GethTrace = match tracer_type {
275 GethDebugTracerType::BuiltInTracer(GethDebugBuiltInTracerType::FourByteTracer) => {
276 let mut inspector = FourByteInspector::default();
277 let mut evm_with_inspector = evm.with_inspector(&mut inspector);
278 evm_with_inspector.fill_env(inspect_input);
279 let tx = std::mem::take(&mut evm_with_inspector.tx);
280 evm_with_inspector.inspect_tx(tx)?;
281 FourByteFrame::from(&inspector).into()
282 }
283 GethDebugTracerType::BuiltInTracer(GethDebugBuiltInTracerType::CallTracer) => {
284 let call_config = opts.tracer_config.into_call_config()?;
285 let mut inspector = TracingInspector::new(TracingInspectorConfig::from_geth_call_config(&call_config));
286 let mut evm_with_inspector = evm.with_inspector(&mut inspector);
287 evm_with_inspector.fill_env(inspect_input);
288 let tx = std::mem::take(&mut evm_with_inspector.tx);
289 let res = evm_with_inspector.inspect_tx(tx)?;
290 let mut trace = inspector.geth_builder().geth_call_traces(call_config, res.result.gas_used()).into();
291 enhance_trace_with_decoded_errors(&mut trace);
292 trace
293 }
294 GethDebugTracerType::BuiltInTracer(GethDebugBuiltInTracerType::PreStateTracer) => {
295 let prestate_config = opts.tracer_config.into_pre_state_config()?;
296 let mut inspector = TracingInspector::new(TracingInspectorConfig::from_geth_prestate_config(&prestate_config));
297 let mut evm_with_inspector = evm.with_inspector(&mut inspector);
298 evm_with_inspector.fill_env(inspect_input);
299 let tx = std::mem::take(&mut evm_with_inspector.tx);
300 let res = evm_with_inspector.inspect_tx(tx)?;
301
302 inspector.geth_builder().geth_prestate_traces(&res, &prestate_config, &cache_db)?.into()
303 }
304 GethDebugTracerType::BuiltInTracer(GethDebugBuiltInTracerType::NoopTracer) => NoopFrame::default().into(),
305 GethDebugTracerType::BuiltInTracer(GethDebugBuiltInTracerType::MuxTracer) => {
306 let mux_config = opts.tracer_config.into_mux_config()?;
307 let mut inspector = MuxInspector::try_from_config(mux_config).map_err(|e| anyhow!(e))?;
308 let mut evm_with_inspector = evm.with_inspector(&mut inspector);
309 evm_with_inspector.fill_env(inspect_input);
310 let tx = std::mem::take(&mut evm_with_inspector.tx);
311 let res = evm_with_inspector.inspect_tx(tx)?;
312 inspector.try_into_mux_frame(&res, &cache_db, tx_info)?.into()
313 }
314 GethDebugTracerType::BuiltInTracer(GethDebugBuiltInTracerType::FlatCallTracer) => {
315 let flat_call_config = opts.tracer_config.into_flat_call_config()?;
316 let mut inspector = TracingInspector::new(TracingInspectorConfig::from_flat_call_config(&flat_call_config));
317 let mut evm_with_inspector = evm.with_inspector(&mut inspector);
318 evm_with_inspector.fill_env(inspect_input);
319 let tx = std::mem::take(&mut evm_with_inspector.tx);
320 let res = evm_with_inspector.inspect_tx(tx)?;
321 inspector
322 .with_transaction_gas_limit(res.result.gas_used())
323 .into_parity_builder()
324 .into_localized_transaction_traces(tx_info)
325 .into()
326 }
327 GethDebugTracerType::JsTracer(code) => {
328 let mut inspector = JsInspector::new(code, opts.tracer_config.into_json()).map_err(|e| anyhow!(e.to_string()))?;
329 let mut evm_with_inspector = evm.with_inspector(&mut inspector);
330 evm_with_inspector.fill_env(inspect_input);
331 let tx = std::mem::take(&mut evm_with_inspector.tx);
332 let block = std::mem::take(&mut evm_with_inspector.block);
333 let res = evm_with_inspector.inspect_tx(tx.clone())?;
334 GethTrace::JS(inspector.json_result(res, &tx, &block, &cache_db).map_err(|e| anyhow!(e.to_string()))?)
335 }
336 };
337
338 Ok(trace_result)
339 }
340}
341
342trait TxEnvExt {
343 fn fill_env(&mut self, input: EvmInput);
344}
345
346trait EvmExt<DB: Database> {
347 fn fill_env(&mut self, input: EvmInput);
348}
349
350impl<DB: Database, INSP, I, P, F> EvmExt<DB> for RevmEvm<Context<BlockEnv, TxEnv, CfgEnv, DB>, INSP, I, P, F> {
351 fn fill_env(&mut self, input: EvmInput) {
352 self.block.fill_env(&input);
353 self.tx.fill_env(input);
354 }
355}
356
357impl TxEnvExt for TxEnv {
358 fn fill_env(&mut self, input: EvmInput) {
359 self.caller = input.from.into();
360 self.kind = match input.to {
361 Some(contract) => TransactTo::Call(contract.into()),
362 None => TransactTo::Create,
363 };
364 self.gas_limit = GAS_MAX_LIMIT;
365 self.gas_price = 0;
366 self.chain_id = input.chain_id.map_into();
367 self.nonce = input.nonce.map_into().unwrap_or_default();
368 self.data = input.data.into();
369 self.value = input.value.into();
370 self.gas_priority_fee = None;
371 }
372}
373
374trait BlockEnvExt {
375 fn fill_env(&mut self, input: &EvmInput);
376}
377
378impl BlockEnvExt for BlockEnv {
379 fn fill_env(&mut self, input: &EvmInput) {
380 self.timestamp = U256::from(*input.block_timestamp);
381 self.number = U256::from(input.block_number.as_u64());
382 self.basefee = 0;
383 }
384}
385
386struct RevmSession {
392 config: ExecutorConfig,
394
395 storage: Arc<StratusStorage>,
397
398 input: EvmInput,
400
401 storage_changes: ExecutionChanges,
403
404 metrics: EvmExecutionMetrics,
406}
407
408impl RevmSession {
409 pub fn new(storage: Arc<StratusStorage>, config: ExecutorConfig) -> Self {
411 Self {
412 config,
413 storage,
414 input: EvmInput::default(),
415 storage_changes: ExecutionChanges::default(),
416 metrics: EvmExecutionMetrics::default(),
417 }
418 }
419
420 pub fn reset(&mut self, input: EvmInput) {
422 self.input = input;
423 self.storage_changes = ExecutionChanges::default();
424 self.metrics = EvmExecutionMetrics::default();
425 }
426}
427
428impl Database for RevmSession {
429 type Error = StratusError;
430
431 fn basic(&mut self, revm_address: RevmAddress) -> Result<Option<AccountInfo>, StratusError> {
432 self.metrics.account_reads += 1;
433
434 let address: Address = revm_address.into();
436 let account = self.storage.read_account(address, self.input.point_in_time, self.input.kind)?;
437
438 if let Some(to_address) = self.input.to
440 && account.bytecode.is_none()
441 && address == to_address
442 && self.input.is_contract_call()
443 {
444 if self.config.executor_reject_not_contract {
445 return Err(TransactionError::AccountNotContract { address: to_address }.into());
446 } else {
447 tracing::warn!(%address, "evm to_account is not a contract because does not have bytecode");
448 }
449 }
450
451 if !address.is_ignored()
452 && let std::collections::hash_map::Entry::Vacant(entry) = self.storage_changes.accounts.entry(address)
453 {
454 entry.insert(ExecutionAccountChanges::from_unchanged(account.clone()));
455 }
456
457 Ok(Some(account.into()))
458 }
459
460 fn code_by_hash(&mut self, _: B256) -> Result<RevmBytecode, StratusError> {
461 todo!()
462 }
463
464 fn storage(&mut self, revm_address: RevmAddress, revm_index: U256) -> Result<U256, StratusError> {
465 self.metrics.slot_reads += 1;
466
467 let address: Address = revm_address.into();
469 let index: SlotIndex = revm_index.into();
470
471 let slot = self.storage.read_slot(address, index, self.input.point_in_time, self.input.kind)?;
473
474 Ok(slot.value.into())
475 }
476
477 fn block_hash(&mut self, _: u64) -> Result<B256, StratusError> {
478 todo!()
479 }
480}
481
482impl DatabaseRef for RevmSession {
483 type Error = StratusError;
484
485 fn basic_ref(&self, address: revm::primitives::Address) -> Result<Option<AccountInfo>, Self::Error> {
486 let address: Address = address.into();
488 let account = self.storage.read_account(address, self.input.point_in_time, self.input.kind)?;
489 Ok(Some(account.into()))
490 }
491
492 fn storage_ref(&self, address: revm::primitives::Address, index: U256) -> Result<U256, Self::Error> {
493 let address: Address = address.into();
495 let index: SlotIndex = index.into();
496
497 let slot = self.storage.read_slot(address, index, self.input.point_in_time, self.input.kind)?;
499
500 Ok(slot.value.into())
501 }
502
503 fn block_hash_ref(&self, _: u64) -> Result<B256, Self::Error> {
504 todo!()
505 }
506
507 fn code_by_hash_ref(&self, _code_hash: B256) -> Result<revm::state::Bytecode, Self::Error> {
508 unimplemented!()
509 }
510}
511
512fn parse_revm_execution(revm_result: ResultAndState, input: EvmInput, execution_changes: ExecutionChanges) -> Result<EvmExecution, StratusError> {
517 let (result, tx_output, logs, gas) = parse_revm_result(revm_result.result);
518 let (changes, deployed_contract_address) = parse_revm_state(revm_result.state, execution_changes)?;
519 tracing::debug!(?result, %gas, tx_output_len = %tx_output.len(), %tx_output, "evm executed");
520
521 Ok(EvmExecution {
522 block_timestamp: input.block_timestamp,
523 result,
524 output: tx_output,
525 logs,
526 gas_used: gas,
527 changes,
528 deployed_contract_address,
529 })
530}
531
532fn parse_revm_result(result: RevmExecutionResult) -> (ExecutionResult, Bytes, Vec<Log>, Gas) {
533 match result {
534 RevmExecutionResult::Success { output, gas_used, logs, .. } => {
535 let result = ExecutionResult::Success;
536 let output = Bytes::from(output);
537 let logs = logs.into_iter().map_into().collect();
538 let gas = Gas::from(gas_used);
539 (result, output, logs, gas)
540 }
541 RevmExecutionResult::Revert { output, gas_used } => {
542 let output = Bytes::from(output);
543 let result = ExecutionResult::Reverted { reason: (&output).into() };
544 let gas = Gas::from(gas_used);
545 (result, output, Vec::new(), gas)
546 }
547 RevmExecutionResult::Halt { reason, gas_used } => {
548 let result = ExecutionResult::new_halted(format!("{reason:?}"));
549 let output = Bytes::default();
550 let gas = Gas::from(gas_used);
551 (result, output, Vec::new(), gas)
552 }
553 }
554}
555
556fn parse_revm_state(revm_state: EvmState, mut execution_changes: ExecutionChanges) -> Result<(ExecutionChanges, Option<Address>), StratusError> {
557 let mut deployed_contract_address = None;
558
559 for (revm_address, revm_account) in revm_state {
560 let address: Address = revm_address.into();
561 if address.is_ignored() {
562 continue;
563 }
564
565 tracing::debug!(
567 %address,
568 status = ?revm_account.status,
569 balance = %revm_account.info.balance,
570 nonce = %revm_account.info.nonce,
571 slots = %revm_account.storage.len(),
572 "evm account"
573 );
574
575 let (account_created, account_touched) = (revm_account.is_created(), revm_account.is_touched());
576
577 if !(account_created || account_touched) {
578 continue;
579 }
580
581 let account: Account = (revm_address, revm_account.info).into();
583 let account_modified_slots: Vec<Slot> = revm_account
584 .storage
585 .into_iter()
586 .filter_map(|(index, value)| match value.is_changed() {
587 true => Some(Slot::new(index.into(), value.present_value.into())),
588 false => None,
589 })
590 .collect();
591
592 if account_created && account.bytecode.is_some() {
593 deployed_contract_address = Some(account.address);
594 }
595
596 execution_changes.insert(account, account_modified_slots);
597 }
598 Ok((execution_changes, deployed_contract_address))
599}
600
601pub fn default_trace(tracer_type: GethDebugTracerType, tx: TransactionExecution) -> GethTrace {
602 match tracer_type {
603 GethDebugTracerType::BuiltInTracer(GethDebugBuiltInTracerType::FourByteTracer) => FourByteFrame::default().into(),
604 GethDebugTracerType::BuiltInTracer(GethDebugBuiltInTracerType::CallTracer) => {
606 let (typ, to) = match tx.evm_input.to {
607 Some(_) => ("CALL".to_string(), tx.evm_input.to.map_into()),
608 None => ("CREATE".to_string(), tx.result.execution.deployed_contract_address.map_into()),
609 };
610
611 CallFrame {
612 from: tx.evm_input.from.into(),
613 to,
614 typ,
615 ..Default::default()
616 }
617 .into()
618 }
619 GethDebugTracerType::BuiltInTracer(GethDebugBuiltInTracerType::MuxTracer) => MuxFrame::default().into(),
620 GethDebugTracerType::BuiltInTracer(GethDebugBuiltInTracerType::FlatCallTracer) => FlatCallFrame::default().into(),
621 _ => NoopFrame::default().into(),
622 }
623}
624
625fn enhance_trace_with_decoded_errors(trace: &mut GethTrace) {
627 match trace {
628 GethTrace::CallTracer(call_frame) => {
629 enhance_call_frame_errors(call_frame);
630 }
631 _ => {
632 }
634 }
635}
636
637fn enhance_call_frame_errors(frame: &mut CallFrame) {
639 if let Some(error) = frame.error.as_ref()
640 && let Some(decoded_error) = frame.output.as_ref().and_then(|output| codegen::error_sig_opt(output))
641 {
642 frame.revert_reason = Some(format!("{error}: {decoded_error}"));
643 }
644
645 for nested_call in frame.calls.iter_mut() {
646 enhance_call_frame_errors(nested_call);
647 }
648}