Skip to main content

reth_engine_tree/tree/payload_processor/
reuse.rs

1//! Reuse of speculative prewarm execution results.
2//!
3//! Prewarm workers execute block transactions in parallel against the parent state and record
4//! every account and storage value a transaction reads from the database. When sequential
5//! execution reaches a transaction whose recorded reads still match the current state, it commits
6//! the prewarm result instead of executing the transaction again. Missing or stale results fall
7//! back to normal execution, which never waits for prewarming.
8//!
9//! Most conflicts between transactions are balance changes, such as fee credits to the block
10//! beneficiary or value transfers to popular contracts. A transaction that never observes an
11//! account's balance produces the same result for any balance, apart from the balance itself, so
12//! such balances may differ and the transaction's balance change is applied to the current balance
13//! instead. Balances are observed by `BALANCE`, `SELFBALANCE`, `SELFDESTRUCT` and failed value
14//! transfers. Successful value transfers and gas payments only require enough starting balance
15//! to cover the largest cumulative debit recorded during speculation.
16//!
17//! Prewarming also seeds results of pool transactions that the txpool prewarm worker executed on
18//! top of the parent before the block arrived, see [`PoolSeeds`]. Their block environment is
19//! predicted, so they must not depend on fields that turn out to differ, and their fee credit to
20//! the beneficiary is applied to the actual beneficiary when the result is reused.
21
22use alloy_consensus::{InMemorySize, Transaction};
23use alloy_primitives::{
24    address,
25    map::{B256Map, DefaultHashBuilder, Entry},
26    Address, B256, KECCAK256_EMPTY, U256,
27};
28use dashmap::DashMap;
29use derive_where::derive_where;
30use evm2::{
31    bytecode::Bytecode,
32    evm::{
33        AccountChanges, AccountInfo, Database, Db, DbResult, DynDatabase, PendingState, StorageSlot,
34    },
35    interpreter::{op, InstrStop, Interpreter, Message, MessageKind, MessageResult},
36    utils::WordExt,
37    EvmFeatures, EvmTypes, Inspector, InspectorConfig, OpcodeSet, TxResultWithState, Version,
38};
39use reth_concurrency::sync::{
40    atomic::{AtomicUsize, Ordering},
41    parking_lot::{Mutex, RwLock},
42};
43use std::{cell::RefCell, rc::Rc, sync::Arc};
44
45/// Balances above this are compared exactly, so that applying balance changes cannot overflow.
46const MAX_REBASED_BALANCE: U256 = U256::from_limbs([u64::MAX, u64::MAX, 0, 0]);
47
48/// Beneficiary of speculative pool transaction executions.
49///
50/// Results of transactions that access it are discarded, so its value only affects how many are.
51pub(crate) const POOL_BENEFICIARY: Address = address!("0x00000000000000000000000000000000000beef0");
52
53/// Maximum estimated number of bytes held by [`PoolResults`].
54const MAX_POOL_RESULT_BYTES: usize = 64 << 20;
55
56/// Opcodes [`BalanceTracker::step`] is called for. Must contain every opcode it matches on.
57const BALANCE_TRACKER_STEPS: OpcodeSet = {
58    let mut steps = OpcodeSet::EMPTY;
59    steps.insert(op::BALANCE);
60    steps.insert(op::SELFBALANCE);
61    steps.insert(op::SELFDESTRUCT);
62    steps.insert(op::COINBASE);
63    steps.insert(op::TIMESTAMP);
64    steps.insert(op::DIFFICULTY);
65    steps.insert(op::GASLIMIT);
66    steps
67};
68
69/// Returns whether blocks executed with `cfg_env` may reuse prewarm results, which excludes
70/// EIP-8037 multidimensional block gas.
71pub(crate) const fn cfg_reuses_prewarm_results(version: &Version) -> bool {
72    !version.feature(EvmFeatures::EIP8037)
73}
74
75/// Speculative prewarm results of a block's transactions, indexed by their position in the block.
76#[derive_where(Debug)]
77pub(crate) struct PrewarmResults<T: EvmTypes> {
78    slots: Box<[Mutex<ResultSlot<T>>]>,
79    /// Writes predicted by the stored results.
80    predicted: Arc<PredictedState>,
81}
82
83/// Prewarm state of a transaction in [`PrewarmResults`].
84#[derive_where(Debug)]
85enum ResultSlot<T: EvmTypes> {
86    /// Prewarming has not executed the transaction.
87    Empty,
88    /// A result that may be reused.
89    Ready(Box<PrewarmedTx<T>>),
90    /// A result that cannot be reused, with the reads it depends on.
91    Unusable(ReadSet),
92    /// Block execution executed the transaction or reused its result, which are published as
93    /// its actual writes.
94    Executed,
95}
96
97impl<T: EvmTypes> PrewarmResults<T> {
98    /// Creates empty result slots for `transaction_count` transactions.
99    pub(crate) fn new(transaction_count: usize) -> Self {
100        Self {
101            slots: (0..transaction_count).map(|_| Mutex::new(ResultSlot::Empty)).collect(),
102            predicted: Arc::default(),
103        }
104    }
105
106    /// Returns the writes predicted by the stored results.
107    pub(super) const fn predicted(&self) -> &Arc<PredictedState> {
108        &self.predicted
109    }
110
111    /// Stores the prewarm result of the transaction at `index` and publishes its writes if
112    /// [`ReadSet::finish`] accepts its reads, otherwise marks it as unusable.
113    pub(super) fn store(
114        &self,
115        index: usize,
116        result: TxResultWithState<T>,
117        reads: ReadSet,
118        balances: &mut BalanceTracker,
119        tx: SpeculativeTx,
120    ) {
121        match reads.finish(balances, tx) {
122            Ok(reads) => self.set(index, |predicted| {
123                predicted.publish(index, &result.pending_state);
124                ResultSlot::Ready(Box::new(PrewarmedTx { result, reads, credit: None }))
125            }),
126            Err(reads) => self.reject(index, reads),
127        }
128    }
129
130    /// Stores the result of the pool transaction with `hash` as the prewarm result of the
131    /// transaction at `index` and publishes its writes, unless prewarming already executed it or
132    /// the result depends on the block environment fields that `seeds` differ in.
133    ///
134    /// Returns the pool transaction if it was stored.
135    pub(super) fn seed(
136        &self,
137        index: usize,
138        hash: &B256,
139        seeds: &PoolSeeds<T>,
140    ) -> Option<Arc<PoolTx<T>>>
141    where
142        T::TxResultExt: Clone,
143    {
144        let tx = seeds.results.get(hash)?;
145        // The speculative execution treated the actual beneficiary as a cold account.
146        if tx.reads.block_env.intersects(seeds.differs) ||
147            tx.reads.position(seeds.beneficiary).is_some()
148        {
149            return None
150        }
151        let mut slot = self.slots.get(index)?.lock();
152        if !matches!(*slot, ResultSlot::Empty) {
153            return None
154        }
155        self.predicted.publish(index, &tx.result.pending_state);
156        *slot = ResultSlot::Ready(Box::new(PrewarmedTx {
157            result: tx.result.clone(),
158            reads: tx.reads.clone(),
159            credit: Some(BeneficiaryCredit { beneficiary: seeds.beneficiary, amount: tx.credit }),
160        }));
161        Some(tx)
162    }
163
164    /// Marks the result of the transaction at `index` as unusable.
165    pub(super) fn reject(&self, index: usize, mut reads: ReadSet) {
166        // Rejection may depend on any balance, such as the caller's.
167        for read in &mut reads.accounts {
168            read.balance = BalanceDependency::Exact;
169        }
170        self.set(index, |_| ResultSlot::Unusable(reads));
171    }
172
173    /// Replaces the predicted writes of the transaction at `index` with the writes of its actual
174    /// execution by block execution.
175    pub(crate) fn publish_executed(&self, index: usize, state: &PendingState) {
176        let Some(slot) = self.slots.get(index) else { return };
177        let mut slot = slot.lock();
178        if let ResultSlot::Ready(previous) = core::mem::replace(&mut *slot, ResultSlot::Executed) {
179            self.predicted.retract(index, &previous.result.pending_state);
180        }
181        self.predicted.publish(index, state);
182        self.predicted.generation.fetch_add(1, Ordering::Relaxed);
183    }
184
185    /// Replaces the slot of the transaction at `index`, retracting the writes of its previous
186    /// result, unless block execution already published its actual writes.
187    fn set(&self, index: usize, f: impl FnOnce(&PredictedState) -> ResultSlot<T>) {
188        let Some(slot) = self.slots.get(index) else { return };
189        let mut slot = slot.lock();
190        match &*slot {
191            ResultSlot::Ready(previous) => {
192                self.predicted.retract(index, &previous.result.pending_state)
193            }
194            ResultSlot::Executed => return,
195            ResultSlot::Empty | ResultSlot::Unusable(_) => {}
196        }
197        *slot = f(&self.predicted);
198    }
199
200    /// Returns whether the transaction at `index` should be executed again, because prewarming
201    /// skipped it or its reads no longer match the predicted state.
202    pub(super) fn needs_refresh(&self, index: usize) -> bool {
203        let Some(slot) = self.slots.get(index) else { return false };
204        let slot = slot.lock();
205        let reads = match &*slot {
206            ResultSlot::Empty => return true,
207            ResultSlot::Ready(tx) => &tx.reads,
208            ResultSlot::Unusable(reads) => reads,
209            ResultSlot::Executed => return false,
210        };
211        !reads.matches(&self.predicted, index)
212    }
213
214    /// Takes the prewarm result of the transaction at `index` if it is ready and its reads match
215    /// `db`.
216    ///
217    /// The returned result has its balance changes applied to the current balances. Stale results,
218    /// and results whose reads fail, stay in their slot unchanged and are freed with `self`.
219    pub(crate) fn take_valid<DB: DynDatabase + ?Sized>(
220        &self,
221        index: usize,
222        db: &mut DB,
223    ) -> Result<Result<TxResultWithState<T>, ReuseMiss>, evm2::DatabaseError> {
224        let Some(slot) = self.slots.get(index) else { return Ok(Err(ReuseMiss::Missing)) };
225        let mut slot = slot.lock();
226        let mut tx = match core::mem::replace(&mut *slot, ResultSlot::Executed) {
227            ResultSlot::Ready(tx) => tx,
228            ResultSlot::Unusable(reads) => {
229                *slot = ResultSlot::Unusable(reads);
230                return Ok(Err(ReuseMiss::Stale))
231            }
232            previous @ (ResultSlot::Empty | ResultSlot::Executed) => {
233                *slot = previous;
234                return Ok(Err(ReuseMiss::Missing))
235            }
236        };
237        let rebased = match tx.validate(db) {
238            Ok(Some(rebased)) => rebased,
239            result => {
240                *slot = ResultSlot::Ready(tx);
241                return result.map(|_| Err(ReuseMiss::Stale))
242            }
243        };
244        // The result stays published as the prediction of this transaction's writes.
245        if rebased {
246            // Later transactions read the rebased balances.
247            self.predicted.publish_accounts(index, &tx.result.pending_state);
248            self.predicted.generation.fetch_add(1, Ordering::Relaxed);
249        }
250        Ok(Ok(tx.result))
251    }
252}
253
254/// Reason a prewarm result could not be reused.
255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
256pub(crate) enum ReuseMiss {
257    /// Prewarming had not finished the transaction.
258    Missing,
259    /// The speculative result was unusable or failed a reuse eligibility check.
260    Stale,
261}
262
263/// A speculative transaction result and the database reads it depends on.
264#[derive_where(Debug)]
265struct PrewarmedTx<T: EvmTypes> {
266    result: TxResultWithState<T>,
267    reads: ReadSet,
268    /// The fee credit to apply to the block beneficiary, for results of pool transactions.
269    credit: Option<BeneficiaryCredit>,
270}
271
272/// A fee credit to the block beneficiary that a speculative result does not contain.
273#[derive(Debug)]
274struct BeneficiaryCredit {
275    beneficiary: Address,
276    amount: U256,
277}
278
279impl<T: EvmTypes> PrewarmedTx<T> {
280    /// Validates recorded reads, then applies balance changes to the current state.
281    fn validate<DB: DynDatabase + ?Sized>(&mut self, db: &mut DB) -> DbResult<Option<bool>> {
282        for read in &self.reads.storage {
283            if db.get_storage(&read.address, &read.slot)? != read.value {
284                return Ok(None)
285            }
286        }
287        let mut rebased = Vec::new();
288        for read in &self.reads.accounts {
289            let current = db.get_account(&read.address)?;
290            match read.compare(current.as_ref()) {
291                AccountMatch::Same => {}
292                AccountMatch::Rebase { speculative, current } => {
293                    if let Some(account) = self
294                        .result
295                        .pending_state
296                        .account_changes()
297                        .find(|a| a.address == read.address)
298                    {
299                        // Replacing metadata must not erase creation, destruction or storage-wipe
300                        // flags.
301                        if account.created || account.selfdestructed || account.storage.wiped {
302                            return Ok(None)
303                        }
304                        let Some(mut info) = account.current.cloned() else { return Ok(None) };
305                        let Some(balance) = info
306                            .balance
307                            .checked_add(current)
308                            .and_then(|b| b.checked_sub(speculative))
309                        else {
310                            return Ok(None)
311                        };
312                        info.balance = balance;
313                        let mut original = account.original.cloned();
314                        if let Some(original) = &mut original {
315                            original.balance = current;
316                        }
317                        rebased.push((read.address, original, Some(info)));
318                    }
319                }
320                AccountMatch::Differs => return Ok(None),
321            }
322        }
323        if let Some(credit) = &self.credit {
324            let Some(original) = db.get_account(&credit.beneficiary)? else { return Ok(None) };
325            let mut current = original.clone();
326            let Some(balance) = current.balance.checked_add(credit.amount) else { return Ok(None) };
327            current.balance = balance;
328            // Execution touches the beneficiary even for a zero credit, which deletes it if it is
329            // empty (EIP-161). Detached state cannot express that, so execute normally.
330            if current.is_empty() {
331                return Ok(None)
332            }
333            // The synthetic beneficiary was not observed. Preserve its current canonical cache
334            // value when committing the detached result's loaded-but-unchanged entries.
335            let synthetic = db.get_account(&POOL_BENEFICIARY)?;
336            rebased.push((POOL_BENEFICIARY, synthetic.clone(), synthetic));
337            rebased.push((credit.beneficiary, Some(original), Some(current)));
338        }
339        let changed = !rebased.is_empty();
340        for (address, original, current) in rebased {
341            self.result.pending_state.insert_account(address, original, current);
342        }
343        Ok(Some(changed))
344    }
345}
346
347/// How a speculative execution depends on an account's balance.
348#[derive(Debug, Clone, Copy, PartialEq, Eq)]
349enum BalanceDependency {
350    /// The balance was only credited or debited, so it may differ.
351    None,
352    /// The account paid for gas or sent value, so the balance must be at least this large.
353    AtLeast(U256),
354    /// The balance was observed, so it must match.
355    Exact,
356}
357
358/// An account a speculative execution read.
359#[derive(Debug, Clone)]
360struct AccountRead {
361    address: Address,
362    /// The account without its bytecode, `None` if it did not exist.
363    info: Option<AccountInfo>,
364    balance: BalanceDependency,
365    /// Whether the account was read from the predicted state.
366    predicted: bool,
367}
368
369impl AccountRead {
370    /// Compares the read account with `current`.
371    fn compare(&self, current: Option<&AccountInfo>) -> AccountMatch {
372        let (speculative, current) = match (&self.info, current) {
373            (Some(speculative), Some(current)) => (speculative, current),
374            (None, None) => return AccountMatch::Same,
375            _ => return AccountMatch::Differs,
376        };
377        if speculative.balance == current.balance {
378            return if speculative == current { AccountMatch::Same } else { AccountMatch::Differs }
379        }
380
381        let allowed = match self.balance {
382            BalanceDependency::None => true,
383            BalanceDependency::AtLeast(min) => current.balance >= min,
384            BalanceDependency::Exact => false,
385        };
386        // A zero balance can make the account empty, which changes gas costs and EIP-161 state
387        // clearing.
388        if !allowed ||
389            speculative.balance.is_zero() ||
390            current.balance.is_zero() ||
391            current.balance > MAX_REBASED_BALANCE ||
392            (AccountInfo { balance: speculative.balance, ..without_code(current) }) !=
393                *speculative
394        {
395            return AccountMatch::Differs
396        }
397        AccountMatch::Rebase { speculative: speculative.balance, current: current.balance }
398    }
399}
400
401/// How a read account compares with its current state.
402#[derive(Debug, Clone, Copy, PartialEq, Eq)]
403enum AccountMatch {
404    /// The account is unchanged.
405    Same,
406    /// Only the balance changed, so the result's balance change must be applied to the current
407    /// balance.
408    Rebase { speculative: U256, current: U256 },
409    /// The account differs in a way the execution may depend on.
410    Differs,
411}
412
413/// A storage slot a speculative execution read.
414#[derive(Debug, Clone)]
415struct StorageRead {
416    address: Address,
417    slot: U256,
418    value: U256,
419    /// Whether the slot was read from the predicted state.
420    predicted: bool,
421}
422
423/// Database reads of a speculative transaction execution.
424#[derive(Debug, Default, Clone)]
425pub(crate) struct ReadSet {
426    accounts: Vec<AccountRead>,
427    storage: Vec<StorageRead>,
428    /// Whether execution loaded bytecode that is unknown to the database.
429    unknown_code: bool,
430    /// Block environment fields the execution observed.
431    block_env: BlockEnvFields,
432}
433
434impl ReadSet {
435    /// Classifies how the execution depends on the balance of each account it read.
436    ///
437    /// Speculation disables nonce and balance checks, so this fails unless `caller` had the
438    /// transaction's `nonce` and could pay `max_balance_spending`, i.e. unless execution with
439    /// these checks enabled would have accepted the transaction.
440    fn finish(mut self, balances: &mut BalanceTracker, tx: SpeculativeTx) -> Result<Self, Self> {
441        let SpeculativeTx { caller, nonce, max_balance_spending } = tx;
442        // Balance changes are applied once per account.
443        self.accounts.sort_unstable_by_key(|read| read.address);
444        self.accounts.dedup_by_key(|read| read.address);
445        self.block_env = balances.block_env;
446
447        let Ok(caller_index) = self.accounts.binary_search_by_key(&caller, |read| read.address)
448        else {
449            return Err(self)
450        };
451        let caller_info = &self.accounts[caller_index].info;
452        let (caller_nonce, caller_balance) =
453            caller_info.as_ref().map_or((0, U256::ZERO), |info| (info.nonce, info.balance));
454        let Some(max_balance_spending) = max_balance_spending else { return Err(self) };
455        // Transactions at the nonce limit cannot be reused, even with validation disabled.
456        if self.unknown_code ||
457            balances.read_failed ||
458            nonce == u64::MAX ||
459            caller_nonce != nonce ||
460            caller_balance < max_balance_spending
461        {
462            return Err(self)
463        }
464
465        // Rebasing only bounded balances keeps every balance during execution far from overflow,
466        // so no value transfer can overflow in one execution but not the other.
467        let bounded = self
468            .accounts
469            .iter()
470            .all(|read| read.info.as_ref().is_none_or(|info| info.balance <= MAX_REBASED_BALANCE));
471        let paid = caller_balance - max_balance_spending;
472        // Sorted, so that each account is looked up in logarithmic time and the smallest balance
473        // a sender had left comes first.
474        let BalanceTracker { observed, senders, .. } = balances;
475        observed.sort_unstable();
476        senders.sort_unstable();
477        for read in &mut self.accounts {
478            // A sender needs enough balance to leave the same smallest balance, which is the
479            // balance after paying for gas for the caller.
480            let sent = senders
481                .get(senders.partition_point(|(address, _)| *address < read.address))
482                .filter(|(address, _)| *address == read.address)
483                .map(|(_, left)| *left);
484            let left = sent.into_iter().chain((read.address == caller).then_some(paid)).min();
485            read.balance = if !bounded || observed.binary_search(&read.address).is_ok() {
486                BalanceDependency::Exact
487            } else if let Some(left) = left {
488                let balance = read.info.as_ref().map_or(U256::ZERO, |info| info.balance);
489                BalanceDependency::AtLeast(balance.saturating_sub(left))
490            } else {
491                BalanceDependency::None
492            };
493        }
494        Ok(self)
495    }
496
497    /// Returns the position of the read of `address` in the sorted account reads.
498    fn position(&self, address: Address) -> Option<usize> {
499        self.accounts.binary_search_by_key(&address, |read| read.address).ok()
500    }
501
502    /// Returns whether executing the transaction at `index` against `predicted` would read the
503    /// same values, as far as the execution depends on them.
504    fn matches(&self, predicted: &PredictedState, index: usize) -> bool {
505        self.accounts.iter().all(|read| match predicted.account(read.address, index) {
506            Some(account) => read.compare(account.as_ref()) != AccountMatch::Differs,
507            None => !read.predicted,
508        }) && self.storage.iter().all(|read| {
509            match predicted.storage(read.address, read.slot, index) {
510                Some(value) => value == read.value,
511                None => !read.predicted,
512            }
513        })
514    }
515}
516
517/// The fields of a speculatively executed transaction that its validity checks depend on.
518#[derive(Debug)]
519pub(crate) struct SpeculativeTx {
520    /// The transaction's sender.
521    pub(crate) caller: Address,
522    /// The transaction's nonce.
523    pub(crate) nonce: u64,
524    /// The most the caller may spend, or an error if it overflows.
525    pub(crate) max_balance_spending: Option<U256>,
526}
527
528/// Writes of a key, sorted by the index of the transaction that made them.
529type Writes<T> = Vec<(usize, T)>;
530
531/// State writes predicted by speculative results, by transaction index.
532///
533/// Speculative executions read the latest write predicted before their transaction, so that
534/// transactions depending on earlier ones in the block can still be reused.
535#[derive(Debug, Default)]
536pub(super) struct PredictedState {
537    /// Accounts, `None` if destroyed.
538    accounts: DashMap<Address, Writes<Option<AccountInfo>>, DefaultHashBuilder>,
539    storage: DashMap<(Address, U256), Writes<U256>, DefaultHashBuilder>,
540    /// Transactions that cleared an account's storage by creating or destroying it.
541    cleared: DashMap<Address, Writes<()>, DefaultHashBuilder>,
542    /// Bytecode deployed by predicted writes.
543    code: DashMap<B256, Bytecode, DefaultHashBuilder>,
544    /// Number of actual execution or rebased account updates published by block execution.
545    generation: AtomicUsize,
546}
547
548impl PredictedState {
549    /// Returns the number of actual execution or rebased account updates published by block
550    /// execution.
551    pub(super) fn generation(&self) -> usize {
552        self.generation.load(Ordering::Relaxed)
553    }
554
555    /// Returns the latest account write predicted before the transaction at `index`.
556    fn account(&self, address: Address, index: usize) -> Option<Option<AccountInfo>> {
557        let writes = self.accounts.get(&address)?;
558        latest(&writes, index).map(|(_, account)| account.clone())
559    }
560
561    /// Returns the latest storage value predicted before the transaction at `index`.
562    fn storage(&self, address: Address, slot: U256, index: usize) -> Option<U256> {
563        let cleared = self.cleared.get(&address).and_then(|w| latest(&w, index).map(|(i, _)| *i));
564        let written = self.storage.get(&(address, slot)).and_then(|w| latest(&w, index).copied());
565        match (written, cleared) {
566            (Some((written, value)), Some(cleared)) if written >= cleared => Some(value),
567            (_, Some(_)) => Some(U256::ZERO),
568            (written, None) => written.map(|(_, value)| value),
569        }
570    }
571
572    /// Returns predicted bytecode by its hash.
573    fn code(&self, code_hash: B256) -> Option<Bytecode> {
574        self.code.get(&code_hash).map(|code| code.clone())
575    }
576
577    /// Publishes the transaction's writes as predictions for later transactions.
578    fn publish(&self, index: usize, state: &PendingState) {
579        for account in state.account_changes() {
580            if let Some((hash, code)) = account.code {
581                self.code.insert(hash, code.clone());
582            }
583        }
584        self.update(index, state.account_changes(), true);
585    }
586
587    /// Republishes rebased account balances.
588    fn publish_accounts(&self, index: usize, state: &PendingState) {
589        self.update(index, state.account_changes(), true);
590    }
591
592    /// Retracts the transaction's predicted writes.
593    fn retract(&self, index: usize, state: &PendingState) {
594        self.update(index, state.account_changes(), false);
595    }
596
597    /// Publishes or retracts each changed account and slot.
598    fn update<'a>(
599        &self,
600        index: usize,
601        state: impl IntoIterator<Item = AccountChanges<'a>>,
602        publish: bool,
603    ) {
604        for account in state {
605            if !account.is_changed() {
606                continue
607            }
608            let address = account.address;
609            if account.storage.wiped || account.created || account.current.is_none() {
610                write(&mut self.cleared.entry(address).or_default(), index, publish.then_some(()));
611            }
612            write(
613                &mut self.accounts.entry(address).or_default(),
614                index,
615                publish.then(|| account.current.map(without_code)),
616            );
617            if account.current.is_none() {
618                continue
619            }
620            for (&slot, value) in &account.storage.slots {
621                if (account.storage.wiped && !value.value.current.is_zero()) ||
622                    (!account.storage.wiped && value.value.original != value.value.current)
623                {
624                    write(
625                        &mut self.storage.entry((address, slot)).or_default(),
626                        index,
627                        publish.then_some(value.value.current),
628                    );
629                }
630            }
631        }
632    }
633}
634
635/// Sets the write of the transaction at `index`, or removes it if `value` is `None`.
636fn write<T>(writes: &mut Writes<T>, index: usize, value: Option<T>) {
637    match (writes.binary_search_by_key(&index, |(i, _)| *i), value) {
638        (Ok(i), Some(value)) => writes[i].1 = value,
639        (Err(i), Some(value)) => writes.insert(i, (index, value)),
640        (Ok(i), None) => {
641            writes.remove(i);
642        }
643        (Err(_), None) => {}
644    }
645}
646
647/// Returns the latest write before the transaction at `index`.
648fn latest<T>(writes: &[(usize, T)], index: usize) -> Option<&(usize, T)> {
649    writes[..writes.partition_point(|(i, _)| *i < index)].last()
650}
651
652/// Block environment fields that speculative executions may observe and that may differ from the
653/// actual block environment.
654#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
655pub(crate) struct BlockEnvFields {
656    /// The beneficiary, observed by `COINBASE`, by accessing its account, or possibly by running
657    /// out of gas.
658    pub(crate) beneficiary: bool,
659    /// The timestamp, observed by `TIMESTAMP`.
660    pub(crate) timestamp: bool,
661    /// The prevrandao, observed by `PREVRANDAO`.
662    pub(crate) prevrandao: bool,
663    /// The gas limit, observed by `GASLIMIT`.
664    pub(crate) gas_limit: bool,
665}
666
667impl BlockEnvFields {
668    /// Returns whether any field is set in both `self` and `other`.
669    const fn intersects(self, other: Self) -> bool {
670        (self.beneficiary && other.beneficiary) ||
671            (self.timestamp && other.timestamp) ||
672            (self.prevrandao && other.prevrandao) ||
673            (self.gas_limit && other.gas_limit)
674    }
675}
676
677/// Results of pool transactions executed on top of a block's parent in a predicted block
678/// environment with [`POOL_BENEFICIARY`] as the beneficiary, by transaction hash.
679#[derive_where(Debug)]
680pub(crate) struct PoolResults<T: EvmTypes> {
681    stored: RwLock<StoredPoolTxs<T>>,
682}
683
684impl<T: EvmTypes> Default for PoolResults<T> {
685    fn default() -> Self {
686        Self { stored: RwLock::new(StoredPoolTxs { txs: B256Map::default(), bytes: 0 }) }
687    }
688}
689
690/// Results of pool transactions stored in [`PoolResults`].
691#[derive_where(Debug)]
692struct StoredPoolTxs<T: EvmTypes> {
693    txs: B256Map<Arc<PoolTx<T>>>,
694    /// Estimated number of bytes held by `txs`.
695    bytes: usize,
696}
697
698impl<T: EvmTypes> PoolResults<T> {
699    /// Stores the result of the pool transaction with `hash` if [`ReadSet::finish`] accepts its
700    /// reads, unless it may have accessed the beneficiary, a result is already stored for `hash`,
701    /// or the stored results would hold more than [`MAX_POOL_RESULT_BYTES`].
702    ///
703    /// Returns whether the result was stored.
704    pub(crate) fn store(
705        &self,
706        hash: B256,
707        mut result: TxResultWithState<T>,
708        reads: ReadSet,
709        balances: &mut BalanceTracker,
710        tx: SpeculativeTx,
711    ) -> bool {
712        if balances.block_env.beneficiary {
713            return false
714        }
715        let Ok(mut reads) = reads.finish(balances, tx) else { return false };
716
717        // The beneficiary was only loaded to credit fees, which are credited to the actual
718        // beneficiary instead. Crediting fees always loads and touches it, even for zero fees.
719        let Some(beneficiary) = result
720            .pending_state
721            .account_changes()
722            .find(|account| account.address == POOL_BENEFICIARY)
723        else {
724            return false
725        };
726        // A zero fee can leave an empty beneficiary that EIP-161 clears during finalization.
727        let balance = beneficiary.current.map_or(U256::ZERO, |info| info.balance);
728        let Some(index) = reads.position(POOL_BENEFICIARY) else { return false };
729        let original = reads.accounts.remove(index).info;
730        let speculative = original.as_ref().map_or(U256::ZERO, |info| info.balance);
731        if speculative > MAX_REBASED_BALANCE {
732            return false
733        }
734        let Some(credit) = balance.checked_sub(speculative) else { return false };
735        result.pending_state.insert_account(POOL_BENEFICIARY, original.clone(), original);
736
737        let bytes = retained_bytes(&result, &reads);
738        let mut stored = self.stored.write();
739        let total = stored.bytes + bytes;
740        if total > MAX_POOL_RESULT_BYTES {
741            return false
742        }
743        let Entry::Vacant(entry) = stored.txs.entry(hash) else { return false };
744        entry.insert(Arc::new(PoolTx { result, reads, credit }));
745        stored.bytes = total;
746        true
747    }
748
749    /// Returns the result of the pool transaction with `hash`.
750    pub(crate) fn get(&self, hash: &B256) -> Option<Arc<PoolTx<T>>> {
751        self.stored.read().txs.get(hash).cloned()
752    }
753
754    /// Returns whether no result is stored.
755    pub(crate) fn is_empty(&self) -> bool {
756        self.stored.read().txs.is_empty()
757    }
758}
759
760/// Returns the estimated number of bytes that storing `result` and `reads` holds.
761fn retained_bytes<T: EvmTypes>(result: &TxResultWithState<T>, reads: &ReadSet) -> usize {
762    let accounts = result.pending_state.account_changes().map(|account| {
763        size_of::<AccountInfo>() * 2 +
764            size_of::<Address>() +
765            account.storage.slots.capacity() * size_of::<(U256, StorageSlot)>() +
766            account.code.map_or(0, |(_, code)| code.len())
767    });
768    reads.accounts.capacity() * size_of::<AccountRead>() +
769        reads.storage.capacity() * size_of::<StorageRead>() +
770        result.result.output.len() +
771        result.result.logs.iter().map(InMemorySize::size).sum::<usize>() +
772        accounts.sum::<usize>()
773}
774
775/// A speculative result of a pool transaction without its fee credit to the beneficiary.
776#[derive_where(Debug)]
777pub(crate) struct PoolTx<T: EvmTypes> {
778    result: TxResultWithState<T>,
779    reads: ReadSet,
780    /// The fee credit to the beneficiary.
781    credit: U256,
782}
783
784impl<T: EvmTypes> PoolTx<T> {
785    /// Returns the state changes of the transaction.
786    pub(super) const fn state(&self) -> &PendingState {
787        &self.result.pending_state
788    }
789
790    /// Loads every read of the transaction from `db`.
791    pub(super) fn load_reads<DB: DynDatabase + ?Sized>(
792        &self,
793        db: &mut DB,
794    ) -> Result<(), evm2::DatabaseError> {
795        for read in &self.reads.accounts {
796            db.get_account(&read.address)?;
797        }
798        for read in &self.reads.storage {
799            db.get_storage(&read.address, &read.slot)?;
800        }
801        Ok(())
802    }
803}
804
805/// Results of pool transactions that may seed the [`PrewarmResults`] of a block on top of the
806/// parent they were executed on.
807#[derive_where(Debug, Clone)]
808pub(crate) struct PoolSeeds<T: EvmTypes> {
809    results: Arc<PoolResults<T>>,
810    /// The beneficiary of the block.
811    beneficiary: Address,
812    /// Block environment fields that differ from the predicted environment.
813    differs: BlockEnvFields,
814}
815
816impl<T: EvmTypes> PoolSeeds<T> {
817    /// Creates seeds for a block with `beneficiary` whose environment differs from the predicted
818    /// environment of `results` in `differs`.
819    pub(crate) const fn new(
820        results: Arc<PoolResults<T>>,
821        beneficiary: Address,
822        differs: BlockEnvFields,
823    ) -> Self {
824        Self { results, beneficiary, differs }
825    }
826}
827
828/// Database wrapper that records reads for speculative execution.
829#[derive(Debug)]
830pub(crate) struct RecordingDb<DB: Database> {
831    inner: Db<DB>,
832    recording: RecordingHandle,
833}
834
835/// Per-worker recording state shared with its EVM and inspector.
836#[derive(Debug, Default, Clone)]
837pub(crate) struct RecordingHandle(Rc<RefCell<RecordingState>>);
838
839#[derive(Debug, Default)]
840struct RecordingState {
841    reads: Option<ReadSet>,
842    predicted: Option<(Arc<PredictedState>, usize)>,
843}
844
845impl RecordingHandle {
846    /// Begins recording against earlier predicted writes, or just the parent state.
847    pub(super) fn start(&self, predicted: Option<(Arc<PredictedState>, usize)>) {
848        *self.0.borrow_mut() = RecordingState { reads: Some(ReadSet::default()), predicted };
849    }
850
851    /// Begins recording a pool transaction against its parent state.
852    pub(crate) fn start_recording_inner(&self) {
853        self.start(None);
854    }
855
856    /// Stops recording and returns the transaction's reads.
857    pub(crate) fn take_reads(&self) -> Option<ReadSet> {
858        let mut state = self.0.borrow_mut();
859        state.predicted = None;
860        state.reads.take()
861    }
862}
863
864impl<DB: Database> RecordingDb<DB> {
865    /// Wraps a database with the worker's recording state.
866    pub(crate) const fn new(inner: DB, recording: RecordingHandle) -> Self {
867        Self { inner: Db::new(inner), recording }
868    }
869}
870
871impl<DB: Database> Database for RecordingDb<DB> {
872    type Error = evm2::DatabaseError;
873
874    fn is_fatal(error: &Self::Error) -> bool {
875        error.is_fatal()
876    }
877
878    fn get_account(&mut self, address: &Address) -> DbResult<Option<AccountInfo>> {
879        let mut state = self.recording.0.borrow_mut();
880        let predicted =
881            state.predicted.as_ref().and_then(|(state, index)| state.account(*address, *index));
882        let is_predicted = predicted.is_some();
883        let account = match predicted {
884            Some(account) => account,
885            None => self.inner.get_account(address)?,
886        };
887        if let Some(reads) = &mut state.reads {
888            reads.accounts.push(AccountRead {
889                address: *address,
890                info: account.as_ref().map(without_code),
891                balance: BalanceDependency::None,
892                predicted: is_predicted,
893            });
894        }
895        Ok(account)
896    }
897
898    fn get_code_by_hash(&mut self, hash: &B256) -> DbResult<Bytecode> {
899        let mut state = self.recording.0.borrow_mut();
900        if let Some(code) = state.predicted.as_ref().and_then(|(state, _)| state.code(*hash)) {
901            return Ok(code)
902        }
903        let code = self.inner.get_code_by_hash(hash)?;
904        if code.is_empty() &&
905            *hash != KECCAK256_EMPTY &&
906            let Some(reads) = &mut state.reads
907        {
908            reads.unknown_code = true;
909        }
910        Ok(code)
911    }
912
913    fn get_storage(&mut self, address: &Address, key: &U256) -> DbResult<U256> {
914        let mut state = self.recording.0.borrow_mut();
915        let predicted = state
916            .predicted
917            .as_ref()
918            .and_then(|(state, index)| state.storage(*address, *key, *index));
919        let is_predicted = predicted.is_some();
920        let value = match predicted {
921            Some(value) => value,
922            None => self.inner.get_storage(address, key)?,
923        };
924        if let Some(reads) = &mut state.reads {
925            reads.storage.push(StorageRead {
926                address: *address,
927                slot: *key,
928                value,
929                predicted: is_predicted,
930            });
931        }
932        Ok(value)
933    }
934
935    fn get_block_hash(&mut self, number: &U256) -> DbResult<B256> {
936        self.inner.get_block_hash(number)
937    }
938}
939
940/// Copies account metadata without retaining the bytecode allocation.
941fn without_code(info: &AccountInfo) -> AccountInfo {
942    let mut info = info.clone();
943    info.code = None;
944    info
945}
946
947impl SpeculativeTx {
948    /// Captures the nonce and maximum fee and value debit checked by canonical execution.
949    pub(crate) fn new(caller: Address, tx: &impl Transaction) -> Self {
950        let max_balance_spending = U256::from(tx.gas_limit())
951            .checked_mul(U256::from(tx.max_fee_per_gas()))
952            .and_then(|gas| gas.checked_add(tx.value()))
953            .and_then(|gas| {
954                U256::from(tx.blob_gas_used().unwrap_or_default())
955                    .checked_mul(U256::from(tx.max_fee_per_blob_gas().unwrap_or_default()))
956                    .and_then(|blob| gas.checked_add(blob))
957            });
958        Self { caller, nonce: tx.nonce(), max_balance_spending }
959    }
960}
961
962/// Inspector that tracks which balances and block environment fields a transaction observes and
963/// which accounts send value.
964#[derive(Debug, Default)]
965pub(crate) struct BalanceTracker {
966    recording: RecordingHandle,
967    read_failed: bool,
968    /// Accounts whose balance was observed.
969    observed: Vec<Address>,
970    /// Accounts that sent value, with the balance they had left after each send.
971    senders: Vec<(Address, U256)>,
972    /// Block environment fields that were observed.
973    block_env: BlockEnvFields,
974}
975
976impl BalanceTracker {
977    /// Creates an inspector sharing the worker's recorded database reads.
978    pub(crate) fn new(recording: RecordingHandle) -> Self {
979        Self { recording, ..Self::default() }
980    }
981
982    fn frame_end<T: EvmTypes>(
983        &mut self,
984        interp: &mut Interpreter<'_, '_, T>,
985        message: &Message<T>,
986        result: &MessageResult<T>,
987    ) {
988        let beneficiary = interp.host().block().beneficiary;
989        self.block_env.beneficiary |=
990            result.stop.is_out_of_gas() ||
991                (message.depth == 0 &&
992                    self.recording.0.borrow_mut().reads.as_ref().is_some_and(|r| {
993                        r.accounts.iter().any(|a| a.address == beneficiary)
994                    }));
995    }
996
997    fn send<T: EvmTypes>(
998        &mut self,
999        interp: &mut Interpreter<'_, '_, T>,
1000        sender: Address,
1001        value: U256,
1002    ) {
1003        let left = match interp.host().state_mut().account_info_untracked(&sender) {
1004            Ok(account) => account.and_then(|account| account.balance.checked_sub(value)),
1005            Err(_) => {
1006                // A failed observer read cannot justify reusing the speculative result.
1007                self.read_failed = true;
1008                None
1009            }
1010        };
1011        match left {
1012            Some(left) => self.senders.push((sender, left)),
1013            None => self.observed.push(sender),
1014        }
1015    }
1016}
1017
1018impl<T: EvmTypes> Inspector<T> for BalanceTracker {
1019    fn inspector_config(&self) -> InspectorConfig {
1020        InspectorConfig::new().with_steps(BALANCE_TRACKER_STEPS)
1021    }
1022
1023    fn step(&mut self, interp: &mut Interpreter<'_, '_, T>) {
1024        let address = match interp.opcode() {
1025            op::BALANCE => {
1026                let Some(word) = interp.stack().peek(0) else { return };
1027                word.to_address()
1028            }
1029            op::SELFBALANCE | op::SELFDESTRUCT => interp.message().destination,
1030            op::COINBASE => {
1031                self.block_env.beneficiary = true;
1032                return
1033            }
1034            op::TIMESTAMP => {
1035                self.block_env.timestamp = true;
1036                return
1037            }
1038            op::DIFFICULTY => {
1039                self.block_env.prevrandao = true;
1040                return
1041            }
1042            op::GASLIMIT => {
1043                self.block_env.gas_limit = true;
1044                return
1045            }
1046            _ => return,
1047        };
1048        if self.observed.last() != Some(&address) {
1049            self.observed.push(address);
1050        }
1051    }
1052
1053    fn call(
1054        &mut self,
1055        interp: &mut Interpreter<'_, '_, T>,
1056        message: &mut Message<T>,
1057    ) -> Option<MessageResult<T>> {
1058        if matches!(message.kind, MessageKind::Call | MessageKind::CallCode) &&
1059            !message.value.is_zero()
1060        {
1061            self.send(interp, message.caller, message.value);
1062        }
1063        None
1064    }
1065
1066    fn call_end(
1067        &mut self,
1068        interp: &mut Interpreter<'_, '_, T>,
1069        message: &Message<T>,
1070        result: &mut MessageResult<T>,
1071    ) {
1072        if result.stop == InstrStop::OutOfFunds {
1073            self.observed.push(message.caller);
1074        }
1075        self.frame_end(interp, message, result);
1076    }
1077
1078    fn create(
1079        &mut self,
1080        interp: &mut Interpreter<'_, '_, T>,
1081        message: &mut Message<T>,
1082    ) -> Option<MessageResult<T>> {
1083        if !message.value.is_zero() {
1084            self.send(interp, message.caller, message.value);
1085        }
1086        None
1087    }
1088
1089    fn create_end(
1090        &mut self,
1091        interp: &mut Interpreter<'_, '_, T>,
1092        message: &Message<T>,
1093        result: &mut MessageResult<T>,
1094    ) {
1095        if result.stop == InstrStop::OutOfFunds {
1096            self.observed.push(message.caller);
1097        }
1098        self.frame_end(interp, message, result);
1099    }
1100}
1101
1102#[cfg(test)]
1103mod tests {
1104    use super::*;
1105    use alloy_consensus::{transaction::Recovered, TxEip1559, TxLegacy};
1106    use alloy_primitives::{bytes, Bytes, Signature, TxKind};
1107    use evm2::{
1108        evm::{CacheDB, EmptyDB},
1109        BaseEvmTypes, SpecId,
1110    };
1111    use reth_errors::ProviderError;
1112    use reth_ethereum_primitives::{Receipt, Transaction, TransactionSigned};
1113    use reth_evm::{BlockExecutor, BlockExecutorFactory, ConfigureEvm, Evm, EvmFor};
1114    use reth_evm_ethereum::{EthBlockExecutionCtx, EthEvmConfig, EthEvmEnv};
1115    use reth_trie_common::bundle_state::BundleState;
1116
1117    const BENEFICIARY: Address = Address::repeat_byte(0xbe);
1118    /// Does nothing.
1119    const NOOP: Address = Address::repeat_byte(0xc0);
1120    /// Increments slot 0.
1121    const COUNTER: Address = Address::repeat_byte(0xc1);
1122    /// Stores the beneficiary balance in slot 0.
1123    const BENEFICIARY_BALANCE_READER: Address = Address::repeat_byte(0xc2);
1124    /// Logs its own balance.
1125    const SELF_BALANCE_READER: Address = Address::repeat_byte(0xc3);
1126    /// Sends 5 wei to [`NOOP`].
1127    const FORWARDER: Address = Address::repeat_byte(0xc4);
1128    /// Has a balance above [`MAX_REBASED_BALANCE`].
1129    const RICH: Address = Address::repeat_byte(0xc5);
1130    /// Exists with a zero balance.
1131    const ZERO_BALANCE: Address = Address::repeat_byte(0xc6);
1132    /// Has a code hash whose bytecode the database does not know.
1133    const UNKNOWN_CODE: Address = Address::repeat_byte(0xc7);
1134    /// Stores the timestamp in slot 0.
1135    const TIMESTAMP_READER: Address = Address::repeat_byte(0xc8);
1136    /// Stores the gas limit in slot 0.
1137    const GAS_LIMIT_READER: Address = Address::repeat_byte(0xc9);
1138    /// Stores the beneficiary in slot 0.
1139    const BENEFICIARY_READER: Address = Address::repeat_byte(0xca);
1140    /// Calls [`POOL_BENEFICIARY`].
1141    const POOL_BENEFICIARY_CALLER: Address = Address::repeat_byte(0xcb);
1142    /// Reads the balance of [`BENEFICIARY`] by its address.
1143    const BENEFICIARY_BALANCE_BY_ADDRESS: Address = Address::repeat_byte(0xcc);
1144    /// Stores the prevrandao in slot 0.
1145    const PREVRANDAO_READER: Address = Address::repeat_byte(0xcd);
1146    /// Has the largest balance.
1147    const SATURATED: Address = Address::repeat_byte(0xce);
1148    /// Index of a sender with the largest nonce.
1149    const EXHAUSTED_SENDER: u8 = 5;
1150    /// Selfdestructs to the noop contract.
1151    const SELFDESTRUCTER: Address = Address::repeat_byte(0xcf);
1152    /// Exists and is empty.
1153    const EMPTY: Address = Address::repeat_byte(0xd0);
1154    const GAS_PRICE: u128 = 2;
1155
1156    type Results = PrewarmResults<BaseEvmTypes>;
1157
1158    fn evm_env(prewarm: bool) -> EthEvmEnv {
1159        let mut env = EthEvmEnv::new(
1160            SpecId::CANCUN,
1161            evm2::env::BlockEnv::<BaseEvmTypes> {
1162                number: U256::from(1),
1163                beneficiary: BENEFICIARY,
1164                basefee: U256::ONE,
1165                gas_limit: U256::from(30_000_000),
1166                ..Default::default()
1167            },
1168            1,
1169        );
1170        if prewarm {
1171            env.version.features.remove(EvmFeatures::NONCE_CHECK | EvmFeatures::BALANCE_CHECK);
1172        }
1173        env
1174    }
1175
1176    fn sender(i: u8) -> Address {
1177        Address::repeat_byte(i)
1178    }
1179
1180    fn tx(from: u8, nonce: u64, to: Address, value: u64) -> Recovered<TransactionSigned> {
1181        tx_with_gas_limit(from, nonce, to, value, 100_000)
1182    }
1183
1184    fn tx_with_gas_limit(
1185        from: u8,
1186        nonce: u64,
1187        to: Address,
1188        value: u64,
1189        gas_limit: u64,
1190    ) -> Recovered<TransactionSigned> {
1191        tx_with_gas_price(from, nonce, to, value, gas_limit, GAS_PRICE)
1192    }
1193
1194    fn tx_with_gas_price(
1195        from: u8,
1196        nonce: u64,
1197        to: Address,
1198        value: u64,
1199        gas_limit: u64,
1200        gas_price: u128,
1201    ) -> Recovered<TransactionSigned> {
1202        let tx = Transaction::Legacy(TxLegacy {
1203            chain_id: Some(1),
1204            nonce,
1205            gas_price,
1206            gas_limit,
1207            to: TxKind::Call(to),
1208            value: U256::from(value),
1209            input: Bytes::new(),
1210        });
1211        Recovered::new_unchecked(
1212            TransactionSigned::new_unhashed(tx, Signature::test_signature()),
1213            sender(from),
1214        )
1215    }
1216
1217    fn parent_state() -> CacheDB<EmptyDB> {
1218        let mut db = CacheDB::new(EmptyDB::default());
1219        // The exhausted sender is funded separately.
1220        for i in [1, 2, 3, 4, 6, 7] {
1221            db.insert_account_info(
1222                &sender(i),
1223                AccountInfo { balance: U256::from(10u64.pow(18)), ..Default::default() },
1224            );
1225        }
1226        db.insert_account_info(
1227            &sender(EXHAUSTED_SENDER),
1228            AccountInfo {
1229                balance: U256::from(10u64.pow(18)),
1230                nonce: u64::MAX,
1231                ..Default::default()
1232            },
1233        );
1234        db.insert_account_info(
1235            &BENEFICIARY,
1236            AccountInfo { balance: U256::from(1), ..Default::default() },
1237        );
1238        db.insert_account_info(
1239            &RICH,
1240            AccountInfo { balance: U256::MAX >> 1, ..Default::default() },
1241        );
1242        db.insert_account_info(
1243            &SATURATED,
1244            AccountInfo { balance: U256::MAX, ..Default::default() },
1245        );
1246        db.insert_account_info(
1247            &sender(1).create(0),
1248            AccountInfo { balance: U256::from(12), ..Default::default() },
1249        );
1250        db.insert_account_info(&ZERO_BALANCE, AccountInfo { nonce: 1, ..Default::default() });
1251        db.insert_account_info(&EMPTY, AccountInfo::default());
1252        db.insert_account_info(
1253            &UNKNOWN_CODE,
1254            AccountInfo { code_hash: B256::repeat_byte(0xab), code: None, ..Default::default() },
1255        );
1256        for (address, code) in [
1257            (NOOP, bytes!("00")),
1258            (SELFDESTRUCTER, bytes!("73c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0ff")),
1259            (COUNTER, bytes!("5f546001015f5500")),
1260            (BENEFICIARY_BALANCE_READER, bytes!("41315f5500")),
1261            (SELF_BALANCE_READER, bytes!("475f5260205fa000")),
1262            (FORWARDER, bytes!("5f5f5f5f600573c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c05af100")),
1263            (TIMESTAMP_READER, bytes!("425f5500")),
1264            (GAS_LIMIT_READER, bytes!("455f5500")),
1265            (BENEFICIARY_READER, bytes!("415f5500")),
1266            (
1267                POOL_BENEFICIARY_CALLER,
1268                bytes!("5f5f5f5f5f7300000000000000000000000000000000000beef05af100"),
1269            ),
1270            (
1271                BENEFICIARY_BALANCE_BY_ADDRESS,
1272                bytes!("73bebebebebebebebebebebebebebebebebebebebe3100"),
1273            ),
1274            (PREVRANDAO_READER, bytes!("445f5500")),
1275        ] {
1276            let code = Bytecode::new_raw(code);
1277            db.insert_account_info(
1278                &address,
1279                AccountInfo {
1280                    balance: U256::from(12),
1281                    code_hash: code.hash_slow(),
1282                    code: Some(code),
1283                    ..Default::default()
1284                },
1285            );
1286        }
1287        db
1288    }
1289
1290    /// Speculative execution of `txs`, as by prewarm workers.
1291    struct Prewarm<'a> {
1292        txs: &'a [Recovered<TransactionSigned>],
1293        results: Results,
1294        evm: EvmFor<'static, EthEvmConfig>,
1295        recording: RecordingHandle,
1296    }
1297
1298    impl<'a> Prewarm<'a> {
1299        /// Executes the transactions at the indices in `order`, then refreshes stale results
1300        /// among them in block order.
1301        fn new(txs: &'a [Recovered<TransactionSigned>], order: &[usize]) -> Self {
1302            let recording = RecordingHandle::default();
1303            let evm = EthEvmConfig::mainnet()
1304                .evm_with_env(RecordingDb::new(parent_state(), recording.clone()), evm_env(true));
1305            let mut prewarm = Self { txs, results: Results::new(txs.len()), evm, recording };
1306            for &index in order {
1307                prewarm.run(index);
1308            }
1309            let mut refresh = order.to_vec();
1310            refresh.sort_unstable();
1311            for index in refresh {
1312                if prewarm.results.needs_refresh(index) {
1313                    prewarm.run(index);
1314                }
1315            }
1316            prewarm
1317        }
1318
1319        fn run(&mut self, index: usize) {
1320            let tx = &self.txs[index];
1321            let tx_env = EthEvmConfig::mainnet().tx_env(tx.clone());
1322            let speculative = SpeculativeTx::new(tx.signer(), tx.inner());
1323            drop(self.evm.take_state_cache());
1324            self.recording.start(Some((Arc::clone(self.results.predicted()), index)));
1325            let result = Evm::transact_with_inspector(
1326                &mut self.evm,
1327                &tx_env,
1328                BalanceTracker::new(self.recording.clone()),
1329            );
1330            let reads = self.recording.take_reads().unwrap();
1331            match result {
1332                Ok((mut balances, result)) => {
1333                    self.results.store(index, result, reads, &mut balances, speculative)
1334                }
1335                Err(_) => self.results.reject(index, reads),
1336            }
1337        }
1338
1339        /// Refreshes stale or missing results of transactions after `index`.
1340        fn refresh_after(&mut self, index: usize) {
1341            for index in index + 1..self.txs.len() {
1342                if self.results.needs_refresh(index) {
1343                    self.run(index);
1344                }
1345            }
1346        }
1347    }
1348
1349    /// Executes `txs` sequentially, committing valid prewarm results instead of executing.
1350    ///
1351    /// If `publish` is set, prewarm results are refreshed against the writes of executed
1352    /// transactions.
1353    fn execute(
1354        txs: &[Recovered<TransactionSigned>],
1355        mut prewarm: Option<&mut Prewarm<'_>>,
1356        publish: bool,
1357        beneficiary: Address,
1358    ) -> Execution {
1359        let config = EthEvmConfig::mainnet();
1360        let mut env = evm_env(false);
1361        env.block.beneficiary = beneficiary;
1362        let evm = config.evm_with_env(parent_state(), env);
1363        let ctx = EthBlockExecutionCtx {
1364            parent_hash: B256::ZERO,
1365            parent_beacon_block_root: None,
1366            ommers: &[],
1367            withdrawals: None,
1368            extra_data: Bytes::new(),
1369            tx_count_hint: None,
1370            slot_number: None,
1371        };
1372        let mut executor = config.block_executor_factory().create_executor(evm, ctx);
1373        let mut outcomes = Vec::new();
1374        let mut changes = Vec::new();
1375        for (index, tx) in txs.iter().enumerate() {
1376            let outcome = if let Some(prewarm) = prewarm.as_deref_mut() {
1377                prewarm.results.take_valid(index, executor.evm_mut().state_db_mut()).unwrap()
1378            } else {
1379                Err(ReuseMiss::Missing)
1380            };
1381            match outcome {
1382                Ok(result) => {
1383                    changes.push(changed_accounts(&result.pending_state));
1384                    executor
1385                        .commit_transaction(config.prewarm_tx_result(tx.inner(), result).unwrap())
1386                        .unwrap();
1387                    outcomes.push(Ok(()));
1388                }
1389                Err(miss) => {
1390                    let result = executor.execute_transaction_without_commit(tx.clone()).unwrap();
1391                    changes.push(changed_accounts(&result.result().pending_state));
1392                    if let Some(prewarm) = prewarm.as_deref_mut() &&
1393                        publish
1394                    {
1395                        prewarm.results.publish_executed(index, &result.result().pending_state);
1396                    }
1397                    executor.commit_transaction(result).unwrap();
1398                    if let Some(prewarm) = prewarm.as_deref_mut() &&
1399                        publish
1400                    {
1401                        prewarm.refresh_after(index);
1402                    }
1403                    outcomes.push(Err(miss));
1404                }
1405            }
1406        }
1407        let output = executor.finish().unwrap();
1408        Execution { receipts: output.result.receipts, bundle: output.state, changes, outcomes }
1409    }
1410
1411    /// Output of [`execute`].
1412    struct Execution {
1413        receipts: Vec<Receipt>,
1414        bundle: BundleState,
1415        /// Accounts each transaction changed, as the state root task sees them.
1416        changes: Vec<Vec<(Address, AccountInfo)>>,
1417        outcomes: Vec<Result<(), ReuseMiss>>,
1418    }
1419
1420    /// Returns the accounts in `state` whose info differs from their original info, which the
1421    /// state root task streams as updates.
1422    fn changed_accounts(state: &PendingState) -> Vec<(Address, AccountInfo)> {
1423        let mut changed = state
1424            .account_changes()
1425            .filter(|account| account.is_info_changed())
1426            .filter_map(|account| account.current.map(|info| (account.address, without_code(info))))
1427            .collect::<Vec<_>>();
1428        changed.sort_unstable_by_key(|(address, _)| *address);
1429        changed
1430    }
1431
1432    /// Database that fails every read.
1433    struct FailingDb;
1434
1435    impl DynDatabase for FailingDb {
1436        fn get_account(&mut self, _: &Address) -> DbResult<Option<AccountInfo>> {
1437            Err(evm2::DatabaseError::new(ProviderError::BestBlockNotFound, true))
1438        }
1439        fn get_code_by_hash(&mut self, _: &B256) -> DbResult<Bytecode> {
1440            Err(evm2::DatabaseError::new(ProviderError::BestBlockNotFound, true))
1441        }
1442        fn get_storage(&mut self, _: &Address, _: &U256) -> DbResult<U256> {
1443            Err(evm2::DatabaseError::new(ProviderError::BestBlockNotFound, true))
1444        }
1445        fn get_block_hash(&mut self, _: &U256) -> DbResult<B256> {
1446            Err(evm2::DatabaseError::new(ProviderError::BestBlockNotFound, true))
1447        }
1448    }
1449
1450    /// Returns whether the prewarm result of the first transaction can be reused, for
1451    /// transactions that block execution would reject.
1452    fn reusable(txs: &[Recovered<TransactionSigned>]) -> Result<(), ReuseMiss> {
1453        let prewarm = Prewarm::new(txs, &[0]);
1454        let mut state = parent_state();
1455        prewarm.results.take_valid(0, &mut state).unwrap().map(drop)
1456    }
1457
1458    /// Asserts that reusing prewarm results produces the same output as executing every
1459    /// transaction, and returns the reuse outcomes.
1460    fn reuse(txs: &[Recovered<TransactionSigned>]) -> Vec<Result<(), ReuseMiss>> {
1461        reuse_in(txs, &(0..txs.len()).collect::<Vec<_>>(), true)
1462    }
1463
1464    /// Like [`reuse`], prewarming only the transactions at the indices in `order`, and refreshing
1465    /// results against the writes of executed transactions if `publish` is set.
1466    fn reuse_in(
1467        txs: &[Recovered<TransactionSigned>],
1468        order: &[usize],
1469        publish: bool,
1470    ) -> Vec<Result<(), ReuseMiss>> {
1471        let reused = execute(txs, Some(&mut Prewarm::new(txs, order)), publish, BENEFICIARY);
1472        let expected = execute(txs, None, false, BENEFICIARY);
1473        assert_eq!(reused.receipts, expected.receipts);
1474        assert_eq!(reused.bundle, expected.bundle);
1475        assert_eq!(reused.changes, expected.changes);
1476        reused.outcomes
1477    }
1478
1479    /// Executes `txs` as pool transactions on top of the parent state, as by the txpool prewarm
1480    /// worker, in a block environment that differs from the actual one in the timestamp and
1481    /// prevrandao.
1482    fn pool_results(txs: &[Recovered<TransactionSigned>]) -> PoolResults<BaseEvmTypes> {
1483        let mut env = evm_env(true);
1484        env.block.beneficiary = POOL_BENEFICIARY;
1485        env.block.timestamp = U256::from(12);
1486        env.block.prevrandao = U256::from_be_bytes([1; 32]);
1487        let recording = RecordingHandle::default();
1488        let mut evm = EthEvmConfig::mainnet()
1489            .evm_with_env(RecordingDb::new(parent_state(), recording.clone()), env);
1490        let results = PoolResults::default();
1491        for tx in txs {
1492            let tx_env = EthEvmConfig::mainnet().tx_env(tx.clone());
1493            let speculative = SpeculativeTx::new(tx.signer(), tx.inner());
1494            drop(evm.take_state_cache());
1495            recording.start_recording_inner();
1496            let (mut balances, result) = Evm::transact_with_inspector(
1497                &mut evm,
1498                &tx_env,
1499                BalanceTracker::new(recording.clone()),
1500            )
1501            .unwrap();
1502            let reads = recording.take_reads().unwrap();
1503            results.store(*tx.tx_hash(), result, reads, &mut balances, speculative);
1504        }
1505        results
1506    }
1507
1508    /// Asserts that reusing results of the `pool` transactions produces the same output as
1509    /// executing every transaction in a block with `beneficiary`, and returns the reuse outcomes.
1510    fn reuse_pool(
1511        txs: &[Recovered<TransactionSigned>],
1512        pool: &[Recovered<TransactionSigned>],
1513        beneficiary: Address,
1514    ) -> Vec<Result<(), ReuseMiss>> {
1515        let differs = BlockEnvFields { timestamp: true, prevrandao: true, ..Default::default() };
1516        reuse_pool_with(txs, pool, beneficiary, differs)
1517    }
1518
1519    /// Like [`reuse_pool`], for a block environment that differs from the predicted one in
1520    /// `differs`.
1521    fn reuse_pool_with(
1522        txs: &[Recovered<TransactionSigned>],
1523        pool: &[Recovered<TransactionSigned>],
1524        beneficiary: Address,
1525        differs: BlockEnvFields,
1526    ) -> Vec<Result<(), ReuseMiss>> {
1527        let seeds = PoolSeeds::new(Arc::new(pool_results(pool)), beneficiary, differs);
1528        let mut prewarm = Prewarm::new(txs, &[]);
1529        for (index, tx) in txs.iter().enumerate() {
1530            prewarm.results.seed(index, tx.tx_hash(), &seeds);
1531        }
1532        let reused = execute(txs, Some(&mut prewarm), false, beneficiary);
1533        let expected = execute(txs, None, false, beneficiary);
1534        assert_eq!(reused.receipts, expected.receipts);
1535        assert_eq!(reused.bundle, expected.bundle);
1536        assert_eq!(reused.changes, expected.changes);
1537        reused.outcomes
1538    }
1539
1540    #[reth_concurrency::test]
1541    fn reuses_independent_transactions() {
1542        let txs = [tx(1, 0, sender(2), 1), tx(3, 0, Address::repeat_byte(0xaa), 1)];
1543        assert_eq!(reuse(&txs), [Ok(()), Ok(())]);
1544    }
1545
1546    #[reth_concurrency::test]
1547    fn rebases_unobserved_balances() {
1548        // The last transaction's caller and recipient were credited by earlier ones.
1549        let txs = [tx(1, 0, NOOP, 1), tx(1, 1, sender(2), 1), tx(2, 0, NOOP, 1)];
1550        assert_eq!(reuse(&txs), [Ok(()), Ok(()), Ok(())]);
1551    }
1552
1553    #[reth_concurrency::test]
1554    fn reuses_predicted_writes() {
1555        let txs = [tx(1, 0, COUNTER, 1), tx(2, 0, COUNTER, 1), tx(1, 1, COUNTER, 1)];
1556        assert_eq!(reuse(&txs), [Ok(()), Ok(()), Ok(())]);
1557        // Results executed before the transactions they depend on are executed again.
1558        assert_eq!(reuse_in(&txs, &[2, 1, 0], true), [Ok(()), Ok(()), Ok(())]);
1559    }
1560
1561    #[reth_concurrency::test]
1562    fn refreshes_against_executed_writes() {
1563        let txs = [tx(1, 0, COUNTER, 1), tx(2, 0, COUNTER, 1), tx(1, 1, sender(3), 1)];
1564        assert_eq!(reuse_in(&txs, &[1, 2], true), [Err(ReuseMiss::Missing), Ok(()), Ok(())]);
1565    }
1566
1567    #[reth_concurrency::test]
1568    fn rebases_original_balances() {
1569        // The first transaction leaves the forwarder 5 wei more, and the second forwards 5 wei, so
1570        // its rebased balance equals its speculative balance before the second transaction.
1571        let txs = [tx(1, 0, FORWARDER, 10), tx(2, 0, FORWARDER, 0)];
1572        assert_eq!(reuse_in(&txs, &[1], false), [Err(ReuseMiss::Missing), Ok(())]);
1573    }
1574
1575    #[reth_concurrency::test]
1576    fn rejects_stale_storage() {
1577        let txs = [tx(1, 0, COUNTER, 1), tx(2, 0, COUNTER, 1)];
1578        assert_eq!(reuse_in(&txs, &[1], false), [Err(ReuseMiss::Missing), Err(ReuseMiss::Stale)]);
1579    }
1580
1581    #[reth_concurrency::test]
1582    fn rejects_stale_callers() {
1583        let txs = [tx(1, 0, sender(2), 1), tx(1, 1, sender(3), 1)];
1584        assert_eq!(reuse_in(&txs, &[1], false), [Err(ReuseMiss::Missing), Err(ReuseMiss::Stale)]);
1585    }
1586
1587    #[reth_concurrency::test]
1588    fn rejects_observed_balances() {
1589        let txs = [
1590            tx(1, 0, SELF_BALANCE_READER, 1),
1591            tx(2, 0, SELF_BALANCE_READER, 1),
1592            tx(3, 0, BENEFICIARY_BALANCE_READER, 1),
1593        ];
1594        assert_eq!(
1595            reuse_in(&txs, &[1, 2], false),
1596            [Err(ReuseMiss::Missing), Err(ReuseMiss::Stale), Err(ReuseMiss::Stale)]
1597        );
1598    }
1599
1600    #[reth_concurrency::test]
1601    fn rejects_lower_sender_balances() {
1602        let txs = [tx(1, 0, FORWARDER, 0), tx(2, 0, FORWARDER, 0), tx(3, 0, FORWARDER, 0)];
1603        // The forwarder can send twice from its speculative balance, but not three times.
1604        assert_eq!(
1605            reuse_in(&txs, &[1, 2], false),
1606            [Err(ReuseMiss::Missing), Ok(()), Err(ReuseMiss::Stale)]
1607        );
1608    }
1609
1610    #[reth_concurrency::test]
1611    fn reuses_pool_results() {
1612        // The last transaction's caller was credited by the first one.
1613        let txs = [tx(1, 0, sender(2), 1), tx(3, 0, COUNTER, 1), tx(2, 0, GAS_LIMIT_READER, 1)];
1614        assert_eq!(reuse_pool(&txs, &txs, BENEFICIARY), [Ok(()), Ok(()), Ok(())]);
1615        // Transactions missing from the pool are executed.
1616        assert_eq!(
1617            reuse_pool(&txs, &txs[1..], BENEFICIARY),
1618            [Err(ReuseMiss::Missing), Ok(()), Ok(())]
1619        );
1620    }
1621
1622    #[reth_concurrency::test]
1623    fn rejects_stale_pool_results() {
1624        // Test transactions are hashed without their sender.
1625        let txs = [tx(1, 0, COUNTER, 1), tx(2, 0, COUNTER, 2)];
1626        assert_eq!(reuse_pool(&txs, &txs, BENEFICIARY), [Ok(()), Err(ReuseMiss::Stale)]);
1627        // The beneficiary must exist to be credited.
1628        let missing = Address::repeat_byte(0xbf);
1629        assert_eq!(reuse_pool(&txs, &txs, missing), [Err(ReuseMiss::Stale), Err(ReuseMiss::Stale)]);
1630    }
1631
1632    #[reth_concurrency::test]
1633    fn rejects_zero_credit_to_empty_beneficiary() {
1634        // Executing the credit deletes the empty beneficiary, which detached state cannot express.
1635        let txs = [tx_with_gas_price(1, 0, COUNTER, 1, 100_000, 1)];
1636        assert_eq!(reuse_pool(&txs, &txs, EMPTY), [Err(ReuseMiss::Stale)]);
1637    }
1638
1639    #[reth_concurrency::test]
1640    fn rejects_pool_results_observing_block_env() {
1641        let txs = [
1642            tx(1, 0, TIMESTAMP_READER, 1),
1643            tx(2, 0, BENEFICIARY_READER, 1),
1644            tx(3, 0, POOL_BENEFICIARY, 1),
1645            tx(4, 0, POOL_BENEFICIARY_CALLER, 1),
1646            tx(6, 0, BENEFICIARY, 1),
1647            tx(7, 0, PREVRANDAO_READER, 1),
1648        ];
1649        assert_eq!(reuse_pool(&txs, &txs, BENEFICIARY), [Err(ReuseMiss::Missing); 6]);
1650
1651        let txs = [tx(1, 0, GAS_LIMIT_READER, 1)];
1652        let differs = BlockEnvFields { gas_limit: true, ..Default::default() };
1653        assert_eq!(reuse_pool_with(&txs, &txs, BENEFICIARY, differs), [Err(ReuseMiss::Missing)]);
1654    }
1655
1656    #[reth_concurrency::test]
1657    fn seeds_only_unexecuted_transactions() {
1658        let txs = [tx(1, 0, COUNTER, 1)];
1659        let differs = BlockEnvFields::default();
1660        let seeds = PoolSeeds::new(Arc::new(pool_results(&txs)), BENEFICIARY, differs);
1661        assert!(Prewarm::new(&txs, &[]).results.seed(0, txs[0].tx_hash(), &seeds).is_some());
1662        assert!(Prewarm::new(&txs, &[0]).results.seed(0, txs[0].tx_hash(), &seeds).is_none());
1663    }
1664
1665    #[reth_concurrency::test]
1666    fn rejects_pool_results_overflowing_the_beneficiary() {
1667        let txs = [tx(1, 0, COUNTER, 1)];
1668        assert_eq!(reuse_pool(&txs, &txs, SATURATED), [Err(ReuseMiss::Stale)]);
1669    }
1670
1671    /// Stores the recorded result of `tx` in `results` again under `hash`, after `modify` changed
1672    /// it and the read of the pool beneficiary.
1673    fn store_again(
1674        results: &PoolResults<BaseEvmTypes>,
1675        tx: &Recovered<TransactionSigned>,
1676        hash: B256,
1677        modify: impl FnOnce(&mut TxResultWithState<BaseEvmTypes>, &mut AccountRead),
1678    ) -> bool {
1679        let recorded = results.get(tx.tx_hash()).unwrap();
1680        let mut result = recorded.result.clone();
1681        result.pending_state.insert_account(POOL_BENEFICIARY, None, Some(AccountInfo::default()));
1682        let mut beneficiary = AccountRead {
1683            address: POOL_BENEFICIARY,
1684            info: None,
1685            balance: BalanceDependency::None,
1686            predicted: false,
1687        };
1688        modify(&mut result, &mut beneficiary);
1689        let mut reads = recorded.reads.clone();
1690        reads.accounts.push(beneficiary);
1691        let speculative = SpeculativeTx::new(tx.signer(), tx.inner());
1692        results.store(hash, result, reads, &mut BalanceTracker::default(), speculative)
1693    }
1694
1695    #[reth_concurrency::test]
1696    fn bounds_pool_results() {
1697        let txs = [tx(1, 0, COUNTER, 1)];
1698        let results = pool_results(&txs);
1699        assert!(store_again(&results, &txs[0], B256::ZERO, |_, _| {}));
1700        // Deployed code counts towards the bound.
1701        assert!(!store_again(&results, &txs[0], B256::with_last_byte(1), |result, _| {
1702            let original = result.pending_state.account_info(&COUNTER).unwrap().clone();
1703            let current = original
1704                .clone()
1705                .with_code(Bytecode::new_raw(vec![0; MAX_POOL_RESULT_BYTES].into()));
1706            result.pending_state.insert_account(COUNTER, Some(original), Some(current));
1707        }));
1708    }
1709
1710    #[reth_concurrency::test]
1711    fn rejects_recorded_pool_hashes() {
1712        let txs = [tx(1, 0, COUNTER, 1)];
1713        let results = pool_results(&txs);
1714        assert!(!store_again(&results, &txs[0], *txs[0].tx_hash(), |_, _| {}));
1715        assert!(store_again(&results, &txs[0], B256::ZERO, |_, _| {}));
1716    }
1717
1718    #[reth_concurrency::test]
1719    fn rejects_saturated_pool_beneficiaries() {
1720        let txs = [tx(1, 0, COUNTER, 1)];
1721        let results = pool_results(&txs);
1722        // Crediting a saturated balance leaves it unchanged.
1723        assert!(!store_again(&results, &txs[0], B256::ZERO, |result, beneficiary| {
1724            beneficiary.info = Some(AccountInfo { balance: U256::MAX, ..Default::default() });
1725            result.pending_state.insert_account(POOL_BENEFICIARY, None, beneficiary.info.clone());
1726        }));
1727        assert!(store_again(&results, &txs[0], B256::ZERO, |_, _| {}));
1728    }
1729
1730    #[reth_concurrency::test]
1731    fn rejects_pool_results_running_out_of_gas() {
1732        // Enough gas to read the balance of the warm beneficiary in the block, but not of the cold
1733        // one during speculation.
1734        let txs = [tx_with_gas_limit(1, 0, BENEFICIARY_BALANCE_BY_ADDRESS, 0, 21_500)];
1735        assert_eq!(reuse_pool(&txs, &txs, BENEFICIARY), [Err(ReuseMiss::Missing)]);
1736    }
1737
1738    #[reth_concurrency::test]
1739    fn rejects_invalid_transactions() {
1740        assert_eq!(reusable(&[tx(1, 0, NOOP, 0)]), Ok(()));
1741        // The caller cannot pay for the value.
1742        assert_eq!(reusable(&[tx(1, 0, NOOP, 10u64.pow(19))]), Err(ReuseMiss::Stale));
1743        // The caller's nonce differs.
1744        assert_eq!(reusable(&[tx(1, 1, NOOP, 0)]), Err(ReuseMiss::Stale));
1745        // The caller's nonce cannot be incremented.
1746        assert_eq!(reusable(&[tx(EXHAUSTED_SENDER, u64::MAX, NOOP, 0)]), Err(ReuseMiss::Stale));
1747        // Speculative execution fails.
1748        assert_eq!(
1749            reusable(&[tx_with_gas_limit(1, 0, NOOP, 0, 40_000_000)]),
1750            Err(ReuseMiss::Stale)
1751        );
1752        // The most the caller may spend overflows, though the effective fee does not.
1753        let overflowing = Transaction::Eip1559(TxEip1559 {
1754            chain_id: 1,
1755            max_fee_per_gas: u128::MAX,
1756            gas_limit: 100_000,
1757            to: TxKind::Call(NOOP),
1758            ..Default::default()
1759        });
1760        let overflowing = Recovered::new_unchecked(
1761            TransactionSigned::new_unhashed(overflowing, Signature::test_signature()),
1762            sender(1),
1763        );
1764        assert_eq!(reusable(&[overflowing]), Err(ReuseMiss::Stale));
1765    }
1766
1767    #[reth_concurrency::test]
1768    fn keeps_stale_results_unchanged() {
1769        let txs = [tx(1, 0, NOOP, 0)];
1770        let prewarm = Prewarm::new(&txs, &[0]);
1771        // The caller's balance can be rebased, but the callee changed.
1772        let mut db = parent_state();
1773        db.insert_account_info(
1774            &sender(1),
1775            AccountInfo { balance: U256::from(2 * 10u64.pow(18)), ..Default::default() },
1776        );
1777        let mut noop = DynDatabase::get_account(&mut db, &NOOP).unwrap().unwrap();
1778        noop.nonce = 1;
1779        db.insert_account_info(&NOOP, noop);
1780        let mut stale = db;
1781        assert_eq!(
1782            prewarm.results.take_valid(0, &mut stale).unwrap().map(drop),
1783            Err(ReuseMiss::Stale)
1784        );
1785
1786        let mut state = parent_state();
1787        let result = prewarm.results.take_valid(0, &mut state).unwrap().unwrap();
1788        let fee = U256::from(21_000 * GAS_PRICE);
1789        assert_eq!(
1790            result.pending_state.account_info(&sender(1)).unwrap().balance,
1791            U256::from(10u64.pow(18)) - fee
1792        );
1793    }
1794
1795    #[reth_concurrency::test]
1796    fn keeps_results_on_database_errors() {
1797        let txs = [tx(1, 0, NOOP, 0)];
1798        let prewarm = Prewarm::new(&txs, &[0]);
1799        assert!(matches!(
1800            prewarm.results.take_valid(0, &mut FailingDb),
1801            Err(err) if err.to_string() == ProviderError::BestBlockNotFound.to_string()
1802        ));
1803        let mut state = parent_state();
1804        assert_eq!(prewarm.results.take_valid(0, &mut state).unwrap().map(drop), Ok(()));
1805    }
1806
1807    #[reth_concurrency::test]
1808    fn rejects_unknown_code() {
1809        assert_eq!(reuse_in(&[tx(1, 0, UNKNOWN_CODE, 0)], &[0], false), [Err(ReuseMiss::Stale)]);
1810    }
1811
1812    #[reth_concurrency::test]
1813    fn rejects_rebasing_unbounded_or_zero_balances() {
1814        let rebased = [tx(1, 0, sender(4), 1), tx(2, 0, sender(4), 1)];
1815        assert_eq!(reuse_in(&rebased, &[1], false), [Err(ReuseMiss::Missing), Ok(())]);
1816        for txs in [
1817            [tx(1, 0, RICH, 1), tx(2, 0, RICH, 1)],
1818            [tx(1, 0, ZERO_BALANCE, 1), tx(2, 0, ZERO_BALANCE, 1)],
1819            // Any unbounded balance read makes every balance exact.
1820            [tx(1, 0, sender(4), 1), tx(4, 0, RICH, 1)],
1821        ] {
1822            assert_eq!(
1823                reuse_in(&txs, &[1], false),
1824                [Err(ReuseMiss::Missing), Err(ReuseMiss::Stale)]
1825            );
1826        }
1827    }
1828
1829    #[reth_concurrency::test]
1830    fn preserves_account_lifecycle_and_rejects_rebasing_it() {
1831        let creation = Recovered::new_unchecked(
1832            TransactionSigned::new_unhashed(
1833                Transaction::Legacy(TxLegacy {
1834                    chain_id: Some(1),
1835                    gas_price: GAS_PRICE,
1836                    gas_limit: 100_000,
1837                    to: TxKind::Create,
1838                    input: bytes!("60015f5500"),
1839                    ..Default::default()
1840                }),
1841                Signature::test_signature(),
1842            ),
1843            sender(1),
1844        );
1845        for (transaction, address) in
1846            [(creation, sender(1).create(0)), (tx(1, 0, SELFDESTRUCTER, 0), SELFDESTRUCTER)]
1847        {
1848            let txs = [transaction];
1849            assert_eq!(reuse(&txs), [Ok(())]);
1850            let prewarm = Prewarm::new(&txs, &[0]);
1851            // An observed SELFDESTRUCT balance is exact; creation also cannot have its
1852            // lifecycle flags reset by metadata replacement during rebasing.
1853            let mut db = parent_state();
1854            let mut info = DynDatabase::get_account(&mut db, &address).unwrap().unwrap();
1855            info.balance += U256::ONE;
1856            db.insert_account_info(&address, info);
1857            assert_eq!(
1858                prewarm.results.take_valid(0, &mut db).unwrap().map(drop),
1859                Err(ReuseMiss::Stale)
1860            );
1861            let result = prewarm.results.take_valid(0, &mut parent_state()).unwrap().unwrap();
1862            let account =
1863                result.pending_state.account_changes().find(|a| a.address == address).unwrap();
1864            if address == sender(1).create(0) {
1865                assert!(account.created);
1866                assert_eq!(account.storage.slots[&U256::ZERO].value.current, U256::ONE);
1867            } else {
1868                // EIP-6780 retains pre-existing contracts after SELFDESTRUCT.
1869                assert_eq!(account.current.unwrap().balance, U256::ZERO);
1870            }
1871        }
1872    }
1873
1874    #[reth_concurrency::test]
1875    fn rejects_results_after_failed_observer_reads() {
1876        let reads = ReadSet {
1877            accounts: vec![AccountRead {
1878                address: sender(1),
1879                info: Some(AccountInfo {
1880                    balance: U256::from(10u64.pow(18)),
1881                    ..Default::default()
1882                }),
1883                balance: BalanceDependency::None,
1884                predicted: false,
1885            }],
1886            ..Default::default()
1887        };
1888        let mut balances = BalanceTracker { read_failed: true, ..Default::default() };
1889        let tx = tx(1, 0, NOOP, 0);
1890        assert!(reads.finish(&mut balances, SpeculativeTx::new(tx.signer(), tx.inner())).is_err());
1891    }
1892}