Skip to main content

reth_rpc_eth_types/cache/
mod.rs

1//! Async caching support for eth RPC
2
3use super::{EthStateCacheConfig, MultiConsumerLruCache};
4use crate::block::CachedTransaction;
5use alloy_consensus::transaction::TxHashRef;
6use alloy_eip7928::{bal::DecodedBal, StorageChange};
7use alloy_eips::BlockHashOrNumber;
8use alloy_primitives::{map::FbBuildHasher, Address, Bytes, TxHash, B256, U256};
9use evm2::{
10    bytecode::Bytecode,
11    evm::{
12        AccountBal as EvmAccountBal, AccountInfoBal as EvmAccountInfoBal, Bal as EvmBal,
13        BalChange as EvmBalChange, BalChanges as EvmBalChanges, BalCodeChange as EvmBalCodeChange,
14        StorageBal as EvmStorageBal,
15    },
16};
17use futures::{Stream, StreamExt};
18use reth_chain_state::CanonStateNotification;
19use reth_errors::{ProviderError, ProviderResult};
20use reth_execution_types::{Chain, DecodedEvmBal};
21use reth_lru::LruMap;
22use reth_primitives_traits::{Block, BlockBody, InMemorySize, NodePrimitives, RecoveredBlock};
23use reth_storage_api::{BalProvider, BlockReader, TransactionVariant};
24use reth_tasks::Runtime;
25use std::{
26    cell::LazyCell,
27    collections::VecDeque,
28    future::Future,
29    pin::Pin,
30    sync::Arc,
31    task::{Context, Poll},
32    time::Duration,
33};
34use tokio::{
35    sync::{
36        mpsc::{unbounded_channel, UnboundedSender},
37        oneshot, OwnedSemaphorePermit, Semaphore,
38    },
39    time::{Instant, Interval, MissedTickBehavior},
40};
41use tokio_stream::wrappers::UnboundedReceiverStream;
42
43pub mod config;
44pub mod db;
45pub mod metrics;
46pub mod multi_consumer;
47
48/// The type that can send the response to a requested [`RecoveredBlock`]
49type BlockWithSendersResponseSender<B> =
50    oneshot::Sender<ProviderResult<Option<Arc<RecoveredBlock<B>>>>>;
51
52/// The type that can send the response to the requested receipts of a block.
53type ReceiptsResponseSender<R> = oneshot::Sender<ProviderResult<Option<Arc<Vec<R>>>>>;
54
55type CachedBlockResponseSender<B> = oneshot::Sender<Option<Arc<RecoveredBlock<B>>>>;
56
57type CachedBalResponseSender = oneshot::Sender<Option<CachedBal>>;
58
59type CachedBlockAndReceiptsResponseSender<B, R> =
60    oneshot::Sender<(Option<Arc<RecoveredBlock<B>>>, Option<Arc<Vec<R>>>)>;
61
62/// The type that can send the response for a transaction hash lookup
63type TransactionHashResponseSender<B, R> = oneshot::Sender<Option<CachedTransaction<B, R>>>;
64
65/// The type that can send the response to a requested evm2 BAL.
66type BalResponseSender = oneshot::Sender<ProviderResult<Option<CachedBal>>>;
67
68type BlockLruCache<B> = MultiConsumerLruCache<
69    B256,
70    Arc<RecoveredBlock<B>>,
71    BlockWithSendersResponseSender<B>,
72    FbBuildHasher<32>,
73>;
74
75type ReceiptsLruCache<R> =
76    MultiConsumerLruCache<B256, Arc<Vec<R>>, ReceiptsResponseSender<R>, FbBuildHasher<32>>;
77
78type BalLruCache = MultiConsumerLruCache<B256, CachedBal, BalResponseSender, FbBuildHasher<32>>;
79
80/// Provides async access to cached eth data
81///
82/// This is the frontend for the async caching service which manages cached data on a different
83/// task.
84#[derive(Debug)]
85pub struct EthStateCache<N: NodePrimitives> {
86    to_service: UnboundedSender<CacheAction<N::Block, N::Receipt>>,
87}
88
89impl<N: NodePrimitives> Clone for EthStateCache<N> {
90    fn clone(&self) -> Self {
91        Self { to_service: self.to_service.clone() }
92    }
93}
94
95impl<N: NodePrimitives> EthStateCache<N> {
96    /// Creates and returns both [`EthStateCache`] frontend and the memory bound service.
97    fn create<Provider>(
98        provider: Provider,
99        action_task_spawner: Runtime,
100        config: EthStateCacheConfig,
101    ) -> (Self, EthStateCacheService<Provider>)
102    where
103        Provider: BlockReader<Block = N::Block, Receipt = N::Receipt> + BalProvider,
104    {
105        let EthStateCacheConfig {
106            max_blocks,
107            max_receipts,
108            max_bals,
109            max_blocks_bytes,
110            max_receipts_bytes,
111            max_bals_bytes,
112            idle_timeout,
113            cache_computed_bals: _,
114            prewarm_bals: _,
115            max_concurrent_db_requests,
116            max_cached_tx_hashes,
117        } = config;
118        let eviction_interval = {
119            let _guard = action_task_spawner.handle().enter();
120            // Clamp short timeouts to avoid busy polling. Expiration is best effort between ticks.
121            let period = (idle_timeout / 4).clamp(Duration::from_secs(1), Duration::from_secs(60));
122            let mut interval = tokio::time::interval_at(Instant::now() + period, period);
123            interval.set_missed_tick_behavior(MissedTickBehavior::Skip);
124            interval
125        };
126        let (to_service, rx) = unbounded_channel();
127
128        let service = EthStateCacheService {
129            provider,
130            full_block_cache: BlockLruCache::new(max_blocks, max_blocks_bytes, "blocks"),
131            receipts_cache: ReceiptsLruCache::new(max_receipts, max_receipts_bytes, "receipts"),
132            bal_cache: BalLruCache::new(max_bals, max_bals_bytes, "bals"),
133            idle_timeout,
134            eviction_interval,
135            eviction_pending: false,
136            action_tx: to_service.clone(),
137            action_rx: UnboundedReceiverStream::new(rx),
138            action_task_spawner,
139            rate_limiter: Arc::new(Semaphore::new(max_concurrent_db_requests)),
140            pending_fetches: VecDeque::new(),
141            tx_hash_index: LruMap::with_hasher(max_cached_tx_hashes, Default::default()),
142        };
143        let cache = Self { to_service };
144        (cache, service)
145    }
146
147    /// Creates a new async LRU backed cache service task and spawns it to a new task via the given
148    /// spawner.
149    ///
150    /// Entry counts and estimated payload bytes bound the cache. Idle entries expire periodically.
151    pub fn spawn_with<Provider>(
152        provider: Provider,
153        config: EthStateCacheConfig,
154        executor: Runtime,
155    ) -> Self
156    where
157        Provider: BlockReader<Block = N::Block, Receipt = N::Receipt>
158            + BalProvider
159            + Clone
160            + Unpin
161            + 'static,
162    {
163        let (this, service) = Self::create(provider, executor.clone(), config);
164        executor.spawn_critical_task("eth state cache", service);
165        this
166    }
167
168    /// Requests the  [`RecoveredBlock`] for the block hash
169    ///
170    /// Returns `None` if the block does not exist.
171    pub async fn get_recovered_block(
172        &self,
173        block_hash: B256,
174    ) -> ProviderResult<Option<Arc<RecoveredBlock<N::Block>>>> {
175        let (response_tx, rx) = oneshot::channel();
176        let _ = self.to_service.send(CacheAction::GetBlockWithSenders { block_hash, response_tx });
177        rx.await.map_err(|_| CacheServiceUnavailable)?
178    }
179
180    /// Requests the block for the given block hash if it is cached.
181    pub async fn get_maybe_block(
182        &self,
183        block_hash: B256,
184    ) -> ProviderResult<Option<Arc<RecoveredBlock<N::Block>>>> {
185        let (response_tx, rx) = oneshot::channel();
186        let _ = self.to_service.send(CacheAction::GetCachedBlock { block_hash, response_tx });
187        rx.await.map_err(|_| CacheServiceUnavailable.into())
188    }
189
190    /// Requests the receipts for the block hash
191    ///
192    /// Returns `None` if the block was not found.
193    pub async fn get_receipts(
194        &self,
195        block_hash: B256,
196    ) -> ProviderResult<Option<Arc<Vec<N::Receipt>>>> {
197        let (response_tx, rx) = oneshot::channel();
198        let _ = self.to_service.send(CacheAction::GetReceipts { block_hash, response_tx });
199        rx.await.map_err(|_| CacheServiceUnavailable)?
200    }
201
202    /// Fetches both receipts and block for the given block hash.
203    pub async fn get_block_and_receipts(
204        &self,
205        block_hash: B256,
206    ) -> ProviderResult<Option<(Arc<RecoveredBlock<N::Block>>, Arc<Vec<N::Receipt>>)>> {
207        let block = self.get_recovered_block(block_hash);
208        let receipts = self.get_receipts(block_hash);
209
210        let (block, receipts) = futures::try_join!(block, receipts)?;
211
212        Ok(block.zip(receipts))
213    }
214
215    /// Retrieves the block and its BAL if the BAL is already cached.
216    ///
217    /// The block is fetched if it is not cached. Returns `None` if the block does not exist.
218    pub async fn get_recovered_block_and_maybe_bal(
219        &self,
220        block_hash: B256,
221    ) -> ProviderResult<Option<(Arc<RecoveredBlock<N::Block>>, Option<Arc<DecodedBal<Arc<EvmBal>>>>)>>
222    {
223        let (response_tx, rx) = oneshot::channel();
224        let _ = self.to_service.send(CacheAction::GetCachedBal { block_hash, response_tx });
225
226        let block = self.get_recovered_block(block_hash);
227        let (block, bal) = futures::join!(block, rx);
228
229        let bal = bal.map_err(|_| CacheServiceUnavailable)?.map(|cached| cached.0);
230        Ok(block?.map(|block| (block, bal)))
231    }
232
233    /// Retrieves receipts and blocks from cache if block is in the cache, otherwise only receipts.
234    pub async fn get_receipts_and_maybe_block(
235        &self,
236        block_hash: B256,
237    ) -> ProviderResult<Option<(Arc<Vec<N::Receipt>>, Option<Arc<RecoveredBlock<N::Block>>>)>> {
238        let (response_tx, rx) = oneshot::channel();
239        let _ = self.to_service.send(CacheAction::GetCachedBlock { block_hash, response_tx });
240
241        let receipts = self.get_receipts(block_hash);
242
243        let (receipts, block) = futures::join!(receipts, rx);
244
245        let block = block.map_err(|_| CacheServiceUnavailable)?;
246        Ok(receipts?.map(|r| (r, block)))
247    }
248
249    /// Retrieves both block and receipts from cache if available.
250    pub async fn maybe_cached_block_and_receipts(
251        &self,
252        block_hash: B256,
253    ) -> ProviderResult<(Option<Arc<RecoveredBlock<N::Block>>>, Option<Arc<Vec<N::Receipt>>>)> {
254        let (response_tx, rx) = oneshot::channel();
255        let _ = self
256            .to_service
257            .send(CacheAction::GetCachedBlockAndReceipts { block_hash, response_tx });
258        rx.await.map_err(|_| CacheServiceUnavailable.into())
259    }
260
261    /// Looks up a transaction by its hash in the cache index.
262    ///
263    /// Returns the cached block, transaction index, and optionally receipts if the transaction
264    /// is in a cached block.
265    pub async fn get_transaction_by_hash(
266        &self,
267        tx_hash: TxHash,
268    ) -> Option<CachedTransaction<N::Block, N::Receipt>> {
269        let (response_tx, rx) = oneshot::channel();
270        let _ = self.to_service.send(CacheAction::GetTransactionByHash { tx_hash, response_tx });
271        rx.await.ok()?
272    }
273
274    /// Requests the evm2 BAL for the block hash.
275    ///
276    /// Returns `None` if the BAL does not exist.
277    pub async fn get_bal(
278        &self,
279        block_hash: B256,
280    ) -> ProviderResult<Option<Arc<DecodedBal<Arc<EvmBal>>>>> {
281        let (response_tx, rx) = oneshot::channel();
282        let _ = self.to_service.send(CacheAction::GetBal { block_hash, response_tx });
283        rx.await
284            .map_err(|_| CacheServiceUnavailable)?
285            .map(|maybe_bal| maybe_bal.map(|cached| cached.0))
286    }
287
288    /// Inserts a decoded evm2 BAL into the cache.
289    pub fn insert_bal(&self, block_hash: B256, bal: DecodedBal<Arc<EvmBal>>) {
290        let _ =
291            self.to_service.send(CacheAction::InsertBal { block_hash, bal: CachedBal::new(bal) });
292    }
293
294    /// Inserts receipts of the block with the given hash that the caller read from the provider.
295    ///
296    /// Requests waiting for the receipts of this block are answered with them.
297    pub fn insert_receipts(&self, block_hash: B256, receipts: Arc<Vec<N::Receipt>>) {
298        let _ = self
299            .to_service
300            .send(CacheAction::ReceiptsResult { block_hash, res: Ok(Some(receipts)) });
301    }
302}
303/// Thrown when the cache service task dropped.
304#[derive(Debug, thiserror::Error)]
305#[error("cache service task stopped")]
306pub struct CacheServiceUnavailable;
307
308impl From<CacheServiceUnavailable> for ProviderError {
309    fn from(err: CacheServiceUnavailable) -> Self {
310        Self::other(err)
311    }
312}
313
314/// A task that manages caches for data required by the `eth` rpc implementation.
315///
316/// It provides a caching layer on top of the given
317/// [`StateProvider`](reth_storage_api::StateProvider) and keeps data fetched via the provider in
318/// memory in an LRU cache. If the requested data is missing in the cache it is fetched and inserted
319/// into the cache afterwards. While fetching data from disk is sync, this service is async since
320/// requests and data is shared via channels.
321///
322/// This type is an endless future that listens for incoming messages from the user facing
323/// [`EthStateCache`] via a channel. If the requested data is not cached then it spawns a new task
324/// that does the IO and sends the result back to it. This way the caching service only
325/// handles messages and does LRU lookups and never blocking IO.
326///
327/// Caution: The channel for the data is _unbounded_ it is assumed that this is mainly used by the
328/// `reth_rpc::EthApi` which is typically invoked by the RPC server, which already uses
329/// permits to limit concurrent requests.
330#[must_use = "Type does nothing unless spawned"]
331pub(crate) struct EthStateCacheService<Provider>
332where
333    Provider: BlockReader + BalProvider,
334{
335    /// The type used to lookup data from disk
336    provider: Provider,
337    /// The LRU cache for full blocks grouped by their block hash.
338    full_block_cache: BlockLruCache<Provider::Block>,
339    /// The LRU cache for block receipts grouped by the block hash.
340    receipts_cache: ReceiptsLruCache<Provider::Receipt>,
341    /// The LRU cache for evm2 BALs grouped by the block hash.
342    bal_cache: BalLruCache,
343    /// Maximum time without a cache hit. Zero disables idle eviction.
344    idle_timeout: Duration,
345    /// Reclaims idle entries even when there are no requests or new blocks.
346    eviction_interval: Interval,
347    /// Whether an idle sweep has more entries to remove in a subsequent poll.
348    eviction_pending: bool,
349    /// Sender half of the action channel.
350    action_tx: UnboundedSender<CacheAction<Provider::Block, Provider::Receipt>>,
351    /// Receiver half of the action channel.
352    action_rx: UnboundedReceiverStream<CacheAction<Provider::Block, Provider::Receipt>>,
353    /// The type that's used to spawn tasks that do the actual work
354    action_task_spawner: Runtime,
355    /// Rate limiter for spawned fetch tasks.
356    ///
357    /// This restricts the max concurrent fetch tasks at the same time.
358    rate_limiter: Arc<Semaphore>,
359    /// Cache misses waiting for a database request slot.
360    ///
361    /// A request is only moved to the blocking pool after it acquires a permit. This prevents
362    /// cache misses that are waiting for a slot from occupying Tokio blocking threads.
363    pending_fetches: VecDeque<CacheFetch>,
364    /// LRU index mapping transaction hashes to their block hash and index within the block.
365    tx_hash_index: LruMap<TxHash, (B256, usize), FbBuildHasher<32>>,
366}
367
368impl<Provider> EthStateCacheService<Provider>
369where
370    Provider: BlockReader + BalProvider + Clone + Unpin + 'static,
371{
372    fn queue_fetch(&mut self, fetch: CacheFetch) {
373        if self.pending_fetches.is_empty() &&
374            let Ok(permit) = self.rate_limiter.clone().try_acquire_owned()
375        {
376            self.spawn_fetch(fetch, permit);
377            return
378        }
379
380        self.pending_fetches.push_back(fetch);
381        self.spawn_pending_fetches();
382    }
383
384    fn spawn_pending_fetches(&mut self) {
385        while let Some(fetch) = self.pending_fetches.pop_front() {
386            let Ok(permit) = self.rate_limiter.clone().try_acquire_owned() else {
387                self.pending_fetches.push_front(fetch);
388                return
389            };
390
391            self.spawn_fetch(fetch, permit);
392        }
393    }
394
395    fn spawn_fetch(&self, fetch: CacheFetch, permit: OwnedSemaphorePermit) {
396        let provider = self.provider.clone();
397        let action_tx = self.action_tx.clone();
398
399        match fetch {
400            CacheFetch::Block(block_hash) => {
401                let mut action_sender = ActionSender::new(CacheKind::Block, block_hash, action_tx);
402                self.action_task_spawner.spawn_blocking_task_detached(async move {
403                    let block_sender = provider
404                        .sealed_block_with_senders(
405                            BlockHashOrNumber::Hash(block_hash),
406                            TransactionVariant::WithHash,
407                        )
408                        .map(|maybe_block| maybe_block.map(Arc::new));
409                    drop(permit);
410                    action_sender.send_block(block_sender);
411                });
412            }
413            CacheFetch::Receipts(block_hash) => {
414                let mut action_sender =
415                    ActionSender::new(CacheKind::Receipt, block_hash, action_tx);
416                self.action_task_spawner.spawn_blocking_task_detached(async move {
417                    let res = provider
418                        .receipts_by_block(block_hash.into())
419                        .map(|maybe_receipts| maybe_receipts.map(Arc::new));
420                    drop(permit);
421                    action_sender.send_receipts(res);
422                });
423            }
424            CacheFetch::Bal(block_hash) => {
425                let mut action_sender = ActionSender::new(CacheKind::Bal, block_hash, action_tx);
426                self.action_task_spawner.spawn_blocking_task_detached(async move {
427                    let res = provider
428                        .get_bal_by_hash(block_hash)
429                        .and_then(|maybe_bal| maybe_bal.map(CachedBal::try_from_raw).transpose());
430                    drop(permit);
431                    action_sender.send_bal(res);
432                });
433            }
434        }
435    }
436
437    /// Indexes all transactions in a block by transaction hash.
438    fn index_block_transactions(&mut self, block: &RecoveredBlock<Provider::Block>) {
439        let block_hash = block.hash();
440        for (tx_idx, tx) in block.body().transactions().iter().enumerate() {
441            self.tx_hash_index.insert(*tx.tx_hash(), (block_hash, tx_idx));
442        }
443    }
444
445    /// Removes transaction index entries for a reorged block.
446    fn remove_block_transactions(&mut self, block: &RecoveredBlock<Provider::Block>) {
447        for tx in block.body().transactions() {
448            self.tx_hash_index.remove(tx.tx_hash());
449        }
450    }
451
452    fn on_new_block(
453        &mut self,
454        block_hash: B256,
455        res: ProviderResult<Option<Arc<RecoveredBlock<Provider::Block>>>>,
456        now: Instant,
457    ) {
458        if let Some(queued) = self.full_block_cache.remove(&block_hash) {
459            // send the response to queued senders
460            for tx in queued {
461                let _ = tx.send(res.clone());
462            }
463        }
464
465        // cache good block
466        if let Ok(Some(block)) = res {
467            self.full_block_cache.insert_at(block_hash, block, now);
468        }
469    }
470
471    fn on_new_receipts(
472        &mut self,
473        block_hash: B256,
474        res: ProviderResult<Option<Arc<Vec<Provider::Receipt>>>>,
475        now: Instant,
476    ) {
477        if let Some(queued) = self.receipts_cache.remove(&block_hash) {
478            // send the response to queued senders
479            for tx in queued {
480                let _ = tx.send(res.clone());
481            }
482        }
483
484        // cache good receipts
485        if let Ok(Some(receipts)) = res {
486            self.receipts_cache.insert_at(block_hash, receipts, now);
487        }
488    }
489
490    fn on_new_bal(
491        &mut self,
492        block_hash: B256,
493        res: ProviderResult<Option<CachedBal>>,
494        now: Instant,
495    ) {
496        // A local replay may finish before an older provider lookup returns.
497        if self.bal_cache.contains_key(&block_hash) {
498            return
499        }
500
501        if let Some(queued) = self.bal_cache.remove(&block_hash) {
502            for tx in queued {
503                let _ = tx.send(res.clone());
504            }
505        }
506
507        if let Ok(Some(bal)) = res {
508            self.bal_cache.insert_at(block_hash, bal, now);
509        }
510    }
511
512    fn on_reorg_block(
513        &mut self,
514        block_hash: B256,
515        res: ProviderResult<Option<Arc<RecoveredBlock<Provider::Block>>>>,
516    ) {
517        if let Some(queued) = self.full_block_cache.remove(&block_hash) {
518            // send the response to queued senders
519            for tx in queued {
520                let _ = tx.send(res.clone());
521            }
522        }
523    }
524
525    fn on_reorg_receipts(
526        &mut self,
527        block_hash: B256,
528        res: ProviderResult<Option<Arc<Vec<Provider::Receipt>>>>,
529    ) {
530        if let Some(queued) = self.receipts_cache.remove(&block_hash) {
531            // send the response to queued senders
532            for tx in queued {
533                let _ = tx.send(res.clone());
534            }
535        }
536    }
537
538    fn on_reorg_bal(&mut self, block_hash: B256, res: ProviderResult<Option<CachedBal>>) {
539        if let Some(queued) = self.bal_cache.remove(&block_hash) {
540            for tx in queued {
541                let _ = tx.send(res.clone());
542            }
543        }
544    }
545
546    /// Shrinks the queues but leaves some space for the next requests
547    fn shrink_queues(&mut self) {
548        let min_capacity = 2;
549        self.full_block_cache.shrink_to(min_capacity);
550        self.receipts_cache.shrink_to(min_capacity);
551        self.bal_cache.shrink_to(min_capacity);
552    }
553
554    fn update_cached_metrics(&mut self) {
555        self.full_block_cache.update_cached_metrics();
556        self.receipts_cache.update_cached_metrics();
557        self.bal_cache.update_cached_metrics();
558    }
559}
560
561impl<Provider> Future for EthStateCacheService<Provider>
562where
563    Provider: BlockReader + BalProvider + Clone + Unpin + 'static,
564{
565    type Output = ();
566
567    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
568        let this = self.get_mut();
569        // All inserts and hits in this poll share a clock read, preserving timestamp/LRU order.
570        let now = LazyCell::new(Instant::now);
571
572        // Poll until pending to register the next timer wakeup before draining requests.
573        while !this.idle_timeout.is_zero() && this.eviction_interval.poll_tick(cx).is_ready() {
574            this.eviction_pending = true;
575        }
576        if this.eviction_pending {
577            let now = *now;
578            this.eviction_pending = this.full_block_cache.evict_expired(now, this.idle_timeout);
579            this.eviction_pending |= this.receipts_cache.evict_expired(now, this.idle_timeout);
580            this.eviction_pending |= this.bal_cache.evict_expired(now, this.idle_timeout);
581            if this.eviction_pending {
582                // Process requests before continuing the sweep in another poll.
583                cx.waker().wake_by_ref();
584            }
585        }
586
587        loop {
588            let Poll::Ready(action) = this.action_rx.poll_next_unpin(cx) else {
589                // shrink queues if we don't have any work to do
590                this.shrink_queues();
591                // gauges only need to be accurate once the batch of messages is drained, and only
592                // caches that changed during the batch republish theirs
593                this.update_cached_metrics();
594                return Poll::Pending;
595            };
596
597            match action {
598                None => {
599                    unreachable!("can't close")
600                }
601                Some(action) => {
602                    let now = *now;
603                    match action {
604                        CacheAction::GetCachedBlock { block_hash, response_tx } => {
605                            let _ = response_tx
606                                .send(this.full_block_cache.get_at(&block_hash, now).cloned());
607                        }
608                        CacheAction::GetCachedBal { block_hash, response_tx } => {
609                            let _ =
610                                response_tx.send(this.bal_cache.get_at(&block_hash, now).cloned());
611                        }
612                        CacheAction::GetCachedBlockAndReceipts { block_hash, response_tx } => {
613                            let block = this.full_block_cache.get_at(&block_hash, now).cloned();
614                            let receipts = this.receipts_cache.get_at(&block_hash, now).cloned();
615                            let _ = response_tx.send((block, receipts));
616                        }
617                        CacheAction::GetBlockWithSenders { block_hash, response_tx } => {
618                            if let Some(block) =
619                                this.full_block_cache.get_at(&block_hash, now).cloned()
620                            {
621                                let _ = response_tx.send(Ok(Some(block)));
622                                continue
623                            }
624
625                            // block is not in the cache, request it if this is the first consumer
626                            if this.full_block_cache.queue(block_hash, response_tx) {
627                                this.queue_fetch(CacheFetch::Block(block_hash));
628                            }
629                        }
630                        CacheAction::GetReceipts { block_hash, response_tx } => {
631                            // check if block is cached
632                            if let Some(receipts) =
633                                this.receipts_cache.get_at(&block_hash, now).cloned()
634                            {
635                                let _ = response_tx.send(Ok(Some(receipts)));
636                                continue
637                            }
638
639                            // block is not in the cache, request it if this is the first consumer
640                            if this.receipts_cache.queue(block_hash, response_tx) {
641                                this.queue_fetch(CacheFetch::Receipts(block_hash));
642                            }
643                        }
644                        CacheAction::GetBal { block_hash, response_tx } => {
645                            if let Some(bal) = this.bal_cache.get_at(&block_hash, now).cloned() {
646                                let _ = response_tx.send(Ok(Some(bal)));
647                                continue
648                            }
649
650                            if this.bal_cache.queue(block_hash, response_tx) {
651                                this.queue_fetch(CacheFetch::Bal(block_hash));
652                            }
653                        }
654                        CacheAction::ReceiptsResult { block_hash, res } => {
655                            this.on_new_receipts(block_hash, res, now);
656                        }
657                        CacheAction::BalResult { block_hash, res } => {
658                            this.on_new_bal(block_hash, res, now);
659                        }
660                        CacheAction::InsertBal { block_hash, bal } => {
661                            this.on_new_bal(block_hash, Ok(Some(bal)), now);
662                        }
663                        CacheAction::BlockWithSendersResult { block_hash, res } => {
664                            this.on_new_block(block_hash, res, now);
665                        }
666                        CacheAction::CacheNewCanonicalChain { chain_change } => {
667                            for block in chain_change.blocks {
668                                // Index transactions before caching the block
669                                this.index_block_transactions(&block);
670                                this.on_new_block(block.hash(), Ok(Some(block)), now);
671                            }
672
673                            for block_receipts in chain_change.receipts {
674                                this.on_new_receipts(
675                                    block_receipts.block_hash,
676                                    Ok(Some(block_receipts.receipts)),
677                                    now,
678                                );
679                            }
680
681                            for (block_hash, bal) in chain_change.bals {
682                                this.on_new_bal(
683                                    block_hash,
684                                    Ok(Some(CachedBal::from_shared(bal))),
685                                    now,
686                                );
687                            }
688                        }
689                        CacheAction::RemoveReorgedChain { chain_change } => {
690                            for block in chain_change.blocks {
691                                let block_hash = block.hash();
692                                // Remove transaction index entries for reorged blocks
693                                this.remove_block_transactions(&block);
694                                this.on_reorg_block(block_hash, Ok(Some(block)));
695                                this.on_reorg_bal(block_hash, Ok(None));
696                            }
697
698                            for block_receipts in chain_change.receipts {
699                                this.on_reorg_receipts(
700                                    block_receipts.block_hash,
701                                    Ok(Some(block_receipts.receipts)),
702                                );
703                            }
704                        }
705                        CacheAction::GetTransactionByHash { tx_hash, response_tx } => {
706                            let result =
707                                this.tx_hash_index.get(&tx_hash).and_then(|(block_hash, idx)| {
708                                    let block =
709                                        this.full_block_cache.get_at(block_hash, now).cloned()?;
710                                    let receipts =
711                                        this.receipts_cache.get_at(block_hash, now).cloned();
712                                    Some(CachedTransaction::new(block, *idx, receipts))
713                                });
714                            let _ = response_tx.send(result);
715                        }
716                    };
717                    this.spawn_pending_fetches();
718                }
719            }
720        }
721    }
722}
723
724/// All message variants sent through the channel
725enum CacheAction<B: Block, R> {
726    GetBlockWithSenders {
727        block_hash: B256,
728        response_tx: BlockWithSendersResponseSender<B>,
729    },
730    GetReceipts {
731        block_hash: B256,
732        response_tx: ReceiptsResponseSender<R>,
733    },
734    GetBal {
735        block_hash: B256,
736        response_tx: BalResponseSender,
737    },
738    GetCachedBlock {
739        block_hash: B256,
740        response_tx: CachedBlockResponseSender<B>,
741    },
742    GetCachedBal {
743        block_hash: B256,
744        response_tx: CachedBalResponseSender,
745    },
746    GetCachedBlockAndReceipts {
747        block_hash: B256,
748        response_tx: CachedBlockAndReceiptsResponseSender<B, R>,
749    },
750    BlockWithSendersResult {
751        block_hash: B256,
752        res: ProviderResult<Option<Arc<RecoveredBlock<B>>>>,
753    },
754    ReceiptsResult {
755        block_hash: B256,
756        res: ProviderResult<Option<Arc<Vec<R>>>>,
757    },
758    BalResult {
759        block_hash: B256,
760        res: ProviderResult<Option<CachedBal>>,
761    },
762    InsertBal {
763        block_hash: B256,
764        bal: CachedBal,
765    },
766    CacheNewCanonicalChain {
767        chain_change: ChainChange<B, R>,
768    },
769    RemoveReorgedChain {
770        chain_change: ChainChange<B, R>,
771    },
772    /// Look up a transaction's cached data by its hash
773    GetTransactionByHash {
774        tx_hash: TxHash,
775        response_tx: TransactionHashResponseSender<B, R>,
776    },
777}
778
779struct BlockReceipts<R> {
780    block_hash: B256,
781    receipts: Arc<Vec<R>>,
782}
783
784/// A change of the canonical chain
785struct ChainChange<B: Block, R> {
786    blocks: Vec<Arc<RecoveredBlock<B>>>,
787    receipts: Vec<BlockReceipts<R>>,
788    bals: Vec<(B256, Arc<DecodedEvmBal>)>,
789}
790
791impl<B: Block, R: Clone> ChainChange<B, R> {
792    fn new<N>(chain: Arc<Chain<N>>) -> Self
793    where
794        N: NodePrimitives<Block = B, Receipt = R>,
795    {
796        let (blocks, receipts): (Vec<_>, Vec<_>) = chain
797            .blocks_and_receipts()
798            .map(|(block, receipts)| {
799                let block_receipts = BlockReceipts {
800                    block_hash: block.hash(),
801                    receipts: Arc::new(receipts.clone()),
802                };
803                (Arc::clone(block), block_receipts)
804            })
805            .unzip();
806        // Blocks without an attached BAL are absent here; their BAL is fetched from the store on
807        // demand.
808        let bals =
809            chain.blocks_and_bals().map(|(block, bal)| (block.hash(), Arc::clone(bal))).collect();
810        Self { blocks, receipts, bals }
811    }
812}
813
814/// Identifier for the caches.
815#[derive(Copy, Clone, Debug)]
816enum CacheKind {
817    Block,
818    Receipt,
819    Bal,
820}
821
822#[derive(Copy, Clone, Debug)]
823enum CacheFetch {
824    Block(B256),
825    Receipts(B256),
826    Bal(B256),
827}
828
829/// Drop aware sender struct that ensures a response is always emitted even if the db task panics
830/// before a result could be sent.
831///
832/// This type wraps a sender and in case the sender is still present on drop emit an error response.
833#[derive(Debug)]
834struct ActionSender<B: Block, R: Send + Sync> {
835    kind: CacheKind,
836    blockhash: B256,
837    tx: Option<UnboundedSender<CacheAction<B, R>>>,
838}
839
840impl<R: Send + Sync, B: Block> ActionSender<B, R> {
841    const fn new(kind: CacheKind, blockhash: B256, tx: UnboundedSender<CacheAction<B, R>>) -> Self {
842        Self { kind, blockhash, tx: Some(tx) }
843    }
844
845    fn send_block(&mut self, block_sender: Result<Option<Arc<RecoveredBlock<B>>>, ProviderError>) {
846        if let Some(tx) = self.tx.take() {
847            let _ = tx.send(CacheAction::BlockWithSendersResult {
848                block_hash: self.blockhash,
849                res: block_sender,
850            });
851        }
852    }
853
854    fn send_receipts(&mut self, receipts: Result<Option<Arc<Vec<R>>>, ProviderError>) {
855        if let Some(tx) = self.tx.take() {
856            let _ =
857                tx.send(CacheAction::ReceiptsResult { block_hash: self.blockhash, res: receipts });
858        }
859    }
860
861    fn send_bal(&mut self, bal: Result<Option<CachedBal>, ProviderError>) {
862        if let Some(tx) = self.tx.take() {
863            let _ = tx.send(CacheAction::BalResult { block_hash: self.blockhash, res: bal });
864        }
865    }
866}
867impl<R: Send + Sync, B: Block> Drop for ActionSender<B, R> {
868    fn drop(&mut self) {
869        if let Some(tx) = self.tx.take() {
870            let msg = match self.kind {
871                CacheKind::Block => CacheAction::BlockWithSendersResult {
872                    block_hash: self.blockhash,
873                    res: Err(CacheServiceUnavailable.into()),
874                },
875                CacheKind::Receipt => CacheAction::ReceiptsResult {
876                    block_hash: self.blockhash,
877                    res: Err(CacheServiceUnavailable.into()),
878                },
879                CacheKind::Bal => CacheAction::BalResult {
880                    block_hash: self.blockhash,
881                    res: Err(CacheServiceUnavailable.into()),
882                },
883            };
884            let _ = tx.send(msg);
885        }
886    }
887}
888
889/// Awaits for new chain events and directly inserts them into the cache so they're available
890/// immediately before they need to be fetched from disk.
891///
892/// Reorged blocks are removed from the cache.
893pub async fn cache_new_blocks_task<St, N: NodePrimitives>(
894    eth_state_cache: EthStateCache<N>,
895    mut events: St,
896) where
897    St: Stream<Item = CanonStateNotification<N>> + Unpin + 'static,
898{
899    while let Some(event) = events.next().await {
900        if let Some(reverted) = event.reverted() {
901            let chain_change = ChainChange::new(reverted);
902
903            let _ =
904                eth_state_cache.to_service.send(CacheAction::RemoveReorgedChain { chain_change });
905        }
906
907        let chain_change = ChainChange::new(event.committed());
908
909        let _ =
910            eth_state_cache.to_service.send(CacheAction::CacheNewCanonicalChain { chain_change });
911    }
912}
913
914/// Cached decoded evm2 BAL.
915#[derive(Clone, Debug)]
916pub(crate) struct CachedBal(Arc<DecodedEvmBal>);
917
918impl CachedBal {
919    /// Creates a cached evm2 BAL from an owned decoded BAL.
920    #[inline]
921    fn new(bal: DecodedEvmBal) -> Self {
922        Self(Arc::new(bal))
923    }
924
925    /// Creates a cached evm2 BAL from a BAL that is already shared, for example one prepared
926    /// during block validation.
927    #[inline]
928    const fn from_shared(bal: Arc<DecodedEvmBal>) -> Self {
929        Self(bal)
930    }
931
932    /// Decodes raw BAL bytes into the representation used by evm2.
933    fn try_from_raw(raw: Bytes) -> ProviderResult<Self> {
934        DecodedBal::from_rlp_bytes(raw)
935            .map_err(Into::into)
936            .and_then(|decoded| {
937                decoded.try_map(|bal| {
938                    EvmBal::try_from(Vec::from(bal)).map(Arc::new).map_err(ProviderError::other)
939                })
940            })
941            .map(Self::new)
942    }
943}
944
945impl InMemorySize for CachedBal {
946    fn size(&self) -> usize {
947        core::mem::size_of::<Self>() + decoded_bal_size(&self.0)
948    }
949}
950
951fn decoded_bal_size(bal: &DecodedEvmBal) -> usize {
952    core::mem::size_of::<DecodedEvmBal>() + bal.as_raw().len() + evm_bal_size(bal.as_bal())
953}
954
955fn evm_bal_size(bal: &EvmBal) -> usize {
956    core::mem::size_of::<EvmBal>() +
957        bal.accounts.capacity() * core::mem::size_of::<(Address, EvmAccountBal)>() +
958        bal.accounts.values().map(evm_account_bal_heap_size).sum::<usize>()
959}
960
961fn evm_account_bal_heap_size(account: &EvmAccountBal) -> usize {
962    evm_account_info_bal_heap_size(&account.account_info) +
963        evm_storage_bal_heap_size(&account.storage)
964}
965
966fn evm_account_info_bal_heap_size(account_info: &EvmAccountInfoBal) -> usize {
967    evm_bal_changes_heap_size(&account_info.nonce, |_| 0) +
968        evm_bal_changes_heap_size(&account_info.balance, |_| 0) +
969        evm_bal_changes_heap_size(&account_info.code, evm_code_change_heap_size)
970}
971
972fn evm_storage_bal_heap_size(storage: &EvmStorageBal) -> usize {
973    storage.storage.capacity() * core::mem::size_of::<(U256, EvmBalChanges<StorageChange>)>() +
974        storage
975            .storage
976            .values()
977            .map(|changes| evm_bal_changes_heap_size(changes, |_| 0))
978            .sum::<usize>()
979}
980
981fn evm_bal_changes_heap_size<T, F>(changes: &EvmBalChanges<T>, mut item_heap_size: F) -> usize
982where
983    T: EvmBalChange,
984    F: FnMut(&T) -> usize,
985{
986    changes.changes.capacity() * core::mem::size_of::<T>() +
987        changes.changes.iter().map(&mut item_heap_size).sum::<usize>()
988}
989
990fn evm_code_change_heap_size(change: &EvmBalCodeChange) -> usize {
991    bytecode_heap_size(&change.code.1)
992}
993
994fn bytecode_heap_size(bytecode: &Bytecode) -> usize {
995    bytecode.original_bytes().len()
996}
997
998#[cfg(test)]
999mod tests {
1000    use super::*;
1001    use alloy_consensus::{transaction::TransactionMeta, Header};
1002    use alloy_eip7928::BlockAccessIndex;
1003    use alloy_eips::{BlockHashOrNumber, NumHash};
1004    use alloy_primitives::{
1005        Address, BlockHash, BlockNumber, Bytes, Signature, TxHash, TxNumber, U256,
1006    };
1007    use core::ops::{RangeBounds, RangeInclusive};
1008    use reth_db_models::StoredBlockBodyIndices;
1009    use reth_ethereum_primitives::{
1010        Block, BlockBody, EthPrimitives, Receipt, Transaction, TransactionSigned,
1011    };
1012    use reth_execution_types::{ExecutionOutcome, RecoveredBlockAndExecutionOutput};
1013    use reth_primitives_traits::{RecoveredBlock, SealedHeader};
1014    use reth_storage_api::{
1015        noop::NoopProvider, BalProvider, BalStore, BalStoreHandle, BlockBodyIndicesProvider,
1016        BlockHashReader, BlockNumReader, BlockReader, BlockSource, HeaderProvider, ReceiptProvider,
1017        TransactionVariant, TransactionsProvider,
1018    };
1019    use std::{
1020        sync::{
1021            atomic::{AtomicUsize, Ordering},
1022            mpsc::{self, Receiver, SyncSender},
1023            Mutex,
1024        },
1025        task::{Wake, Waker},
1026        thread,
1027        time::Duration,
1028    };
1029
1030    #[derive(Default)]
1031    struct WakeCounter(AtomicUsize);
1032
1033    impl Wake for WakeCounter {
1034        fn wake(self: Arc<Self>) {
1035            self.0.fetch_add(1, Ordering::Relaxed);
1036        }
1037    }
1038
1039    fn test_service() -> EthStateCacheService<NoopProvider> {
1040        let (_cache, service) = EthStateCache::<EthPrimitives>::create(
1041            NoopProvider::default(),
1042            Runtime::test(),
1043            EthStateCacheConfig {
1044                max_blocks: 4,
1045                max_receipts: 4,
1046                max_bals: 4,
1047                cache_computed_bals: false,
1048                prewarm_bals: None,
1049                max_concurrent_db_requests: 1,
1050                max_cached_tx_hashes: 16,
1051                ..Default::default()
1052            },
1053        );
1054        service
1055    }
1056
1057    fn test_decoded_evm_bal() -> DecodedBal<Arc<EvmBal>> {
1058        DecodedBal::new(Arc::new(EvmBal::default()), Bytes::from_static(&[0xc0]))
1059    }
1060
1061    fn test_block() -> RecoveredBlock<Block> {
1062        RecoveredBlock::new_unhashed(
1063            Block {
1064                header: Header { number: 1, ..Default::default() },
1065                body: BlockBody {
1066                    transactions: vec![TransactionSigned::new_unhashed(
1067                        Transaction::Legacy(Default::default()),
1068                        Signature::test_signature(),
1069                    )],
1070                    ..Default::default()
1071                },
1072            },
1073            vec![Address::ZERO],
1074        )
1075    }
1076
1077    #[tokio::test(start_paused = true)]
1078    async fn idle_timer_continues_waking_after_its_first_tick() {
1079        let (cache, mut service) = EthStateCache::<EthPrimitives>::create(
1080            NoopProvider::default(),
1081            Runtime::test(),
1082            EthStateCacheConfig { idle_timeout: Duration::from_secs(10), ..Default::default() },
1083        );
1084        tokio::time::advance(Duration::from_secs(3)).await;
1085        let block = Arc::new(test_block());
1086        let hash = block.hash();
1087        let receipts = Arc::new(vec![]);
1088        let bal = CachedBal::new(test_decoded_evm_bal());
1089        let retained_block = Arc::downgrade(&block);
1090        let retained_receipts = Arc::downgrade(&receipts);
1091        let retained_bal = Arc::downgrade(&bal.0);
1092        service.on_new_block(hash, Ok(Some(block)), Instant::now());
1093        service.on_new_receipts(hash, Ok(Some(receipts)), Instant::now());
1094        service.on_new_bal(hash, Ok(Some(bal)), Instant::now());
1095        let (response_tx, response_rx) = oneshot::channel();
1096        service.full_block_cache.queue(hash, response_tx);
1097        let service_task = tokio::spawn(service);
1098        assert!(cache.get_maybe_block(hash).await.unwrap().is_some());
1099
1100        tokio::time::advance(Duration::from_secs(7)).await;
1101        tokio::task::yield_now().await;
1102        assert!(retained_block.upgrade().is_some());
1103        assert!(retained_receipts.upgrade().is_some());
1104        assert!(retained_bal.upgrade().is_some());
1105        // No more cache actions: only a later timer tick can release these payloads.
1106        tokio::time::advance(Duration::from_secs(11)).await;
1107        tokio::task::yield_now().await;
1108        let expired = retained_block.upgrade().is_none() &&
1109            retained_receipts.upgrade().is_none() &&
1110            retained_bal.upgrade().is_none();
1111
1112        // Expiration must leave pending consumers available for the next result.
1113        cache
1114            .to_service
1115            .send(CacheAction::BlockWithSendersResult {
1116                block_hash: hash,
1117                res: Ok(Some(Arc::new(test_block()))),
1118            })
1119            .unwrap();
1120        let response = response_rx.await.unwrap();
1121        service_task.abort();
1122        assert!(expired, "idle service did not register its next timer wakeup");
1123        assert!(response.unwrap().is_some());
1124    }
1125
1126    #[tokio::test(start_paused = true)]
1127    async fn idle_eviction_yields_between_batches_and_serves_requests() {
1128        let (cache, mut service) = EthStateCache::<EthPrimitives>::create(
1129            NoopProvider::default(),
1130            Runtime::test(),
1131            EthStateCacheConfig { idle_timeout: Duration::from_secs(10), ..Default::default() },
1132        );
1133        let mut retained = Vec::new();
1134        for key in 0..12 {
1135            let hash = B256::with_last_byte(key);
1136            let block = Arc::new(test_block());
1137            let receipts = Arc::new(vec![]);
1138            let bal = CachedBal::new(test_decoded_evm_bal());
1139            retained.push((
1140                Arc::downgrade(&block),
1141                Arc::downgrade(&receipts),
1142                Arc::downgrade(&bal.0),
1143            ));
1144            service.on_new_block(hash, Ok(Some(block)), Instant::now());
1145            service.on_new_receipts(hash, Ok(Some(receipts)), Instant::now());
1146            service.on_new_bal(hash, Ok(Some(bal)), Instant::now());
1147        }
1148        let (response_tx, mut response_rx) = oneshot::channel();
1149        cache
1150            .to_service
1151            .send(CacheAction::GetCachedBlock { block_hash: B256::repeat_byte(0xff), response_tx })
1152            .unwrap();
1153        tokio::time::advance(Duration::from_secs(10)).await;
1154
1155        let wakes = Arc::new(WakeCounter::default());
1156        let waker = Waker::from(wakes.clone());
1157        let mut cx = Context::from_waker(&waker);
1158        for (remaining, expected_wakes) in [(7, 1), (2, 2), (0, 2)] {
1159            assert!(Pin::new(&mut service).poll(&mut cx).is_pending());
1160            assert_eq!(wakes.0.load(Ordering::Relaxed), expected_wakes);
1161            assert_eq!(
1162                retained.iter().filter(|(block, _, _)| block.strong_count() > 0).count(),
1163                remaining
1164            );
1165            assert_eq!(
1166                retained.iter().filter(|(_, receipts, _)| receipts.strong_count() > 0).count(),
1167                remaining
1168            );
1169            assert_eq!(
1170                retained.iter().filter(|(_, _, bal)| bal.strong_count() > 0).count(),
1171                remaining
1172            );
1173            if remaining == 7 {
1174                assert!(response_rx.try_recv().unwrap().is_none());
1175            }
1176        }
1177    }
1178
1179    #[tokio::test(start_paused = true)]
1180    async fn disabled_idle_timeout_does_not_schedule_cleanup() {
1181        let (_cache, mut service) = EthStateCache::<EthPrimitives>::create(
1182            NoopProvider::default(),
1183            Runtime::test(),
1184            EthStateCacheConfig { idle_timeout: Duration::ZERO, ..Default::default() },
1185        );
1186        let wakes = Arc::new(WakeCounter::default());
1187        let waker = Waker::from(wakes.clone());
1188        let mut cx = Context::from_waker(&waker);
1189        assert!(Pin::new(&mut service).poll(&mut cx).is_pending());
1190
1191        tokio::time::advance(Duration::from_secs(10)).await;
1192        assert_eq!(wakes.0.load(Ordering::Relaxed), 0);
1193    }
1194
1195    #[test]
1196    fn oversized_results_reach_queued_consumers() {
1197        let block = Arc::new(test_block());
1198        let receipts = Arc::new(vec![Receipt::default()]);
1199        let bal = CachedBal::new(test_decoded_evm_bal());
1200        let hash = block.hash();
1201        let (_cache, mut service) = EthStateCache::<EthPrimitives>::create(
1202            NoopProvider::default(),
1203            Runtime::test(),
1204            EthStateCacheConfig {
1205                max_blocks_bytes: block.size() - 1,
1206                max_receipts_bytes: receipts.size() - 1,
1207                max_bals_bytes: bal.size() - 1,
1208                ..Default::default()
1209            },
1210        );
1211        let (block_tx, mut block_rx) = oneshot::channel();
1212        let (receipts_tx, mut receipts_rx) = oneshot::channel();
1213        let (bal_tx, mut bal_rx) = oneshot::channel();
1214        service.full_block_cache.queue(hash, block_tx);
1215        service.receipts_cache.queue(hash, receipts_tx);
1216        service.bal_cache.queue(hash, bal_tx);
1217
1218        service.on_new_block(hash, Ok(Some(block.clone())), Instant::now());
1219        service.on_new_receipts(hash, Ok(Some(receipts.clone())), Instant::now());
1220        service.on_new_bal(hash, Ok(Some(bal.clone())), Instant::now());
1221
1222        assert!(Arc::ptr_eq(&block_rx.try_recv().unwrap().unwrap().unwrap(), &block));
1223        assert!(Arc::ptr_eq(&receipts_rx.try_recv().unwrap().unwrap().unwrap(), &receipts));
1224        assert!(Arc::ptr_eq(&bal_rx.try_recv().unwrap().unwrap().unwrap().0, &bal.0));
1225        assert!(service.full_block_cache.get(&hash).is_none());
1226        assert!(service.receipts_cache.get(&hash).is_none());
1227        assert!(service.bal_cache.get(&hash).is_none());
1228    }
1229
1230    #[tokio::test(start_paused = true)]
1231    async fn cached_transaction_lookup_renews_idle_timeout() {
1232        let (cache, mut service) = EthStateCache::<EthPrimitives>::create(
1233            NoopProvider::default(),
1234            Runtime::test(),
1235            EthStateCacheConfig { idle_timeout: Duration::from_secs(10), ..Default::default() },
1236        );
1237        let block = Arc::new(test_block());
1238        let hash = block.hash();
1239        let tx_hash = *block.body().transactions().next().unwrap().tx_hash();
1240        service.index_block_transactions(&block);
1241        service.on_new_block(hash, Ok(Some(block)), Instant::now());
1242        service.on_new_receipts(hash, Ok(Some(Arc::new(vec![Receipt::default()]))), Instant::now());
1243
1244        for delay in [6, 6, 11] {
1245            tokio::time::advance(Duration::from_secs(delay)).await;
1246            let request = cache.get_transaction_by_hash(tx_hash);
1247            futures::pin_mut!(request);
1248            assert!(futures::poll!(&mut request).is_pending());
1249            assert!(futures::poll!(&mut service).is_pending());
1250            let result = request.await;
1251            if delay < 10 {
1252                let result = result.expect("transaction is still cached after a renewed hit");
1253                assert_eq!(result.block.hash(), hash);
1254                assert!(result.receipts.is_some());
1255            } else {
1256                assert!(result.is_none());
1257            }
1258        }
1259    }
1260
1261    #[test]
1262    fn reorg_removes_tx_hash_index_entries_unconditionally() {
1263        let mut service = test_service();
1264        let block = test_block();
1265        let tx_hash = *block.body().transactions().next().expect("test transaction").tx_hash();
1266
1267        service.tx_hash_index.insert(tx_hash, (B256::repeat_byte(0x33), 0));
1268
1269        service.remove_block_transactions(&block);
1270
1271        assert!(service.tx_hash_index.get(&tx_hash).is_none());
1272    }
1273
1274    #[test]
1275    fn reorg_evicts_cached_bal() {
1276        let mut service = test_service();
1277        let block_hash = B256::repeat_byte(0x44);
1278
1279        assert!(service.bal_cache.insert(block_hash, CachedBal::new(test_decoded_evm_bal())));
1280        assert!(service.bal_cache.get(&block_hash).is_some());
1281
1282        service.on_reorg_bal(block_hash, Ok(None));
1283
1284        assert!(service.bal_cache.get(&block_hash).is_none());
1285    }
1286
1287    #[test]
1288    fn late_provider_miss_preserves_generated_bal() {
1289        let mut service = test_service();
1290        let hash = B256::repeat_byte(0x69);
1291        let (tx, mut rx) = oneshot::channel();
1292        assert!(service.bal_cache.queue(hash, tx));
1293        service.on_new_bal(hash, Ok(Some(CachedBal::new(test_decoded_evm_bal()))), Instant::now());
1294        assert!(rx.try_recv().unwrap().unwrap().is_some());
1295        service.on_new_bal(hash, Ok(None), Instant::now());
1296        assert!(service.bal_cache.contains_key(&hash));
1297    }
1298
1299    #[tokio::test]
1300    async fn cache_misses_wait_in_service_queue_for_db_slot() {
1301        let (started_tx, started_rx) = mpsc::sync_channel(1);
1302        let (release_tx, release_rx) = mpsc::sync_channel(1);
1303        let (_cache, mut service) = EthStateCache::<EthPrimitives>::create(
1304            TestBalProvider::new_blocking(started_tx, release_rx),
1305            Runtime::test(),
1306            EthStateCacheConfig { max_concurrent_db_requests: 1, ..Default::default() },
1307        );
1308        let permit = service.rate_limiter.clone().try_acquire_owned().unwrap();
1309
1310        service.queue_fetch(CacheFetch::Bal(B256::repeat_byte(0x01)));
1311        service.queue_fetch(CacheFetch::Bal(B256::repeat_byte(0x02)));
1312
1313        assert_eq!(service.pending_fetches.len(), 2);
1314
1315        drop(permit);
1316        service.spawn_pending_fetches();
1317
1318        started_rx.recv_timeout(Duration::from_secs(1)).expect("first fetch started");
1319        assert_eq!(service.pending_fetches.len(), 1);
1320        release_tx.send(()).unwrap();
1321    }
1322
1323    #[test]
1324    fn pending_cache_miss_does_not_block_unrelated_blocking_work() {
1325        let (started_tx, started_rx) = mpsc::sync_channel(1);
1326        let (release_tx, release_rx) = mpsc::sync_channel(1);
1327        let (unrelated_tx, unrelated_rx) = mpsc::sync_channel(1);
1328
1329        let test = thread::spawn(move || {
1330            let runtime = tokio::runtime::Builder::new_multi_thread()
1331                .worker_threads(1)
1332                .max_blocking_threads(1)
1333                .enable_all()
1334                .build()
1335                .unwrap();
1336
1337            runtime.block_on(async move {
1338                let provider = TestBalProvider::new_blocking(started_tx, release_rx);
1339                let (_cache, mut service) = EthStateCache::<EthPrimitives>::create(
1340                    provider,
1341                    Runtime::test(),
1342                    EthStateCacheConfig {
1343                        max_blocks: 0,
1344                        max_receipts: 0,
1345                        max_bals: 0,
1346                        cache_computed_bals: false,
1347                        prewarm_bals: None,
1348                        max_concurrent_db_requests: 1,
1349                        max_cached_tx_hashes: 0,
1350                        ..Default::default()
1351                    },
1352                );
1353
1354                service.queue_fetch(CacheFetch::Bal(B256::repeat_byte(0x01)));
1355                started_rx.recv_timeout(Duration::from_secs(1)).expect("first fetch started");
1356
1357                service.queue_fetch(CacheFetch::Bal(B256::repeat_byte(0x02)));
1358                assert_eq!(service.pending_fetches.len(), 1);
1359
1360                tokio::task::spawn_blocking(move || unrelated_tx.send(()).unwrap());
1361                release_tx.send(()).unwrap();
1362
1363                unrelated_rx
1364                    .recv_timeout(Duration::from_secs(1))
1365                    .expect("unrelated blocking work was not starved");
1366            });
1367        });
1368
1369        test.join().unwrap();
1370    }
1371
1372    #[test]
1373    fn reorg_forwards_bal_to_queued_requests() {
1374        let mut service = test_service();
1375        let block_hash = B256::repeat_byte(0x55);
1376        let (response_tx, mut response_rx) = oneshot::channel();
1377        let bal = CachedBal::new(test_decoded_evm_bal());
1378
1379        assert!(service.bal_cache.queue(block_hash, response_tx));
1380
1381        service.on_reorg_bal(block_hash, Ok(Some(bal)));
1382
1383        let bal = response_rx.try_recv().expect("queued BAL response").expect("BAL result");
1384
1385        assert!(bal.is_some());
1386    }
1387
1388    #[test]
1389    fn cached_evm_bal_size_accounts_for_nested_allocations() {
1390        let index = BlockAccessIndex::new(1);
1391        let mut account = EvmAccountBal::default();
1392        account.account_info.nonce.changes.push(alloy_eip7928::NonceChange::new(index, 1));
1393        account
1394            .account_info
1395            .balance
1396            .changes
1397            .push(alloy_eip7928::BalanceChange::new(index, U256::from(1)));
1398        account.account_info.code.changes.push(EvmBalCodeChange::new(
1399            index,
1400            (B256::repeat_byte(0xaa), Bytecode::new_raw(Bytes::from_static(&[0x60, 0x00]))),
1401        ));
1402        account.storage.storage.insert(
1403            U256::from(1),
1404            EvmBalChanges::new(vec![alloy_eip7928::StorageChange::new(index, U256::from(2))]),
1405        );
1406
1407        let mut bal = EvmBal::default();
1408        bal.accounts.insert(Address::ZERO, account);
1409
1410        let raw = Bytes::from_static(&[0xc0, 0x01, 0x02]);
1411        let previous_estimate = core::mem::size_of::<CachedBal>() +
1412            core::mem::size_of::<DecodedBal<Arc<EvmBal>>>() +
1413            raw.len() +
1414            core::mem::size_of::<EvmBal>();
1415        assert!(CachedBal::new(DecodedBal::new(Arc::new(bal), raw)).size() > previous_estimate);
1416    }
1417
1418    #[tokio::test]
1419    async fn get_bal_only_caches_results_within_budget() {
1420        for (max_bals_bytes, expected_fetches) in [(usize::MAX, 1), (1, 2), (0, 2)] {
1421            let fetches = Arc::new(AtomicUsize::default());
1422            let cache = EthStateCache::<EthPrimitives>::spawn_with(
1423                TestBalProvider::new(fetches.clone()),
1424                EthStateCacheConfig {
1425                    max_blocks: 0,
1426                    max_receipts: 0,
1427                    max_bals: 4,
1428                    max_bals_bytes,
1429                    cache_computed_bals: false,
1430                    prewarm_bals: None,
1431                    max_concurrent_db_requests: 1,
1432                    max_cached_tx_hashes: 0,
1433                    ..Default::default()
1434                },
1435                Runtime::test(),
1436            );
1437            let block_hash = B256::repeat_byte(0x66);
1438
1439            assert!(cache.get_bal(block_hash).await.unwrap().is_some());
1440            assert!(cache.get_bal(block_hash).await.unwrap().is_some());
1441
1442            assert_eq!(fetches.load(Ordering::SeqCst), expected_fetches);
1443        }
1444    }
1445
1446    #[reth_concurrency::test]
1447    async fn get_recovered_block_and_maybe_bal_does_not_fetch_bal() {
1448        let bal_fetches = Arc::new(AtomicUsize::default());
1449        let block = test_block();
1450        let block_hash = block.hash();
1451        let provider = TestBalProvider::new(bal_fetches.clone()).with_block(block);
1452        let cache = EthStateCache::<EthPrimitives>::spawn_with(
1453            provider,
1454            EthStateCacheConfig {
1455                max_blocks: 4,
1456                max_receipts: 0,
1457                max_bals: 4,
1458                cache_computed_bals: false,
1459                prewarm_bals: None,
1460                max_concurrent_db_requests: 1,
1461                max_cached_tx_hashes: 0,
1462                ..Default::default()
1463            },
1464            Runtime::test(),
1465        );
1466
1467        let (returned_block, bal) = cache
1468            .get_recovered_block_and_maybe_bal(block_hash)
1469            .await
1470            .unwrap()
1471            .expect("block exists");
1472        assert_eq!(returned_block.hash(), block_hash);
1473        assert!(bal.is_none());
1474        assert_eq!(bal_fetches.load(Ordering::SeqCst), 0);
1475
1476        assert!(cache.get_bal(block_hash).await.unwrap().is_some());
1477
1478        let (_, bal) = cache
1479            .get_recovered_block_and_maybe_bal(block_hash)
1480            .await
1481            .unwrap()
1482            .expect("block exists");
1483        assert!(bal.is_some());
1484        assert_eq!(bal_fetches.load(Ordering::SeqCst), 1);
1485    }
1486
1487    #[tokio::test]
1488    async fn insert_bal_populates_cache_without_provider_fetch() {
1489        let fetches = Arc::new(AtomicUsize::default());
1490        let provider = TestBalProvider::new(fetches.clone());
1491        let cache = EthStateCache::<EthPrimitives>::spawn_with(
1492            provider,
1493            EthStateCacheConfig { max_bals: 4, ..Default::default() },
1494            Runtime::test(),
1495        );
1496        let block_hash = B256::repeat_byte(0x68);
1497        cache.insert_bal(block_hash, test_decoded_evm_bal());
1498        assert!(cache.get_bal(block_hash).await.unwrap().is_some());
1499        assert_eq!(fetches.load(Ordering::SeqCst), 0);
1500    }
1501
1502    #[tokio::test]
1503    async fn insert_receipts_populates_cache_without_provider_fetch() {
1504        let cache = EthStateCache::<EthPrimitives>::spawn_with(
1505            TestBalProvider::default(),
1506            EthStateCacheConfig { max_receipts: 4, ..Default::default() },
1507            Runtime::test(),
1508        );
1509        let block_hash = B256::repeat_byte(0x69);
1510        let receipts = Arc::new(vec![Receipt::default()]);
1511
1512        // the provider has no receipts for the block, so they can only come from the insert.
1513        cache.insert_receipts(block_hash, receipts.clone());
1514        assert_eq!(cache.get_receipts(block_hash).await.unwrap(), Some(receipts));
1515    }
1516
1517    #[tokio::test]
1518    async fn canonical_chain_notification_caches_prepared_bal() {
1519        let fetches = Arc::new(AtomicUsize::default());
1520        let provider = TestBalProvider::new(fetches.clone());
1521        let cache = EthStateCache::<EthPrimitives>::spawn_with(
1522            provider,
1523            EthStateCacheConfig { max_blocks: 4, max_bals: 4, ..Default::default() },
1524            Runtime::test(),
1525        );
1526
1527        let block = test_block();
1528        let block_hash = block.hash();
1529        let block_number = block.number;
1530        let mut chain: Chain<EthPrimitives> = Chain::new(
1531            [block],
1532            ExecutionOutcome::new(Default::default(), vec![vec![]], block_number, vec![]),
1533            Default::default(),
1534        );
1535        chain.insert_bal(block_number, Arc::new(test_decoded_evm_bal()));
1536
1537        cache_new_blocks_task(
1538            cache.clone(),
1539            tokio_stream::iter([CanonStateNotification::Commit { new: Arc::new(chain) }]),
1540        )
1541        .await;
1542
1543        assert!(cache.get_bal(block_hash).await.unwrap().is_some());
1544        assert_eq!(fetches.load(Ordering::SeqCst), 0);
1545    }
1546
1547    #[reth_concurrency::test]
1548    async fn concurrent_get_bal_requests_share_fetch() {
1549        let fetches = Arc::new(AtomicUsize::default());
1550        let provider = TestBalProvider::new(fetches.clone());
1551        let cache = EthStateCache::<EthPrimitives>::spawn_with(
1552            provider,
1553            EthStateCacheConfig {
1554                max_blocks: 0,
1555                max_receipts: 0,
1556                max_bals: 4,
1557                cache_computed_bals: false,
1558                prewarm_bals: None,
1559                max_concurrent_db_requests: 1,
1560                max_cached_tx_hashes: 0,
1561                ..Default::default()
1562            },
1563            Runtime::test(),
1564        );
1565        let block_hash = B256::repeat_byte(0x77);
1566
1567        let (first, second) = tokio::join!(cache.get_bal(block_hash), cache.get_bal(block_hash));
1568
1569        assert!(first.unwrap().is_some());
1570        assert!(second.unwrap().is_some());
1571        assert_eq!(fetches.load(Ordering::SeqCst), 1);
1572    }
1573
1574    #[reth_concurrency::test]
1575    async fn panicking_fetch_reports_cache_service_unavailable() {
1576        let (started_tx, _started_rx) = mpsc::sync_channel(1);
1577        // The fetch unwraps a receive from this channel, so it panics once the sender is gone.
1578        let (_, release_rx) = mpsc::sync_channel(1);
1579        let cache = EthStateCache::<EthPrimitives>::spawn_with(
1580            TestBalProvider::new_blocking(started_tx, release_rx),
1581            EthStateCacheConfig { max_bals: 4, ..Default::default() },
1582            Runtime::test(),
1583        );
1584
1585        let err = cache.get_bal(B256::repeat_byte(0x78)).await.unwrap_err();
1586
1587        assert!(err.is_other::<CacheServiceUnavailable>());
1588    }
1589
1590    #[derive(Clone, Debug, Default)]
1591    struct TestBalProvider {
1592        bal_store: BalStoreHandle,
1593        block: Option<RecoveredBlock<Block>>,
1594    }
1595
1596    impl TestBalProvider {
1597        fn new(fetches: Arc<AtomicUsize>) -> Self {
1598            Self {
1599                bal_store: BalStoreHandle::new(TestBalStore { fetches, blocking_fetch: None }),
1600                block: None,
1601            }
1602        }
1603
1604        fn with_block(mut self, block: RecoveredBlock<Block>) -> Self {
1605            self.block = Some(block);
1606            self
1607        }
1608
1609        fn new_blocking(started: SyncSender<()>, release: Receiver<()>) -> Self {
1610            Self {
1611                bal_store: BalStoreHandle::new(TestBalStore {
1612                    fetches: Arc::new(AtomicUsize::default()),
1613                    blocking_fetch: Some(BlockingFetch { started, release: Mutex::new(release) }),
1614                }),
1615                block: None,
1616            }
1617        }
1618    }
1619
1620    impl BalProvider for TestBalProvider {
1621        fn bal_store(&self) -> &BalStoreHandle {
1622            &self.bal_store
1623        }
1624    }
1625
1626    #[derive(Debug)]
1627    struct TestBalStore {
1628        fetches: Arc<AtomicUsize>,
1629        blocking_fetch: Option<BlockingFetch>,
1630    }
1631
1632    #[derive(Debug)]
1633    struct BlockingFetch {
1634        started: SyncSender<()>,
1635        release: Mutex<Receiver<()>>,
1636    }
1637
1638    impl BalStore for TestBalStore {
1639        fn insert(&self, _num_hash: NumHash, _bal: reth_storage_api::RawBal) -> ProviderResult<()> {
1640            Ok(())
1641        }
1642
1643        fn prune(&self, _tip: BlockNumber) -> ProviderResult<usize> {
1644            Ok(0)
1645        }
1646
1647        fn get_by_hashes(&self, block_hashes: &[BlockHash]) -> ProviderResult<Vec<Option<Bytes>>> {
1648            self.fetches.fetch_add(1, Ordering::SeqCst);
1649            if let Some(blocking_fetch) = &self.blocking_fetch {
1650                blocking_fetch.started.send(()).unwrap();
1651                blocking_fetch.release.lock().unwrap().recv().unwrap();
1652            }
1653            Ok(block_hashes.iter().map(|_| Some(Bytes::from_static(&[0xc0]))).collect())
1654        }
1655    }
1656
1657    impl BlockHashReader for TestBalProvider {
1658        fn block_hash(&self, _number: BlockNumber) -> ProviderResult<Option<B256>> {
1659            Ok(None)
1660        }
1661
1662        fn canonical_hashes_range(
1663            &self,
1664            _start: BlockNumber,
1665            _end: BlockNumber,
1666        ) -> ProviderResult<Vec<B256>> {
1667            Ok(Vec::new())
1668        }
1669    }
1670
1671    impl BlockNumReader for TestBalProvider {
1672        fn chain_info(&self) -> ProviderResult<reth_chainspec::ChainInfo> {
1673            Ok(reth_chainspec::ChainInfo::default())
1674        }
1675
1676        fn best_block_number(&self) -> ProviderResult<BlockNumber> {
1677            Ok(0)
1678        }
1679
1680        fn last_block_number(&self) -> ProviderResult<BlockNumber> {
1681            Ok(0)
1682        }
1683
1684        fn block_number(&self, _hash: B256) -> ProviderResult<Option<BlockNumber>> {
1685            Ok(None)
1686        }
1687    }
1688
1689    impl HeaderProvider for TestBalProvider {
1690        type Header = Header;
1691
1692        fn header(&self, _block_hash: BlockHash) -> ProviderResult<Option<Self::Header>> {
1693            Ok(None)
1694        }
1695
1696        fn header_by_number(&self, _num: u64) -> ProviderResult<Option<Self::Header>> {
1697            Ok(None)
1698        }
1699
1700        fn headers_range(
1701            &self,
1702            _range: impl RangeBounds<BlockNumber>,
1703        ) -> ProviderResult<Vec<Self::Header>> {
1704            Ok(Vec::new())
1705        }
1706
1707        fn sealed_header(
1708            &self,
1709            _number: BlockNumber,
1710        ) -> ProviderResult<Option<SealedHeader<Self::Header>>> {
1711            Ok(None)
1712        }
1713
1714        fn sealed_headers_while(
1715            &self,
1716            _range: impl RangeBounds<BlockNumber>,
1717            _predicate: impl FnMut(&SealedHeader<Self::Header>) -> bool,
1718        ) -> ProviderResult<Vec<SealedHeader<Self::Header>>> {
1719            Ok(Vec::new())
1720        }
1721    }
1722
1723    impl BlockBodyIndicesProvider for TestBalProvider {
1724        fn block_body_indices(&self, _num: u64) -> ProviderResult<Option<StoredBlockBodyIndices>> {
1725            Ok(None)
1726        }
1727
1728        fn block_body_indices_range(
1729            &self,
1730            _range: RangeInclusive<BlockNumber>,
1731        ) -> ProviderResult<Vec<StoredBlockBodyIndices>> {
1732            Ok(Vec::new())
1733        }
1734    }
1735
1736    impl TransactionsProvider for TestBalProvider {
1737        type Transaction = TransactionSigned;
1738
1739        fn transaction_id(&self, _tx_hash: TxHash) -> ProviderResult<Option<TxNumber>> {
1740            Ok(None)
1741        }
1742
1743        fn transaction_by_id(&self, _id: TxNumber) -> ProviderResult<Option<Self::Transaction>> {
1744            Ok(None)
1745        }
1746
1747        fn transaction_by_id_unhashed(
1748            &self,
1749            _id: TxNumber,
1750        ) -> ProviderResult<Option<Self::Transaction>> {
1751            Ok(None)
1752        }
1753
1754        fn transaction_by_hash(&self, _hash: TxHash) -> ProviderResult<Option<Self::Transaction>> {
1755            Ok(None)
1756        }
1757
1758        fn transaction_by_hash_with_meta(
1759            &self,
1760            _hash: TxHash,
1761        ) -> ProviderResult<Option<(Self::Transaction, TransactionMeta)>> {
1762            Ok(None)
1763        }
1764
1765        fn transactions_by_block(
1766            &self,
1767            _block: BlockHashOrNumber,
1768        ) -> ProviderResult<Option<Vec<Self::Transaction>>> {
1769            Ok(None)
1770        }
1771
1772        fn transactions_by_block_range(
1773            &self,
1774            _range: impl RangeBounds<BlockNumber>,
1775        ) -> ProviderResult<Vec<Vec<Self::Transaction>>> {
1776            Ok(Vec::new())
1777        }
1778
1779        fn transactions_by_tx_range(
1780            &self,
1781            _range: impl RangeBounds<TxNumber>,
1782        ) -> ProviderResult<Vec<Self::Transaction>> {
1783            Ok(Vec::new())
1784        }
1785
1786        fn senders_by_tx_range(
1787            &self,
1788            _range: impl RangeBounds<TxNumber>,
1789        ) -> ProviderResult<Vec<Address>> {
1790            Ok(Vec::new())
1791        }
1792
1793        fn transaction_sender(&self, _id: TxNumber) -> ProviderResult<Option<Address>> {
1794            Ok(None)
1795        }
1796    }
1797
1798    impl ReceiptProvider for TestBalProvider {
1799        type Receipt = Receipt;
1800
1801        fn receipt(&self, _id: TxNumber) -> ProviderResult<Option<Self::Receipt>> {
1802            Ok(None)
1803        }
1804
1805        fn receipt_by_hash(&self, _hash: TxHash) -> ProviderResult<Option<Self::Receipt>> {
1806            Ok(None)
1807        }
1808
1809        fn receipts_by_block(
1810            &self,
1811            _block: BlockHashOrNumber,
1812        ) -> ProviderResult<Option<Vec<Self::Receipt>>> {
1813            Ok(None)
1814        }
1815
1816        fn receipts_by_tx_range(
1817            &self,
1818            _range: impl RangeBounds<TxNumber>,
1819        ) -> ProviderResult<Vec<Self::Receipt>> {
1820            Ok(Vec::new())
1821        }
1822
1823        fn receipts_by_block_range(
1824            &self,
1825            _block_range: RangeInclusive<BlockNumber>,
1826        ) -> ProviderResult<Vec<Vec<Self::Receipt>>> {
1827            Ok(Vec::new())
1828        }
1829    }
1830
1831    impl BlockReader for TestBalProvider {
1832        type Block = Block;
1833
1834        fn find_block_by_hash(
1835            &self,
1836            _hash: B256,
1837            _source: BlockSource,
1838        ) -> ProviderResult<Option<Self::Block>> {
1839            Ok(None)
1840        }
1841
1842        fn block(&self, _id: BlockHashOrNumber) -> ProviderResult<Option<Self::Block>> {
1843            Ok(None)
1844        }
1845
1846        fn pending_block(&self) -> ProviderResult<Option<Arc<RecoveredBlock<Self::Block>>>> {
1847            Ok(None)
1848        }
1849
1850        fn pending_block_and_receipts(
1851            &self,
1852        ) -> ProviderResult<Option<RecoveredBlockAndExecutionOutput<Self::Block, Self::Receipt>>>
1853        {
1854            Ok(None)
1855        }
1856
1857        fn recovered_block(
1858            &self,
1859            _id: BlockHashOrNumber,
1860            _transaction_kind: TransactionVariant,
1861        ) -> ProviderResult<Option<RecoveredBlock<Self::Block>>> {
1862            Ok(None)
1863        }
1864
1865        fn sealed_block_with_senders(
1866            &self,
1867            _id: BlockHashOrNumber,
1868            _transaction_kind: TransactionVariant,
1869        ) -> ProviderResult<Option<RecoveredBlock<Self::Block>>> {
1870            Ok(self.block.clone())
1871        }
1872
1873        fn block_range(
1874            &self,
1875            _range: RangeInclusive<BlockNumber>,
1876        ) -> ProviderResult<Vec<Self::Block>> {
1877            Ok(Vec::new())
1878        }
1879
1880        fn block_with_senders_range(
1881            &self,
1882            _range: RangeInclusive<BlockNumber>,
1883        ) -> ProviderResult<Vec<RecoveredBlock<Self::Block>>> {
1884            Ok(Vec::new())
1885        }
1886
1887        fn recovered_block_range(
1888            &self,
1889            _range: RangeInclusive<BlockNumber>,
1890        ) -> ProviderResult<Vec<RecoveredBlock<Self::Block>>> {
1891            Ok(Vec::new())
1892        }
1893
1894        fn block_by_transaction_id(&self, _id: TxNumber) -> ProviderResult<Option<BlockNumber>> {
1895            Ok(None)
1896        }
1897    }
1898}