Skip to main content

reth_engine_tree/tree/payload_processor/bal/
worker.rs

1use super::BalExecutionError;
2use alloy_consensus::Transaction;
3use alloy_eip7928::BlockAccessIndex;
4use alloy_primitives::{Address, B256, U256};
5use evm2::{bytecode::Bytecode, evm::AccountInfo, AnyError};
6use reth_concurrency::sync::{
7    channel::{select_biased, Receiver, Sender},
8    rayon::Scope,
9};
10use reth_evm::{
11    BlockExecutionError, BlockExecutor, BlockExecutorFactory, BlockExecutorFor,
12    BlockValidationError, ConfigureEvm, Database, EvmEnvFor, ExecutableTxFor, ExecutionCtxFor,
13};
14use std::{cell::RefCell, rc::Rc, sync::Arc};
15
16#[derive(Debug, thiserror::Error)]
17pub(super) enum BalWorkerError {
18    /// Worker state or provider setup failed.
19    #[error("BAL worker setup failed: {0}")]
20    Setup(#[source] BalExecutionError),
21    /// Transaction recovery or conversion failed before EVM execution.
22    #[error("BAL worker transaction conversion failed for transaction {tx_index}: {source}")]
23    Transaction {
24        /// Index of the transaction that failed.
25        tx_index: usize,
26        /// The underlying recovery or conversion error.
27        #[source]
28        source: AnyError,
29    },
30    /// EVM transaction execution failed.
31    #[error("BAL worker EVM execution failed for transaction {tx_index}: {source}")]
32    Execution {
33        /// Index of the transaction that failed.
34        tx_index: usize,
35        /// Gas limit of the transaction that failed.
36        tx_gas_limit: u64,
37        /// The underlying execution error.
38        #[source]
39        source: BlockExecutionError,
40    },
41}
42
43impl From<BalWorkerError> for BalExecutionError {
44    fn from(err: BalWorkerError) -> Self {
45        match err {
46            BalWorkerError::Setup(err) => err,
47            BalWorkerError::Transaction { source, .. } => {
48                Self::Execution(BlockValidationError::Other(source).into())
49            }
50            BalWorkerError::Execution { source, .. } => Self::Execution(source),
51        }
52    }
53}
54
55pub(super) struct BalWorkerOutput<R> {
56    pub(super) index: usize,
57    pub(super) signer: Address,
58    pub(super) tx_gas_limit: u64,
59    pub(super) result: R,
60}
61
62type WorkerExecutorResult<'a, Cfg> =
63    <BlockExecutorFor<'a, Cfg> as BlockExecutor>::TransactionResultWithState;
64
65type WorkerResultSender<'a, Cfg> =
66    Sender<Result<BalWorkerOutput<WorkerExecutorResult<'a, Cfg>>, BalWorkerError>>;
67
68#[expect(clippy::too_many_arguments)]
69pub(super) fn spawn_worker<'scope, Evm, Tx, Err, DB, MakeDb>(
70    scope: &Scope<'scope>,
71    tx_rx: Receiver<(usize, Result<Tx, Err>)>,
72    abort_rx: Receiver<()>,
73    result_tx: WorkerResultSender<'scope, Evm>,
74    evm_config: &'scope Evm,
75    make_db: &'scope MakeDb,
76    received_bal: Arc<<BlockExecutorFor<'scope, Evm> as BlockExecutor>::BlockAccessList>,
77    evm_env: EvmEnvFor<Evm>,
78    ctx: ExecutionCtxFor<'scope, Evm>,
79) where
80    Evm: ConfigureEvm + 'scope,
81    Tx: ExecutableTxFor<Evm> + Send + 'scope,
82    Err: core::error::Error + Send + Sync + 'static,
83    DB: Database + Send + 'scope,
84    MakeDb: Fn(bool) -> Result<DB, BalExecutionError> + Sync + 'scope,
85{
86    scope.spawn(move |_| {
87        let worker_result = (|| -> Result<(), BalWorkerError> {
88            // Keep the cache-filling database across executor resets so a speculative failure
89            // cannot introduce an unindexed provider setup error ahead of its ordered verdict.
90            let database = Rc::new(RefCell::new(make_db(true).map_err(BalWorkerError::Setup)?));
91            'worker: loop {
92                let evm =
93                    evm_config.evm_with_env(WorkerDatabase(database.clone()), evm_env.clone());
94                let mut executor =
95                    evm_config.block_executor_factory().create_executor(evm, ctx.clone());
96                executor.set_block_access_list(Arc::clone(&received_bal));
97
98                loop {
99                    let (tx_index, tx) = select_biased! {
100                        recv(abort_rx) -> _ => break 'worker,
101                        recv(tx_rx) -> msg => match msg {
102                            Ok(ix_tx) => ix_tx,
103                            Err(_) => break 'worker,
104                        },
105                    };
106                    let tx = match tx {
107                        Ok(tx) => tx,
108                        Err(source) => {
109                            let error = BalWorkerError::Transaction {
110                                tx_index,
111                                source: AnyError::new(source),
112                            };
113                            if result_tx.send(Err(error)).is_err() {
114                                break 'worker;
115                            }
116                            continue;
117                        }
118                    };
119                    let signer = *tx.signer();
120                    let tx_gas_limit = tx.tx().gas_limit();
121
122                    executor
123                        .set_block_access_index(BlockAccessIndex::from_tx_index(tx_index as u64));
124                    let message = match executor.execute_transaction_without_commit(tx) {
125                        Ok(result) => {
126                            Ok(BalWorkerOutput { index: tx_index, signer, tx_gas_limit, result })
127                        }
128                        Err(source) => {
129                            Err(BalWorkerError::Execution { tx_index, tx_gas_limit, source })
130                        }
131                    };
132                    let failed = message.is_err();
133                    if result_tx.send(message).is_err() {
134                        break 'worker;
135                    }
136                    if failed {
137                        // The executor trait does not guarantee reuse after an error. Rebuild
138                        // its EVM and state before serving more work: the queue can still contain
139                        // earlier transactions whose verdict must precede this failure.
140                        break;
141                    }
142                }
143            }
144
145            Ok(())
146        })();
147
148        if let Err(err) = worker_result {
149            let _ = result_tx.send(Err(err));
150        }
151    });
152}
153
154// Executor resets retain the same provider. The wrapper is created and used entirely on one
155// worker thread; its shared ownership decouples the database lifetime from each executor.
156struct WorkerDatabase<DB>(Rc<RefCell<DB>>);
157
158impl<DB: Database> Database for WorkerDatabase<DB> {
159    type Error = DB::Error;
160
161    fn is_fatal(error: &Self::Error) -> bool {
162        DB::is_fatal(error)
163    }
164
165    fn get_account(&mut self, address: &Address) -> Result<Option<AccountInfo>, Self::Error> {
166        self.0.borrow_mut().get_account(address)
167    }
168
169    fn get_code_by_hash(&mut self, hash: &B256) -> Result<Bytecode, Self::Error> {
170        self.0.borrow_mut().get_code_by_hash(hash)
171    }
172
173    fn get_storage(&mut self, address: &Address, key: &U256) -> Result<U256, Self::Error> {
174        self.0.borrow_mut().get_storage(address, key)
175    }
176
177    fn get_block_hash(&mut self, number: &U256) -> Result<B256, Self::Error> {
178        self.0.borrow_mut().get_block_hash(number)
179    }
180}