Skip to main content

revm_handler/
api.rs

1use crate::{
2    frame::EthFrame, instructions::InstructionProvider, Handler, MainnetHandler, PrecompileProvider,
3};
4use context::{
5    result::{
6        EVMError, ExecResultAndState, ExecutionResult, HaltReason, InvalidTransaction,
7        ResultAndState, ResultVecAndState, TransactionIndexedError,
8    },
9    Block, ContextSetters, ContextTr, Database, Evm, JournalTr, Transaction,
10};
11#[cfg(feature = "asyncdb")]
12use database_interface::async_db::{on_fiber_result_with_stack, AsyncResult};
13use database_interface::DatabaseCommit;
14use interpreter::{interpreter::EthInterpreter, InterpreterResult};
15use state::EvmState;
16#[cfg(feature = "asyncdb")]
17use std::ptr::NonNull;
18use std::vec::Vec;
19
20/// Type alias for the result of transact_many_finalize to reduce type complexity.
21type TransactManyFinalizeResult<ExecutionResult, State, Error> =
22    Result<ResultVecAndState<ExecutionResult, State>, TransactionIndexedError<Error>>;
23
24/// Execute EVM transactions. Main trait for transaction execution.
25pub trait ExecuteEvm {
26    /// Output of transaction execution.
27    type ExecutionResult;
28    /// Output state type representing changes after execution.
29    type State;
30    /// Error type
31    type Error;
32    /// Transaction type.
33    type Tx: Transaction;
34    /// Block type.
35    type Block: Block;
36
37    /// Set the block.
38    fn set_block(&mut self, block: Self::Block);
39
40    /// Execute transaction and store state inside journal. Returns output of transaction execution.
41    ///
42    /// # Return Value
43    /// Returns only the execution result
44    ///
45    /// # Error Handling
46    /// If the transaction fails, the journal will revert all changes of given transaction.
47    /// For quicker error handling, use [`ExecuteEvm::transact`] that will drop the journal.
48    ///
49    /// # State Management
50    /// State changes are stored in the internal journal.
51    /// To retrieve the state, call [`ExecuteEvm::finalize`] after transaction execution.
52    ///
53    /// # History Note
54    /// Previously this function returned both output and state.
55    /// Now it follows a two-step process: execute then finalize.
56    fn transact_one(&mut self, tx: Self::Tx) -> Result<Self::ExecutionResult, Self::Error>;
57
58    /// Finalize execution, clearing the journal and returning the accumulated state changes.
59    ///
60    /// # State Management
61    /// Journal is cleared and can be used for next transaction.
62    fn finalize(&mut self) -> Self::State;
63
64    /// Transact the given transaction and finalize in a single operation.
65    ///
66    /// Internally calls [`ExecuteEvm::transact_one`] followed by [`ExecuteEvm::finalize`].
67    ///
68    /// # Outcome of Error
69    ///
70    /// If the transaction fails, the journal is considered broken.
71    #[inline]
72    fn transact(
73        &mut self,
74        tx: Self::Tx,
75    ) -> Result<ExecResultAndState<Self::ExecutionResult, Self::State>, Self::Error> {
76        let output_or_error = self.transact_one(tx);
77        // finalize will clear the journal
78        let state = self.finalize();
79        let output = output_or_error?;
80        Ok(ExecResultAndState::new(output, state))
81    }
82
83    /// Execute multiple transactions without finalizing the state.
84    ///
85    /// Returns a vector of execution results. State changes are accumulated in the journal
86    /// but not finalized. Call [`ExecuteEvm::finalize`] after execution to retrieve state changes.
87    ///
88    /// # Outcome of Error
89    ///
90    /// If any transaction fails, the journal is finalized and the error is returned with the
91    /// transaction index that failed.
92    #[deprecated(
93        note = "batched execution is unused and will be removed; call `transact` or `transact_commit` for each transaction instead"
94    )]
95    #[inline]
96    fn transact_many(
97        &mut self,
98        txs: impl Iterator<Item = Self::Tx>,
99    ) -> Result<Vec<Self::ExecutionResult>, TransactionIndexedError<Self::Error>> {
100        let (lower, _) = txs.size_hint();
101        let mut outputs = Vec::with_capacity(lower);
102        for (index, tx) in txs.enumerate() {
103            outputs.push(
104                self.transact_one(tx)
105                    .inspect_err(|_| {
106                        let _ = self.finalize();
107                    })
108                    .map_err(|error| TransactionIndexedError::new(error, index))?,
109            );
110        }
111        Ok(outputs)
112    }
113
114    /// Execute multiple transactions and finalize the state in a single operation.
115    ///
116    /// Internally calls [`ExecuteEvm::transact_many`] followed by [`ExecuteEvm::finalize`].
117    #[deprecated(
118        note = "batched execution is unused and will be removed; call `transact` or `transact_commit` for each transaction instead"
119    )]
120    #[inline]
121    #[allow(deprecated)]
122    fn transact_many_finalize(
123        &mut self,
124        txs: impl Iterator<Item = Self::Tx>,
125    ) -> TransactManyFinalizeResult<Self::ExecutionResult, Self::State, Self::Error> {
126        // on error transact_multi will clear the journal
127        let result = self.transact_many(txs)?;
128        let state = self.finalize();
129        Ok(ExecResultAndState::new(result, state))
130    }
131
132    /// Execute previous transaction and finalize it.
133    fn replay(
134        &mut self,
135    ) -> Result<ExecResultAndState<Self::ExecutionResult, Self::State>, Self::Error>;
136}
137
138/// Extension of the [`ExecuteEvm`] trait that adds a method that commits the state after execution.
139pub trait ExecuteCommitEvm: ExecuteEvm {
140    /// Commit the state.
141    fn commit(&mut self, state: Self::State);
142
143    /// Finalize the state and commit it to the database.
144    ///
145    /// Internally calls `finalize` and `commit` functions.
146    #[inline]
147    fn commit_inner(&mut self) {
148        let state = self.finalize();
149        self.commit(state);
150    }
151
152    /// Transact the transaction and commit to the state.
153    ///
154    /// # Outcome of Error
155    ///
156    /// If the transaction fails, the journal is finalized (not committed) so it
157    /// does not leak into the next transaction.
158    #[inline]
159    fn transact_commit(&mut self, tx: Self::Tx) -> Result<Self::ExecutionResult, Self::Error> {
160        let output = self.transact_one(tx).inspect_err(|_| {
161            // finalize (clear) the journal on error; do not commit it.
162            let _ = self.finalize();
163        })?;
164        self.commit_inner();
165        Ok(output)
166    }
167
168    /// Transact multiple transactions and commit to the state.
169    ///
170    /// Internally calls `transact_many` and `commit_inner` functions.
171    #[deprecated(
172        note = "batched execution is unused and will be removed; call `transact` or `transact_commit` for each transaction instead"
173    )]
174    #[inline]
175    #[allow(deprecated)]
176    fn transact_many_commit(
177        &mut self,
178        txs: impl Iterator<Item = Self::Tx>,
179    ) -> Result<Vec<Self::ExecutionResult>, TransactionIndexedError<Self::Error>> {
180        let outputs = self.transact_many(txs)?;
181        self.commit_inner();
182        Ok(outputs)
183    }
184
185    /// Replay the transaction and commit to the state.
186    ///
187    /// Internally calls `replay` and `commit` functions.
188    #[inline]
189    fn replay_commit(&mut self) -> Result<Self::ExecutionResult, Self::Error> {
190        let result = self.replay()?;
191        self.commit(result.state);
192        Ok(result.result)
193    }
194}
195
196/// Async extension of the [`ExecuteEvm`] trait that runs execution on an async fiber.
197#[cfg(feature = "asyncdb")]
198pub trait ExecuteEvmAsync: ExecuteEvm {
199    /// Execute transaction and store state inside journal on an async fiber.
200    fn transact_one_async(
201        &mut self,
202        tx: Self::Tx,
203    ) -> impl core::future::Future<Output = AsyncResult<Self::ExecutionResult, Self::Error>> + Send + '_;
204
205    /// Transact the given transaction and finalize in a single operation on an async fiber.
206    fn transact_async(
207        &mut self,
208        tx: Self::Tx,
209    ) -> impl core::future::Future<
210        Output = AsyncResult<ExecResultAndState<Self::ExecutionResult, Self::State>, Self::Error>,
211    > + Send
212           + '_;
213}
214
215impl<CTX, INSP, INST, PRECOMPILES> ExecuteEvm
216    for Evm<CTX, INSP, INST, PRECOMPILES, EthFrame<EthInterpreter>>
217where
218    CTX: ContextTr<Journal: JournalTr<State = EvmState>> + ContextSetters,
219    INST: InstructionProvider<Context = CTX, InterpreterTypes = EthInterpreter>,
220    PRECOMPILES: PrecompileProvider<CTX, Output = InterpreterResult>,
221{
222    type ExecutionResult = ExecutionResult<HaltReason>;
223    type State = EvmState;
224    type Error = EVMError<<CTX::Db as Database>::Error, InvalidTransaction>;
225    type Tx = <CTX as ContextTr>::Tx;
226    type Block = <CTX as ContextTr>::Block;
227
228    #[inline]
229    fn transact_one(&mut self, tx: Self::Tx) -> Result<Self::ExecutionResult, Self::Error> {
230        self.ctx.set_tx(tx);
231        MainnetHandler::default().run(self)
232    }
233
234    #[inline]
235    fn finalize(&mut self) -> Self::State {
236        self.journal_mut().finalize()
237    }
238
239    #[inline]
240    fn set_block(&mut self, block: Self::Block) {
241        self.ctx.set_block(block);
242    }
243
244    #[inline]
245    fn replay(&mut self) -> Result<ResultAndState<HaltReason>, Self::Error> {
246        MainnetHandler::default()
247            .run(self)
248            // finalize (clear) the journal on error; on success the `map`
249            // branch below finalizes it.
250            .inspect_err(|_| {
251                let _ = self.finalize();
252            })
253            .map(|result| {
254                let state = self.finalize();
255                ResultAndState::new(result, state)
256            })
257    }
258}
259
260#[cfg(feature = "asyncdb")]
261impl<CTX, INSP, INST, PRECOMPILES> ExecuteEvmAsync
262    for Evm<CTX, INSP, INST, PRECOMPILES, EthFrame<EthInterpreter>>
263where
264    CTX: ContextTr<Journal: JournalTr<State = EvmState>> + ContextSetters,
265    INST: InstructionProvider<Context = CTX, InterpreterTypes = EthInterpreter>,
266    PRECOMPILES: PrecompileProvider<CTX, Output = InterpreterResult>,
267    ExecutionResult<HaltReason>: Send,
268    EvmState: Send,
269    EVMError<<CTX::Db as Database>::Error, InvalidTransaction>: Send,
270    <CTX as ContextTr>::Tx: Send,
271{
272    #[inline]
273    fn transact_one_async(
274        &mut self,
275        tx: Self::Tx,
276    ) -> impl core::future::Future<Output = AsyncResult<Self::ExecutionResult, Self::Error>> + Send + '_
277    {
278        let stack = NonNull::from(&mut self.async_stack);
279        // SAFETY: The returned future owns the exclusive `&mut self` borrow, so nothing else can
280        // access the EVM stack slot until that future is dropped.
281        unsafe { on_fiber_result_with_stack(stack, move || self.transact_one(tx)) }
282    }
283
284    #[inline]
285    fn transact_async(
286        &mut self,
287        tx: Self::Tx,
288    ) -> impl core::future::Future<
289        Output = AsyncResult<ExecResultAndState<Self::ExecutionResult, Self::State>, Self::Error>,
290    > + Send
291           + '_ {
292        let stack = NonNull::from(&mut self.async_stack);
293        // SAFETY: The returned future owns the exclusive `&mut self` borrow, so nothing else can
294        // access the EVM stack slot until that future is dropped.
295        unsafe { on_fiber_result_with_stack(stack, move || self.transact(tx)) }
296    }
297}
298
299impl<CTX, INSP, INST, PRECOMPILES> ExecuteCommitEvm
300    for Evm<CTX, INSP, INST, PRECOMPILES, EthFrame<EthInterpreter>>
301where
302    CTX: ContextTr<Journal: JournalTr<State = EvmState>, Db: DatabaseCommit> + ContextSetters,
303    INST: InstructionProvider<Context = CTX, InterpreterTypes = EthInterpreter>,
304    PRECOMPILES: PrecompileProvider<CTX, Output = InterpreterResult>,
305{
306    #[inline]
307    fn commit(&mut self, state: Self::State) {
308        self.db_mut().commit(state);
309    }
310}