Skip to main content

reth_rpc/eth/
filter.rs

1//! `eth_` `Filter` RPC handler implementation
2
3use alloy_consensus::{transaction::TxHashRef, BlockHeader, TxReceipt};
4use alloy_eips::BlockNumberOrTag;
5use alloy_primitives::{Sealable, TxHash};
6use alloy_rpc_types_eth::{
7    error::EthRpcErrorCode, Filter, FilterBlockOption, FilterChanges, FilterId,
8    PendingTransactionFilterKind,
9};
10use async_trait::async_trait;
11use futures::{
12    future::TryFutureExt,
13    stream::{FuturesOrdered, StreamExt},
14    Future,
15};
16use itertools::Itertools;
17use jsonrpsee::{core::RpcResult, server::IdProvider};
18use reth_errors::ProviderError;
19use reth_primitives_traits::{NodePrimitives, SealedHeader};
20use reth_rpc_eth_api::{
21    helpers::{EthBlocks, LoadReceipt},
22    EngineEthFilter, EthApiTypes, EthFilterApiServer, FullEthApiTypes, QueryLimits, RpcConvert,
23    RpcLog, RpcNodeCoreExt, RpcTransaction,
24};
25use reth_rpc_eth_types::{
26    logs_utils::{self, append_matching_block_logs, ProviderOrBlock},
27    EthApiError, EthFilterConfig, EthStateCache, EthSubscriptionIdProvider,
28};
29use reth_rpc_server_types::{result::rpc_error_with_code, ToRpcResult};
30use reth_storage_api::{
31    BlockHashReader, BlockIdReader, BlockNumReader, BlockReader, HeaderProvider, ProviderBlock,
32    ProviderReceipt, ReceiptProvider, TransactionsProvider,
33};
34use reth_tasks::Runtime;
35use reth_transaction_pool::{PoolTransaction, TransactionPool, ValidPoolTransaction};
36use std::{
37    collections::{HashMap, VecDeque},
38    fmt,
39    iter::{Peekable, StepBy},
40    ops::RangeInclusive,
41    pin::Pin,
42    sync::{Arc, OnceLock},
43    time::{Duration, Instant},
44};
45use tokio::{
46    sync::{
47        broadcast::{self, error::TryRecvError},
48        oneshot, Mutex,
49    },
50    time::MissedTickBehavior,
51};
52use tokio_stream::{wrappers::ReceiverStream, Stream};
53use tracing::{debug, error, trace};
54
55impl<Eth> EngineEthFilter<RpcLog<Eth::NetworkTypes>> for EthFilter<Eth>
56where
57    Eth: FullEthApiTypes + RpcNodeCoreExt<Provider: BlockIdReader> + LoadReceipt + EthBlocks,
58{
59    /// Returns logs matching given filter object, no query limits
60    fn logs(
61        &self,
62        filter: Filter,
63        limits: QueryLimits,
64    ) -> impl Future<Output = RpcResult<Vec<RpcLog<Eth::NetworkTypes>>>> + Send {
65        trace!(target: "rpc::eth", "Serving eth_getLogs");
66        self.logs_for_filter(filter, limits).map_err(|e| e.into())
67    }
68}
69
70/// The JSON-RPC error code for exceeding a limit, as defined by EIP-1474.
71const LIMIT_EXCEEDED_CODE: i32 = -32005;
72
73/// How many times per `stale_filter_ttl` expired filters are evicted.
74///
75/// Expired filters count against the active filter limit until a sweep removes them, so this
76/// bounds how long past its TTL an abandoned filter can hold a slot.
77const STALE_FILTER_SWEEPS_PER_TTL: u32 = 4;
78
79/// Upper bound on the capacity of a [`TxFeed`].
80///
81/// Unlike the pool's listener channels, a broadcast channel allocates all of its slots up front, so
82/// following an arbitrarily large configured listener buffer could allocate gigabytes for the first
83/// pending filter.
84const MAX_TX_FEED_CAPACITY: usize = 1 << 16;
85
86/// Threshold for deciding between cached and range mode processing
87const CACHED_MODE_BLOCK_THRESHOLD: u64 = 250;
88
89/// Threshold for bloom filter matches that triggers reduced caching
90const HIGH_BLOOM_MATCH_THRESHOLD: usize = 20;
91
92/// Threshold for bloom filter matches that triggers moderately reduced caching
93const MODERATE_BLOOM_MATCH_THRESHOLD: usize = 10;
94
95/// Minimum block count to apply bloom filter match adjustments
96const BLOOM_ADJUSTMENT_MIN_BLOCKS: u64 = 100;
97
98/// The maximum number of headers we read at once when handling a range filter.
99const MAX_HEADERS_RANGE: u64 = 1_000; // with ~530bytes per header this is ~500kb
100
101// Cached mode is only reachable for ranges that fit into a single header window, which is what
102// keeps the mode decision independent of how a range is split.
103const _: () = assert!(CACHED_MODE_BLOCK_THRESHOLD <= MAX_HEADERS_RANGE);
104
105/// Minimum number of bloom matching blocks in a header window for fetching their receipts in
106/// parallel
107const PARALLEL_PROCESSING_THRESHOLD: usize = 1000;
108
109/// Default concurrency for parallel processing
110const DEFAULT_PARALLEL_CONCURRENCY: usize = 4;
111
112/// Maximum number of blocks whose receipts the parallel fetching holds in memory at once
113const MAX_PARALLEL_BATCH_SIZE: usize = 256;
114
115/// Lower bound on the JSON size in bytes of a log without its topics and data: the field names,
116/// the address and the block and transaction hashes.
117const MIN_LOG_JSON_SIZE: usize = 300;
118
119/// Upper bound on the JSON size in bytes of a log without the hex digits of its topics and data:
120/// every quantity at its widest, the quotes, prefixes and separators of four topics, and the
121/// separator to the next log.
122const MAX_LOG_JSON_SIZE: usize = 436;
123
124/// Allowance in bytes for the JSON-RPC envelope around the logs of a response, enough for request
125/// ids of up to 90 bytes.
126const MAX_RESPONSE_ENVELOPE_SIZE: usize = 128;
127
128/// `Eth` filter RPC implementation.
129///
130/// This type handles `eth_` rpc requests related to filters (`eth_getLogs`).
131pub struct EthFilter<Eth: EthApiTypes> {
132    /// All nested fields bundled together
133    inner: Arc<EthFilterInner<Eth>>,
134}
135
136impl<Eth> Clone for EthFilter<Eth>
137where
138    Eth: EthApiTypes,
139{
140    fn clone(&self) -> Self {
141        Self { inner: self.inner.clone() }
142    }
143}
144
145impl<Eth> EthFilter<Eth>
146where
147    Eth: EthApiTypes + 'static,
148{
149    /// Creates a new, shareable instance.
150    ///
151    /// This uses the given pool to get notified about new transactions, the provider to interact
152    /// with the blockchain, the cache to fetch cacheable data, like the logs.
153    ///
154    /// See also [`EthFilterConfig`].
155    ///
156    /// This also spawns a task that periodically clears stale filters.
157    ///
158    /// # Create a new instance with [`EthApi`](crate::EthApi)
159    ///
160    /// ```no_run
161    /// use reth_evm_ethereum::EthEvmConfig;
162    /// use reth_network_api::noop::NoopNetwork;
163    /// use reth_provider::noop::NoopProvider;
164    /// use reth_rpc::{EthApi, EthFilter};
165    /// use reth_tasks::Runtime;
166    /// use reth_transaction_pool::noop::NoopTransactionPool;
167    /// let eth_api = EthApi::builder(
168    ///     NoopProvider::default(),
169    ///     NoopTransactionPool::default(),
170    ///     NoopNetwork::default(),
171    ///     EthEvmConfig::mainnet(),
172    /// )
173    /// .build();
174    /// let filter = EthFilter::new(eth_api, Default::default(), Runtime::test());
175    /// ```
176    pub fn new(eth_api: Eth, config: EthFilterConfig, task_spawner: Runtime) -> Self {
177        let EthFilterConfig {
178            max_blocks_per_filter,
179            max_logs_per_response,
180            stale_filter_ttl,
181            max_response_size,
182            max_active_filters,
183        } = config;
184        let inner = EthFilterInner {
185            eth_api,
186            active_filters: ActiveFilters::new(),
187            max_active_filters,
188            pending_transaction_hashes: Arc::new(TxFeed::new()),
189            full_pending_transactions: OnceLock::new(),
190            id_provider: Arc::new(EthSubscriptionIdProvider::default()),
191            max_headers_range: MAX_HEADERS_RANGE,
192            task_spawner,
193            stale_filter_ttl,
194            query_limits: QueryLimits {
195                max_blocks_per_filter,
196                max_logs_per_response,
197                max_response_size,
198            },
199        };
200
201        let eth_filter = Self { inner: Arc::new(inner) };
202
203        let this = eth_filter.clone();
204        eth_filter.inner.task_spawner.spawn_critical_task(
205            "eth-filters_stale-filters-clean",
206            async move {
207                this.watch_and_clear_stale_filters().await;
208            },
209        );
210
211        eth_filter
212    }
213
214    /// Returns all currently active filters
215    pub fn active_filters(&self) -> &ActiveFilters<RpcTransaction<Eth::NetworkTypes>> {
216        &self.inner.active_filters
217    }
218
219    /// Endless future that [`Self::clear_stale_filters`] [`STALE_FILTER_SWEEPS_PER_TTL`] times per
220    /// `stale_filter_ttl`.
221    /// Nonetheless, this endless future frees the thread at every await point.
222    async fn watch_and_clear_stale_filters(&self) {
223        // `interval_at` panics on a zero period, which a tiny TTL truncates to, and the timer does
224        // not resolve below a millisecond.
225        let period = (self.inner.stale_filter_ttl / STALE_FILTER_SWEEPS_PER_TTL)
226            .max(Duration::from_millis(1));
227        let mut interval = tokio::time::interval_at(tokio::time::Instant::now() + period, period);
228        interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
229        loop {
230            interval.tick().await;
231            self.clear_stale_filters(Instant::now()).await;
232        }
233    }
234
235    /// Clears all filters that have not been polled for longer than the configured
236    /// `stale_filter_ttl` at the given instant.
237    pub async fn clear_stale_filters(&self, now: Instant) {
238        trace!(target: "rpc::eth", "clear stale filters");
239        let mut filters = self.active_filters().inner.lock().await;
240        filters.retain(|id, filter| {
241            let is_valid = (now - filter.last_poll_timestamp) < self.inner.stale_filter_ttl;
242
243            if !is_valid {
244                trace!(target: "rpc::eth", "evict filter with id: {:?}", id);
245            }
246
247            is_valid
248        });
249        filters.shrink_to_fit();
250    }
251}
252
253impl<Eth> EthFilter<Eth>
254where
255    Eth: FullEthApiTypes<Provider: BlockReader + BlockIdReader> + LoadReceipt + EthBlocks,
256{
257    /// Access the underlying provider.
258    fn provider(&self) -> &Eth::Provider {
259        self.inner.eth_api.provider()
260    }
261
262    /// Access the underlying pool.
263    fn pool(&self) -> &Eth::Pool {
264        self.inner.eth_api.pool()
265    }
266
267    /// Returns all the filter changes for the given id, if any
268    pub async fn filter_changes(
269        &self,
270        id: FilterId,
271    ) -> Result<
272        FilterChanges<RpcTransaction<Eth::NetworkTypes>, RpcLog<Eth::NetworkTypes>>,
273        EthFilterError,
274    > {
275        let best_number = self.provider().chain_info()?.best_number;
276
277        // start_block is the first block the filter has not delivered changes for yet
278        let (start_block, kind) = {
279            let mut filters = self.inner.active_filters.inner.lock().await;
280            let filter =
281                filters.get_mut(&id).ok_or_else(|| EthFilterError::FilterNotFound(id.clone()))?;
282            filter.last_poll_timestamp = Instant::now();
283
284            // Pending transactions arrive between blocks, so only block and log filters can skip a
285            // poll without a new block.
286            if filter.block > best_number &&
287                matches!(filter.kind, FilterKind::Block | FilterKind::Log(_))
288            {
289                // no new blocks since the last poll
290                return Ok(FilterChanges::Empty)
291            }
292
293            (filter.block, filter.kind.clone())
294        };
295
296        match kind {
297            FilterKind::PendingTransaction(filter) => Ok(match filter.drain().await {
298                FilterChanges::Empty => FilterChanges::Empty,
299                FilterChanges::Hashes(hashes) => FilterChanges::Hashes(hashes),
300                FilterChanges::Transactions(transactions) => {
301                    FilterChanges::Transactions(transactions)
302                }
303                FilterChanges::Logs(_) => unreachable!("pending transaction filter returned logs"),
304            }),
305            FilterKind::Block => {
306                // Note: we need to fetch the block hashes from inclusive range
307                // [start_block..best_block]
308                let end_block = best_number + 1;
309                let block_hashes =
310                    self.provider().canonical_hashes_range(start_block, end_block).map_err(
311                        |_| EthApiError::HeaderRangeNotFound(start_block.into(), end_block.into()),
312                    )?;
313                self.advance_filter_cursor(&id, end_block).await;
314                Ok(FilterChanges::Hashes(block_hashes))
315            }
316            FilterKind::Log(filter) => {
317                let mut limits = self.inner.query_limits;
318                // A poll acknowledges what it returns, so it only returns logs that fit the
319                // response size limit at their largest encoding. The scan checks a lower bound,
320                // which is at least `MIN_LOG_JSON_SIZE / MAX_LOG_JSON_SIZE` of that.
321                limits.max_response_size = limits.max_response_size.map(|max| {
322                    max.saturating_sub(MAX_RESPONSE_ENVELOPE_SIZE) / MAX_LOG_JSON_SIZE *
323                        MIN_LOG_JSON_SIZE
324                });
325                let (from_block_number, to_block_number) = match filter.block_option {
326                    FilterBlockOption::Range { from_block, to_block } => {
327                        // `latest` and `pending` don't bound a poll, it covers the blocks since
328                        // the last poll
329                        let bound = |num: Option<BlockNumberOrTag>| {
330                            num.filter(|num| !num.is_latest() && !num.is_pending())
331                                .map(|num| self.provider().convert_block_number(num))
332                                .transpose()
333                                .map(Option::flatten)
334                        };
335                        let (from, to) = (bound(from_block)?, bound(to_block)?);
336                        // a filter whose own range is invalid keeps reporting that, it is not a
337                        // range the cursor has exhausted
338                        if let (Some(from), Some(to)) = (from, to) &&
339                            from > to
340                        {
341                            return Err(EthFilterError::InvalidBlockRangeParams)
342                        }
343
344                        // only the blocks since the last poll, clamped to the filter's own range
345                        (
346                            from.map_or(start_block, |from| from.max(start_block)),
347                            to.map_or(best_number, |to| to.min(best_number)),
348                        )
349                    }
350                    FilterBlockOption::AtBlockHash(_) => {
351                        // The block is read by its hash, so a reorg cannot make the poll return the
352                        // logs of the block that replaced it. Once delivered, no later poll has
353                        // anything to return, since the block never changes.
354                        let logs = self.inner.clone().logs_for_filter(*filter, limits).await?;
355                        self.advance_filter_cursor(&id, u64::MAX).await;
356                        return Ok(FilterChanges::Logs(logs))
357                    }
358                };
359                if from_block_number > to_block_number {
360                    // the filter's range contains no block since the last poll
361                    return Ok(FilterChanges::Empty)
362                }
363
364                // a poll delivers at most the configured block cap, the next poll continues from
365                // there
366                let to_block_number = limits.max_blocks_per_filter.map_or(to_block_number, |max| {
367                    to_block_number.min(from_block_number.saturating_add(max))
368                });
369                let (logs, delivered_to) = match self
370                    .inner
371                    .clone()
372                    .get_logs_in_block_range(
373                        *filter.clone(),
374                        from_block_number,
375                        to_block_number,
376                        limits,
377                    )
378                    .await
379                {
380                    Ok(logs) => (logs, to_block_number),
381                    Err(
382                        EthFilterError::QueryExceedsMaxResults { to_block, .. } |
383                        EthFilterError::QueryExceedsMaxResponseSize { to_block, .. },
384                    ) => {
385                        // deliver the prefix of blocks that fits under the log cap and the
386                        // response size, the next poll continues from there
387                        let logs = self
388                            .inner
389                            .clone()
390                            .get_logs_in_block_range(*filter, from_block_number, to_block, limits)
391                            .await?;
392                        (logs, to_block)
393                    }
394                    Err(err @ EthFilterError::ReceiptsUnavailable(_)) => {
395                        // Pruned receipts do not come back, so a retry would fail the same way on
396                        // every later poll. The error reports the gap and the next poll continues
397                        // after this poll's range.
398                        self.advance_filter_cursor(&id, to_block_number + 1).await;
399                        return Err(err)
400                    }
401                    Err(err) => return Err(err),
402                };
403                self.advance_filter_cursor(&id, delivered_to + 1).await;
404                Ok(FilterChanges::Logs(logs))
405            }
406        }
407    }
408
409    /// Moves the cursor of the filter with the given id to `next`, the first block a subsequent
410    /// poll returns changes for, or `u64::MAX` once the filter has nothing left to deliver.
411    ///
412    /// This runs after the changes were fetched so that a failed poll is retried by the next one.
413    /// A poll therefore delivers its range at least once: two polls of the same filter that run
414    /// concurrently both cover the range neither of them has acknowledged yet.
415    ///
416    /// There are two exceptions. A single block whose logs alone exceed the response size limit is
417    /// returned whole, as `eth_getLogs` does for one block, so the cursor moves past it although
418    /// the transport may reject the response. A poll that fails because receipts in its range were
419    /// pruned moves the cursor past that range, since every retry would fail the same way.
420    async fn advance_filter_cursor(&self, id: &FilterId, next: u64) {
421        let mut filters = self.inner.active_filters.inner.lock().await;
422        if let Some(filter) = filters.get_mut(id) {
423            filter.block = filter.block.max(next);
424        }
425    }
426
427    /// Returns an array of all logs matching filter with given id.
428    ///
429    /// Returns an error if no matching log filter exists.
430    ///
431    /// Handler for `eth_getFilterLogs`
432    pub async fn filter_logs(
433        &self,
434        id: FilterId,
435    ) -> Result<Vec<RpcLog<Eth::NetworkTypes>>, EthFilterError> {
436        let filter = {
437            let mut filters = self.inner.active_filters.inner.lock().await;
438            let filter =
439                filters.get_mut(&id).ok_or_else(|| EthFilterError::FilterNotFound(id.clone()))?;
440            if let FilterKind::Log(ref inner_filter) = filter.kind {
441                filter.last_poll_timestamp = Instant::now();
442                *inner_filter.clone()
443            } else {
444                // Not a log filter
445                return Err(EthFilterError::FilterNotFound(id))
446            }
447        };
448
449        self.logs_for_filter(filter, self.inner.query_limits).await
450    }
451
452    /// Returns logs matching given filter object.
453    async fn logs_for_filter(
454        &self,
455        filter: Filter,
456        limits: QueryLimits,
457    ) -> Result<Vec<RpcLog<Eth::NetworkTypes>>, EthFilterError> {
458        self.inner.clone().logs_for_filter(filter, limits).await
459    }
460}
461
462impl<Eth> EthFilterApiServer<RpcTransaction<Eth::NetworkTypes>, RpcLog<Eth::NetworkTypes>>
463    for EthFilter<Eth>
464where
465    Eth: FullEthApiTypes + LoadReceipt + EthBlocks,
466{
467    /// Handler for `eth_newFilter`
468    async fn new_filter(&self, filter: Filter) -> RpcResult<FilterId> {
469        trace!(target: "rpc::eth", "Serving eth_newFilter");
470        self.inner.install_filter(|| FilterKind::Log(Box::new(filter))).await
471    }
472
473    /// Handler for `eth_newBlockFilter`
474    async fn new_block_filter(&self) -> RpcResult<FilterId> {
475        trace!(target: "rpc::eth", "Serving eth_newBlockFilter");
476        self.inner.install_filter(|| FilterKind::Block).await
477    }
478
479    /// Handler for `eth_newPendingTransactionFilter`
480    async fn new_pending_transaction_filter(
481        &self,
482        kind: Option<PendingTransactionFilterKind>,
483    ) -> RpcResult<FilterId> {
484        trace!(target: "rpc::eth", "Serving eth_newPendingTransactionFilter");
485
486        let kind = kind.unwrap_or_default();
487
488        // The filter only subscribes to its feed once it is within the filter limit, so a rejected
489        // request neither starts a feed nor leaves a receiver behind.
490        self.inner
491            .install_filter(|| {
492                FilterKind::PendingTransaction(match kind {
493                    PendingTransactionFilterKind::Hashes => {
494                        PendingTransactionKind::Hashes(PendingTransactionsReceiver::new(
495                            self.inner.pending_transaction_hashes.subscribe(
496                                &self.inner.task_spawner,
497                                || {
498                                    let listener = self.pool().pending_transactions_listener();
499                                    let capacity = listener.max_capacity();
500                                    (ReceiverStream::new(listener), capacity)
501                                },
502                            ),
503                        ))
504                    }
505                    PendingTransactionFilterKind::Full => {
506                        let feed = self.inner.full_pending_transactions.get_or_init(|| {
507                            Arc::new(PoolFullTransactionsFeed::new(
508                                self.pool().clone(),
509                                dyn_clone::clone(self.inner.eth_api.converter()),
510                            ))
511                        });
512                        PendingTransactionKind::FullTransaction(
513                            feed.subscribe(&self.inner.task_spawner),
514                        )
515                    }
516                })
517            })
518            .await
519    }
520
521    /// Handler for `eth_getFilterChanges`
522    async fn filter_changes(
523        &self,
524        id: FilterId,
525    ) -> RpcResult<FilterChanges<RpcTransaction<Eth::NetworkTypes>, RpcLog<Eth::NetworkTypes>>>
526    {
527        trace!(target: "rpc::eth", "Serving eth_getFilterChanges");
528        Ok(Self::filter_changes(self, id).await?)
529    }
530
531    /// Returns an array of all logs matching filter with given id.
532    ///
533    /// Returns an error if no matching log filter exists.
534    ///
535    /// Handler for `eth_getFilterLogs`
536    async fn filter_logs(&self, id: FilterId) -> RpcResult<Vec<RpcLog<Eth::NetworkTypes>>> {
537        trace!(target: "rpc::eth", "Serving eth_getFilterLogs");
538        Ok(Self::filter_logs(self, id).await?)
539    }
540
541    /// Handler for `eth_uninstallFilter`
542    async fn uninstall_filter(&self, id: FilterId) -> RpcResult<bool> {
543        trace!(target: "rpc::eth", "Serving eth_uninstallFilter");
544        let mut filters = self.inner.active_filters.inner.lock().await;
545        if filters.remove(&id).is_some() {
546            trace!(target: "rpc::eth::filter", ?id, "uninstalled filter");
547            Ok(true)
548        } else {
549            Ok(false)
550        }
551    }
552
553    /// Returns logs matching given filter object.
554    ///
555    /// Handler for `eth_getLogs`
556    async fn logs(&self, filter: Filter) -> RpcResult<Vec<RpcLog<Eth::NetworkTypes>>> {
557        trace!(target: "rpc::eth", "Serving eth_getLogs");
558        Ok(self.logs_for_filter(filter, self.inner.query_limits).await?)
559    }
560}
561
562impl<Eth> std::fmt::Debug for EthFilter<Eth>
563where
564    Eth: EthApiTypes,
565{
566    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
567        f.debug_struct("EthFilter").finish_non_exhaustive()
568    }
569}
570
571/// Container type `EthFilter`
572#[derive(Debug)]
573struct EthFilterInner<Eth: EthApiTypes> {
574    /// Inner `eth` API implementation.
575    eth_api: Eth,
576    /// All currently installed filters.
577    active_filters: ActiveFilters<RpcTransaction<Eth::NetworkTypes>>,
578    /// Maximum number of installed filters, `None` if unlimited.
579    max_active_filters: Option<usize>,
580    /// The hashes of new pending transactions, shared by all pending transaction hash filters.
581    pending_transaction_hashes: Arc<TxFeed<TxHash>>,
582    /// The new pending transactions, shared by all full pending transaction filters.
583    ///
584    /// Filled by the first such filter, because the pool's transaction type is not known to this
585    /// type.
586    full_pending_transactions:
587        OnceLock<Arc<dyn FullTransactionsFeed<RpcTransaction<Eth::NetworkTypes>>>>,
588    /// Provides ids to identify filters
589    id_provider: Arc<dyn IdProvider>,
590    /// limits for logs queries
591    query_limits: QueryLimits,
592    /// maximum number of headers to read at once for range filter
593    max_headers_range: u64,
594    /// The type that can spawn tasks.
595    task_spawner: Runtime,
596    /// Duration since the last filter poll, after which the filter is considered stale
597    stale_filter_ttl: Duration,
598}
599
600impl<Eth> EthFilterInner<Eth>
601where
602    Eth: RpcNodeCoreExt<Provider: BlockIdReader, Pool: TransactionPool>
603        + EthApiTypes<NetworkTypes: reth_rpc_eth_api::types::RpcTypes>
604        + LoadReceipt
605        + EthBlocks,
606{
607    /// Access the underlying provider.
608    fn provider(&self) -> &Eth::Provider {
609        self.eth_api.provider()
610    }
611
612    /// Access the underlying [`EthStateCache`].
613    fn eth_cache(&self) -> &EthStateCache<Eth::Primitives> {
614        self.eth_api.cache()
615    }
616
617    /// Returns logs matching given filter object.
618    async fn logs_for_filter(
619        self: Arc<Self>,
620        filter: Filter,
621        limits: QueryLimits,
622    ) -> Result<Vec<RpcLog<Eth::NetworkTypes>>, EthFilterError> {
623        match filter.block_option {
624            FilterBlockOption::AtBlockHash(block_hash) => {
625                // Only take what the cache already holds, so that the receipts of a block whose
626                // bloom rules out the filter are never read.
627                let (maybe_block, receipts) =
628                    self.eth_cache().maybe_cached_block_and_receipts(block_hash).await?;
629
630                // With the block in the cache, serving its logs needs no further reads besides
631                // the receipts, which the cache reads on its own blocking tasks.
632                if let Some(block) = maybe_block {
633                    let header = block.clone_sealed_header();
634                    if !Self::block_logs_may_match(self.provider(), &filter, &header)? {
635                        return Ok(Vec::new())
636                    }
637                    let receipts = match receipts {
638                        Some(receipts) => receipts,
639                        None => self
640                            .eth_cache()
641                            .get_receipts(block_hash)
642                            .await?
643                            .ok_or_else(|| Self::missing_receipts(self.provider(), &header))?,
644                    };
645
646                    let mut all_logs = Vec::new();
647                    append_matching_block_logs(
648                        &mut all_logs,
649                        self.eth_api.converter(),
650                        ProviderOrBlock::<Eth::Provider>::Block(block),
651                        &filter,
652                        &header,
653                        &receipts,
654                        false,
655                    )?;
656                    return Ok(all_logs)
657                }
658
659                // Everything else is read from the provider on one blocking task, which shares the
660                // budget for blocking IO requests with the range scans instead of blocking an
661                // executor thread.
662                let cache = self.eth_cache().clone();
663                self.spawn_blocking_io_with_permit(move |eth_api| {
664                    let provider = eth_api.provider();
665                    let header = provider
666                        .sealed_header_by_hash(block_hash)?
667                        .ok_or(ProviderError::HeaderNotFound(block_hash.into()))?;
668                    if !Self::block_logs_may_match(provider, &filter, &header)? {
669                        return Ok(Vec::new())
670                    }
671                    let receipts = match receipts {
672                        Some(receipts) => receipts,
673                        None => {
674                            let receipts = Arc::new(
675                                provider
676                                    .receipts_by_block(block_hash.into())?
677                                    .ok_or_else(|| Self::missing_receipts(provider, &header))?,
678                            );
679                            // Kept for later queries of this block, as a read through the cache
680                            // would.
681                            cache.insert_receipts(block_hash, receipts.clone());
682                            receipts
683                        }
684                    };
685                    Self::block_logs_from_provider(&eth_api, &filter, &header, &receipts)
686                })
687                .await
688            }
689            FilterBlockOption::Range { from_block, to_block } => {
690                // Handle special case where from block is pending
691                if from_block.is_some_and(|b| b.is_pending()) {
692                    let to_block = to_block.unwrap_or(BlockNumberOrTag::Pending);
693                    if !(to_block.is_pending() || to_block.is_number()) {
694                        // always empty range
695                        return Ok(Vec::new());
696                    }
697                    // Try to get pending block and receipts
698                    if let Ok(Some(pending_block)) = self.eth_api.local_pending_block().await {
699                        if let BlockNumberOrTag::Number(to_block) = to_block &&
700                            to_block < pending_block.block.number()
701                        {
702                            // this block range is empty based on the user input
703                            return Ok(Vec::new());
704                        }
705
706                        let info = self.provider().chain_info()?;
707                        if pending_block.block.number() > info.best_number {
708                            // only consider the pending block if it is ahead of the chain
709                            let mut all_logs = Vec::new();
710                            let header = pending_block.block.clone_sealed_header();
711                            append_matching_block_logs(
712                                &mut all_logs,
713                                self.eth_api.converter(),
714                                ProviderOrBlock::<Eth::Provider>::Block(pending_block.block),
715                                &filter,
716                                &header,
717                                &pending_block.receipts,
718                                false, // removed = false for pending blocks
719                            )?;
720                            return Ok(all_logs)
721                        }
722                    }
723                }
724
725                let info = self.provider().chain_info()?;
726                let start_block = info.best_number;
727                // Without a pending block to serve, a `pending` bound resolves to the head on both
728                // ends instead of to whatever payload the engine currently holds
729                let from = from_block
730                    .filter(|num| !num.is_pending())
731                    .map(|num| self.provider().convert_block_number(num))
732                    .transpose()?
733                    .flatten();
734                let to = to_block
735                    .filter(|num| !num.is_pending())
736                    .map(|num| self.provider().convert_block_number(num))
737                    .transpose()?
738                    .flatten();
739
740                // Return error if toBlock exceeds current head
741                if let Some(t) = to &&
742                    t > info.best_number
743                {
744                    return Err(EthFilterError::BlockRangeExceedsHead {
745                        requested: t,
746                        head: info.best_number,
747                    });
748                }
749
750                let (from_block_number, to_block_number) =
751                    logs_utils::get_filter_block_range(from, to, start_block, info)?;
752
753                // Check if the requested range overlaps with pruned history (EIP-4444)
754                let earliest_block = self.provider().earliest_block_number()?;
755                if from_block_number < earliest_block {
756                    return Err(EthApiError::PrunedHistoryUnavailable {
757                        requested: from_block_number,
758                        earliest_available: earliest_block,
759                    }
760                    .into());
761                }
762
763                self.get_logs_in_block_range(filter, from_block_number, to_block_number, limits)
764                    .await
765            }
766        }
767    }
768
769    /// Installs the filter that `kind` returns and returns the new identifier.
770    ///
771    /// Returns [`EthFilterError::TooManyFilters`] without calling `kind` if the maximum number of
772    /// active filters is reached. The limit check and the insertion happen under the same lock, so
773    /// concurrent requests cannot exceed it, and `kind` runs under that lock, so it must not wait.
774    async fn install_filter(
775        &self,
776        kind: impl FnOnce() -> FilterKind<RpcTransaction<Eth::NetworkTypes>>,
777    ) -> RpcResult<FilterId> {
778        let last_poll_block_number = self.provider().best_block_number().to_rpc_result()?;
779        let subscription_id = self.id_provider.next_id();
780
781        let id = match subscription_id {
782            jsonrpsee_types::SubscriptionId::Num(n) => FilterId::Num(n),
783            jsonrpsee_types::SubscriptionId::Str(s) => FilterId::Str(s.into_owned()),
784        };
785        let mut filters = self.active_filters.inner.lock().await;
786        if let Some(max) = self.max_active_filters &&
787            filters.len() >= max
788        {
789            return Err(EthFilterError::TooManyFilters(max).into())
790        }
791        filters.insert(
792            id.clone(),
793            ActiveFilter {
794                block: last_poll_block_number,
795                last_poll_timestamp: Instant::now(),
796                kind: kind(),
797            },
798        );
799        Ok(id)
800    }
801
802    /// Returns all logs in the given _inclusive_ range that match the filter
803    ///
804    /// Returns an error if:
805    ///  - underlying database error
806    ///  - amount of matches exceeds configured limit
807    async fn get_logs_in_block_range(
808        self: Arc<Self>,
809        filter: Filter,
810        from_block: u64,
811        to_block: u64,
812        limits: QueryLimits,
813    ) -> Result<Vec<RpcLog<Eth::NetworkTypes>>, EthFilterError> {
814        trace!(target: "rpc::eth::filter", from=from_block, to=to_block, ?filter, "finding logs in range");
815
816        // perform boundary checks first
817        if to_block < from_block {
818            return Err(EthFilterError::InvalidBlockRangeParams)
819        }
820
821        if let Some(max_blocks_per_filter) =
822            limits.max_blocks_per_filter.filter(|limit| to_block - from_block > *limit)
823        {
824            return Err(EthFilterError::QueryExceedsMaxBlocks(max_blocks_per_filter))
825        }
826
827        // The scan occupies a blocking thread until it completes, so it shares the budget for
828        // blocking IO requests with `eth_call` and friends instead of pinning an unbounded number
829        // of pool threads.
830        let permit = self
831            .eth_api
832            .acquire_owned_blocking_io()
833            .await
834            .map_err(|_| EthFilterError::InternalError)?;
835
836        let (mut tx, rx) = oneshot::channel();
837        let this = self.clone();
838        self.task_spawner.spawn_blocking_task(async move {
839            let _permit = permit;
840            let fut = this.get_logs_in_block_range_inner(&filter, from_block, to_block, limits);
841            tokio::pin!(fut);
842            let res = tokio::select! {
843                // Range scans perform blocking reads before their first yield.
844                biased;
845                _ = tx.closed() => None,
846                res = &mut fut => Some(res),
847            };
848            if let Some(res) = res {
849                let _ = tx.send(res);
850            }
851        });
852
853        rx.await.map_err(|_| EthFilterError::InternalError)?
854    }
855
856    /// Returns all logs in the given _inclusive_ range that match the filter
857    ///
858    /// Note: This function uses a mix of blocking db operations for fetching indices and header
859    /// ranges and utilizes the rpc cache for optimistically fetching receipts and blocks.
860    /// This function is considered blocking and should thus be spawned on a blocking task.
861    ///
862    /// Returns an error if:
863    ///  - underlying database error
864    async fn get_logs_in_block_range_inner(
865        self: Arc<Self>,
866        filter: &Filter,
867        from_block: u64,
868        to_block: u64,
869        limits: QueryLimits,
870    ) -> Result<Vec<RpcLog<Eth::NetworkTypes>>, EthFilterError> {
871        let mut all_logs = Vec::new();
872        // A lower bound on the JSON size of the matching logs.
873        let mut response_size = 0;
874        let mut retry_range_end = to_block;
875
876        // get current chain tip to determine processing mode
877        let chain_tip = self.provider().best_block_number()?;
878
879        // Scan the range window by window so that receipts are fetched while headers are still
880        // being read: the log limit can end the query after the first window, memory is bounded by
881        // one window, and a cancelled query stops at the next window.
882        for (from, to) in
883            BlockRangeInclusiveIter::new(from_block..=to_block, self.max_headers_range)
884        {
885            // reading headers is blocking, this gives the cancellation check a chance to run
886            tokio::task::yield_now().await;
887
888            // collect the headers of this window that match the bloom filter
889            let mut matching_headers = Vec::new();
890            let headers = self.provider().headers_range(from..=to)?;
891
892            let mut headers_iter = headers.into_iter().peekable();
893
894            while let Some(header) = headers_iter.next() {
895                if !filter.matches_bloom(header.logs_bloom()) {
896                    continue
897                }
898
899                let current_number = header.number();
900
901                let block_hash = match headers_iter.peek() {
902                    Some(next_header) if next_header.number() == current_number + 1 => {
903                        // Headers are consecutive, use the more efficient parent_hash
904                        next_header.parent_hash()
905                    }
906                    _ => {
907                        // Headers not consecutive or last header, calculate hash
908                        header.hash_slow()
909                    }
910                };
911
912                matching_headers.push(SealedHeader::new(header, block_hash));
913            }
914
915            // initialize the appropriate range mode based on collected headers
916            let mut range_mode = RangeMode::new(
917                self.clone(),
918                matching_headers,
919                from_block,
920                to_block,
921                self.max_headers_range,
922                chain_tip,
923            );
924
925            // iterate through the range mode to get receipts and blocks
926            while let Some(ReceiptBlockResult { receipts, recovered_block, header }) =
927                range_mode.next().await?
928            {
929                let num_hash = header.num_hash();
930                let logs_before = all_logs.len();
931
932                let payload_len = append_matching_block_logs(
933                    &mut all_logs,
934                    self.eth_api.converter(),
935                    recovered_block
936                        .map(ProviderOrBlock::Block)
937                        .unwrap_or_else(|| ProviderOrBlock::Provider(self.provider())),
938                    filter,
939                    &header,
940                    &receipts,
941                    false,
942                )?;
943
944                // size check but only if range is multiple blocks, so we always return all
945                // logs of a single block
946                let is_multi_block_range = from_block != to_block;
947                if let Some(max_response_size) = limits.max_response_size &&
948                    is_multi_block_range
949                {
950                    // Topics and data are hex encoded.
951                    response_size +=
952                        (all_logs.len() - logs_before) * MIN_LOG_JSON_SIZE + payload_len * 2;
953                    // The transport measures the encoded response, so the retry range ends before
954                    // the first block whose logs may no longer fit it. A range of only
955                    // `from_block` is left to the transport, like any single block.
956                    let max_encoded_size = MAX_RESPONSE_ENVELOPE_SIZE +
957                        response_size +
958                        all_logs.len() * (MAX_LOG_JSON_SIZE - MIN_LOG_JSON_SIZE);
959                    if max_encoded_size > max_response_size {
960                        retry_range_end =
961                            retry_range_end.min(num_hash.number.saturating_sub(1).max(from_block));
962                    }
963                    if response_size > max_response_size {
964                        debug!(
965                            target: "rpc::eth::filter",
966                            response_size,
967                            max_response_size,
968                            from_block,
969                            to_block = retry_range_end,
970                            "Query exceeded max response size"
971                        );
972                        return Err(EthFilterError::QueryExceedsMaxResponseSize {
973                            max_bytes: max_response_size,
974                            from_block,
975                            to_block: retry_range_end,
976                        });
977                    }
978                }
979
980                if let Some(max_logs_per_response) = limits.max_logs_per_response &&
981                    is_multi_block_range &&
982                    all_logs.len() > max_logs_per_response
983                {
984                    let retry_to_block = if num_hash.number == from_block {
985                        from_block
986                    } else {
987                        num_hash.number - 1
988                    };
989
990                    debug!(
991                        target: "rpc::eth::filter",
992                        logs_found = all_logs.len(),
993                        max_logs_per_response,
994                        from_block,
995                        to_block = retry_to_block,
996                        "Query exceeded max logs per response limit"
997                    );
998                    return Err(EthFilterError::QueryExceedsMaxResults {
999                        max_logs: max_logs_per_response,
1000                        from_block,
1001                        to_block: retry_to_block,
1002                    });
1003                }
1004            }
1005        }
1006
1007        Ok(all_logs)
1008    }
1009
1010    /// Runs `f` on a blocking task once a blocking IO permit is available, holding the permit until
1011    /// `f` returns.
1012    async fn spawn_blocking_io_with_permit<R: Send + 'static>(
1013        &self,
1014        f: impl FnOnce(Eth) -> Result<R, EthFilterError> + Send + 'static,
1015    ) -> Result<R, EthFilterError> {
1016        let permit = self
1017            .eth_api
1018            .acquire_owned_blocking_io()
1019            .await
1020            .map_err(|_| EthFilterError::InternalError)?;
1021        self.eth_api
1022            .spawn_blocking_io(move |eth_api| {
1023                let _permit = permit;
1024                Ok(f(eth_api))
1025            })
1026            .await
1027            .map_err(|_| EthFilterError::InternalError)?
1028    }
1029
1030    /// Returns the logs of the block with the given header that match the filter, reading the
1031    /// transactions of the receipts with matching logs from the provider.
1032    ///
1033    /// This performs blocking reads and must run on a blocking task.
1034    fn block_logs_from_provider(
1035        eth_api: &Eth,
1036        filter: &Filter,
1037        header: &SealedHeader<<Eth::Provider as HeaderProvider>::Header>,
1038        receipts: &[ProviderReceipt<Eth::Provider>],
1039    ) -> Result<Vec<RpcLog<Eth::NetworkTypes>>, EthFilterError> {
1040        let provider = eth_api.provider();
1041        let mut all_logs = Vec::new();
1042
1043        // Looking up a transaction by its id costs about as much as decoding four of the block's
1044        // transactions, so they are all read at once if more than a quarter of the receipts have
1045        // matching logs.
1046        let more_than_a_quarter_match = receipts
1047            .iter()
1048            .filter(|receipt| receipt.logs().iter().any(|log| filter.matches(log)))
1049            .nth(receipts.len() / 4)
1050            .is_some();
1051        if more_than_a_quarter_match {
1052            // Reading them by hash fails instead of returning the transactions of another block if
1053            // this one was reorged out in the meantime.
1054            let transactions = provider
1055                .transactions_by_block(header.hash().into())?
1056                .ok_or(ProviderError::HeaderNotFound(header.hash().into()))?;
1057            logs_utils::append_matching_block_logs_with(
1058                &mut all_logs,
1059                eth_api.converter(),
1060                filter,
1061                header,
1062                receipts,
1063                false,
1064                |receipt_idx| {
1065                    // A block's transactions and receipts share their indices.
1066                    let transaction =
1067                        transactions.get(receipt_idx).ok_or(EthApiError::TransactionNotFound)?;
1068                    Ok(Some(*transaction.tx_hash()))
1069                },
1070            )?;
1071            return Ok(all_logs)
1072        }
1073
1074        let res = append_matching_block_logs(
1075            &mut all_logs,
1076            eth_api.converter(),
1077            ProviderOrBlock::Provider(provider),
1078            filter,
1079            header,
1080            receipts,
1081            false,
1082        );
1083
1084        // The transactions were looked up by the number of the block, so they are its own only if
1085        // it is still the canonical block at that number. Numbers resolve to the in-memory
1086        // canonical chain before the database, as those lookups do, so this also catches a reorg
1087        // the database has not applied yet. A reorg also explains a failed lookup.
1088        if (res.is_err() || !all_logs.is_empty()) &&
1089            provider.block_hash(header.number())? != Some(header.hash())
1090        {
1091            return Err(ProviderError::HeaderNotFound(header.hash().into()).into())
1092        }
1093        res?;
1094        Ok(all_logs)
1095    }
1096
1097    /// Returns whether the bloom of the block allows logs matching the filter.
1098    ///
1099    /// Returns an error if the history of the block has expired (EIP-4444).
1100    fn block_logs_may_match(
1101        provider: &Eth::Provider,
1102        filter: &Filter,
1103        header: &SealedHeader<<Eth::Provider as HeaderProvider>::Header>,
1104    ) -> Result<bool, EthFilterError> {
1105        let earliest_block = provider.earliest_block_number()?;
1106        if header.number() < earliest_block {
1107            return Err(EthApiError::PrunedHistoryUnavailable {
1108                requested: header.number(),
1109                earliest_available: earliest_block,
1110            }
1111            .into());
1112        }
1113
1114        Ok(filter.matches_bloom(header.logs_bloom()))
1115    }
1116
1117    /// Returns the error for a block whose receipts cannot be read although its header was found.
1118    ///
1119    /// The receipts were pruned, unless the block was reorged out after its header was read.
1120    fn missing_receipts(
1121        provider: &Eth::Provider,
1122        header: &SealedHeader<<Eth::Provider as HeaderProvider>::Header>,
1123    ) -> EthFilterError {
1124        match provider.block_number(header.hash()) {
1125            Ok(Some(_)) => EthFilterError::ReceiptsUnavailable(header.number()),
1126            Ok(None) => ProviderError::HeaderNotFound(header.hash().into()).into(),
1127            Err(err) => err.into(),
1128        }
1129    }
1130}
1131
1132/// All active filters
1133#[derive(Debug, Clone, Default)]
1134pub struct ActiveFilters<T> {
1135    inner: Arc<Mutex<HashMap<FilterId, ActiveFilter<T>>>>,
1136}
1137
1138impl<T> ActiveFilters<T> {
1139    /// Returns an empty instance.
1140    pub fn new() -> Self {
1141        Self { inner: Arc::new(Mutex::new(HashMap::default())) }
1142    }
1143
1144    /// Returns `true` if a filter with the given id exists.
1145    pub async fn contains(&self, id: &FilterId) -> bool {
1146        self.inner.lock().await.contains_key(id)
1147    }
1148
1149    /// Returns the number of currently active filters.
1150    pub async fn len(&self) -> usize {
1151        self.inner.lock().await.len()
1152    }
1153
1154    /// Returns `true` if there are no active filters.
1155    pub async fn is_empty(&self) -> bool {
1156        self.inner.lock().await.is_empty()
1157    }
1158
1159    /// Returns all active filter ids.
1160    pub async fn ids(&self) -> Vec<FilterId> {
1161        self.inner.lock().await.keys().cloned().collect()
1162    }
1163}
1164
1165/// An installed filter
1166#[derive(Debug)]
1167struct ActiveFilter<T> {
1168    /// The first block the next poll returns changes for, or `u64::MAX` once a log filter has
1169    /// nothing left to deliver.
1170    block: u64,
1171    /// Last time this filter was polled.
1172    last_poll_timestamp: Instant,
1173    /// What kind of filter it is.
1174    kind: FilterKind<T>,
1175}
1176
1177/// A receiver of the shared feed of pending transaction hashes.
1178///
1179/// Returns all hashes that were published since the last poll.
1180#[derive(Debug, Clone)]
1181struct PendingTransactionsReceiver {
1182    txs_receiver: Arc<Mutex<broadcast::Receiver<TxHash>>>,
1183}
1184
1185impl PendingTransactionsReceiver {
1186    fn new(receiver: broadcast::Receiver<TxHash>) -> Self {
1187        Self { txs_receiver: Arc::new(Mutex::new(receiver)) }
1188    }
1189
1190    /// Returns all new pending transactions received since the last poll.
1191    async fn drain<T>(&self) -> FilterChanges<T> {
1192        let mut pending_txs = Vec::new();
1193        drain_feed(&mut *self.txs_receiver.lock().await, |tx_hash| pending_txs.push(tx_hash));
1194        FilterChanges::Hashes(pending_txs)
1195    }
1196}
1197
1198/// A receiver of the shared feed of new pending transactions, that returns them as RPC
1199/// transactions.
1200#[derive(Debug)]
1201struct FullTransactionsReceiver<T: PoolTransaction, TxCompat> {
1202    txs_receiver: Mutex<broadcast::Receiver<Arc<ValidPoolTransaction<T>>>>,
1203    converter: TxCompat,
1204}
1205
1206impl<T, TxCompat> FullTransactionsReceiver<T, TxCompat>
1207where
1208    T: PoolTransaction + 'static,
1209    TxCompat: RpcConvert<Primitives: NodePrimitives<SignedTx = T::Consensus>>,
1210{
1211    /// Returns all new pending transactions received since the last poll.
1212    async fn drain(&self) -> FilterChanges<RpcTransaction<TxCompat::Network>> {
1213        // The guard is dropped before the conversion, so a concurrent poll of the filter only waits
1214        // for the transactions to be taken from the feed.
1215        let mut txs = Vec::new();
1216        drain_feed(&mut *self.txs_receiver.lock().await, |tx| txs.push(tx));
1217        let pending_txs = txs
1218            .into_iter()
1219            .filter_map(|tx| match self.converter.fill_pending(tx.to_consensus()) {
1220                Ok(tx) => Some(tx),
1221                Err(err) => {
1222                    error!(target: "rpc",
1223                        %err,
1224                        "Failed to fill txn with block context"
1225                    );
1226                    None
1227                }
1228            })
1229            .collect();
1230        FilterChanges::Transactions(pending_txs)
1231    }
1232}
1233
1234/// Helper trait for [`FullTransactionsReceiver`] to erase the `Transaction` type.
1235#[async_trait]
1236trait FullTransactionsFilter<T>: fmt::Debug + Send + Sync + Unpin + 'static {
1237    async fn drain(&self) -> FilterChanges<T>;
1238}
1239
1240#[async_trait]
1241impl<T, TxCompat> FullTransactionsFilter<RpcTransaction<TxCompat::Network>>
1242    for FullTransactionsReceiver<T, TxCompat>
1243where
1244    T: PoolTransaction + 'static,
1245    TxCompat: RpcConvert<Primitives: NodePrimitives<SignedTx = T::Consensus>>,
1246{
1247    async fn drain(&self) -> FilterChanges<RpcTransaction<TxCompat::Network>> {
1248        Self::drain(self).await
1249    }
1250}
1251
1252/// The shared feed of new pending transactions behind all full pending transaction filters.
1253#[derive(Debug)]
1254struct PoolFullTransactionsFeed<Pool: TransactionPool, TxCompat> {
1255    pool: Pool,
1256    converter: TxCompat,
1257    feed: Arc<TxFeed<Arc<ValidPoolTransaction<Pool::Transaction>>>>,
1258}
1259
1260impl<Pool, TxCompat> PoolFullTransactionsFeed<Pool, TxCompat>
1261where
1262    Pool: TransactionPool,
1263{
1264    /// Creates a feed without a producer.
1265    fn new(pool: Pool, converter: TxCompat) -> Self {
1266        Self { pool, converter, feed: Arc::new(TxFeed::new()) }
1267    }
1268}
1269
1270/// Helper trait for [`PoolFullTransactionsFeed`] to erase the pool type.
1271trait FullTransactionsFeed<T>: fmt::Debug + Send + Sync + 'static {
1272    /// Returns a filter over the feed that only sees the transactions published from now on.
1273    ///
1274    /// Starts the producer on `spawner` if the feed has none.
1275    fn subscribe(&self, spawner: &Runtime) -> Arc<dyn FullTransactionsFilter<T>>;
1276}
1277
1278impl<Pool, TxCompat> FullTransactionsFeed<RpcTransaction<TxCompat::Network>>
1279    for PoolFullTransactionsFeed<Pool, TxCompat>
1280where
1281    Pool: TransactionPool<
1282            Transaction: PoolTransaction<
1283                Consensus = <TxCompat::Primitives as NodePrimitives>::SignedTx,
1284            >,
1285        > + 'static,
1286    TxCompat: RpcConvert,
1287{
1288    fn subscribe(
1289        &self,
1290        spawner: &Runtime,
1291    ) -> Arc<dyn FullTransactionsFilter<RpcTransaction<TxCompat::Network>>> {
1292        let txs_receiver = self.feed.subscribe(spawner, || {
1293            let listener = self.pool.new_pending_pool_transactions_listener();
1294            let capacity = listener.max_capacity();
1295            (listener.map(|event| event.transaction), capacity)
1296        });
1297        Arc::new(FullTransactionsReceiver {
1298            txs_receiver: Mutex::new(txs_receiver),
1299            converter: dyn_clone::clone(&self.converter),
1300        })
1301    }
1302}
1303
1304/// Represents the kind of pending transaction data that can be retrieved.
1305///
1306/// This enum differentiates between two kinds of pending transaction data:
1307/// - Just the transaction hashes.
1308/// - Full transaction details.
1309#[derive(Debug, Clone)]
1310enum PendingTransactionKind<T> {
1311    Hashes(PendingTransactionsReceiver),
1312    FullTransaction(Arc<dyn FullTransactionsFilter<T>>),
1313}
1314
1315impl<T: 'static> PendingTransactionKind<T> {
1316    /// Returns the transactions published to the kind's feed since the last poll.
1317    ///
1318    /// A filter that is polled less often than its feed holds items loses the oldest ones, like a
1319    /// lagging subscription does.
1320    async fn drain(&self) -> FilterChanges<T> {
1321        match self {
1322            Self::Hashes(receiver) => receiver.drain().await,
1323            Self::FullTransaction(receiver) => receiver.drain().await,
1324        }
1325    }
1326}
1327
1328/// Broadcasts the new pending transactions of one filter kind to all filters of that kind.
1329///
1330/// The pool buffers new transactions per listener, so a listener for every filter would multiply
1331/// that buffer and the pool's work per inserted transaction with the number of filters. All filters
1332/// of a kind share one listener instead. The feed holds as many transactions as that listener's
1333/// buffer, so a filter can fall as far behind as a listener of its own could before it loses the
1334/// oldest ones.
1335#[derive(Debug)]
1336struct TxFeed<T> {
1337    /// The running producer's sender, if any.
1338    ///
1339    /// The producer holds the only strong sender, so if it dies, its filters end and the next
1340    /// filter starts a new producer.
1341    sender: parking_lot::Mutex<Option<broadcast::WeakSender<T>>>,
1342}
1343
1344impl<T: Clone + Send + 'static> TxFeed<T> {
1345    /// Creates a feed without a producer.
1346    const fn new() -> Self {
1347        Self { sender: parking_lot::Mutex::new(None) }
1348    }
1349
1350    /// Subscribes to the feed. If no producer is running, this starts one on `spawner` over the
1351    /// stream that `source` returns, together with the capacity of the listener behind it.
1352    ///
1353    /// `source` runs before this returns, so the producer does not miss anything that is
1354    /// published after the call.
1355    fn subscribe<S>(
1356        self: &Arc<Self>,
1357        spawner: &Runtime,
1358        source: impl FnOnce() -> (S, usize),
1359    ) -> broadcast::Receiver<T>
1360    where
1361        S: Stream<Item = T> + Send + Unpin + 'static,
1362    {
1363        let mut slot = self.sender.lock();
1364        if let Some(sender) = slot.as_ref().and_then(broadcast::WeakSender::upgrade) {
1365            return sender.subscribe()
1366        }
1367        let (source, capacity) = source();
1368        let (sender, receiver) = broadcast::channel(capacity.min(MAX_TX_FEED_CAPACITY));
1369        *slot = Some(sender.downgrade());
1370        let feed = self.clone();
1371        spawner.spawn_task(async move { feed.produce(sender, source).await });
1372        receiver
1373    }
1374
1375    /// Broadcasts the items of `source` until the feed has no receivers left or `source` ends.
1376    async fn produce<S: Stream<Item = T> + Unpin>(
1377        &self,
1378        sender: broadcast::Sender<T>,
1379        mut source: S,
1380    ) {
1381        loop {
1382            tokio::select! {
1383                _ = sender.closed() => {
1384                    if self.stop_if_unused(&sender) {
1385                        break
1386                    }
1387                }
1388                item = source.next() => {
1389                    let Some(item) = item else {
1390                        // Dropping the sender ends all filters of the feed.
1391                        *self.sender.lock() = None;
1392                        break
1393                    };
1394                    if sender.send(item).is_err() && self.stop_if_unused(&sender) {
1395                        break
1396                    }
1397                }
1398            }
1399        }
1400        debug!(target: "rpc::eth::filter", "pending transaction feed stopped");
1401    }
1402
1403    /// Removes the producer behind `sender` from the feed if it has no receivers left, and returns
1404    /// whether it did.
1405    ///
1406    /// Subscribing holds the same lock, so a new filter either joins before this check or starts a
1407    /// new producer after it.
1408    fn stop_if_unused(&self, sender: &broadcast::Sender<T>) -> bool {
1409        let mut slot = self.sender.lock();
1410        if sender.receiver_count() > 0 {
1411            return false
1412        }
1413        *slot = None;
1414        true
1415    }
1416}
1417
1418/// Passes everything that `receiver` has buffered to `f`, oldest first.
1419///
1420/// If the receiver lagged behind its feed, this skips to the oldest item that the feed still
1421/// holds.
1422fn drain_feed<T: Clone>(receiver: &mut broadcast::Receiver<T>, mut f: impl FnMut(T)) {
1423    loop {
1424        match receiver.try_recv() {
1425            Ok(item) => f(item),
1426            Err(TryRecvError::Lagged(skipped)) => {
1427                debug!(target: "rpc::eth::filter", skipped, "pending transaction filter lagging behind its feed")
1428            }
1429            Err(TryRecvError::Empty | TryRecvError::Closed) => break,
1430        }
1431    }
1432}
1433
1434#[derive(Clone, Debug)]
1435enum FilterKind<T> {
1436    Log(Box<Filter>),
1437    Block,
1438    PendingTransaction(PendingTransactionKind<T>),
1439}
1440
1441/// An iterator that yields _inclusive_ block ranges of a given step size
1442#[derive(Debug)]
1443struct BlockRangeInclusiveIter {
1444    iter: StepBy<RangeInclusive<u64>>,
1445    step: u64,
1446    end: u64,
1447}
1448
1449impl BlockRangeInclusiveIter {
1450    fn new(range: RangeInclusive<u64>, step: u64) -> Self {
1451        Self { end: *range.end(), iter: range.step_by(step as usize + 1), step }
1452    }
1453}
1454
1455impl Iterator for BlockRangeInclusiveIter {
1456    type Item = (u64, u64);
1457
1458    fn next(&mut self) -> Option<Self::Item> {
1459        let start = self.iter.next()?;
1460        let end = (start + self.step).min(self.end);
1461        if start > end {
1462            return None
1463        }
1464        Some((start, end))
1465    }
1466}
1467
1468/// Errors that can occur in the handler implementation
1469#[derive(Debug, thiserror::Error)]
1470pub enum EthFilterError {
1471    /// Filter not found.
1472    #[error("filter not found")]
1473    FilterNotFound(FilterId),
1474    /// Invalid block range.
1475    #[error("invalid block range params")]
1476    InvalidBlockRangeParams,
1477    /// Block range extends beyond current head.
1478    #[error("block range extends beyond current head block: requested {requested}, head {head}")]
1479    BlockRangeExceedsHead {
1480        /// The requested `toBlock` number
1481        requested: u64,
1482        /// The current head block number
1483        head: u64,
1484    },
1485    /// Query scope is too broad.
1486    #[error("query exceeds max block range {0}")]
1487    QueryExceedsMaxBlocks(u64),
1488    /// Receipts of a block the filter matched are gone, most likely pruned.
1489    #[error("pruned history unavailable")]
1490    ReceiptsUnavailable(u64),
1491    /// Query result is too large.
1492    #[error("query exceeds max results {max_logs}, retry with the range {from_block}-{to_block}")]
1493    QueryExceedsMaxResults {
1494        /// Maximum number of logs allowed per response
1495        max_logs: usize,
1496        /// Start block of the suggested retry range
1497        from_block: u64,
1498        /// End block of the suggested retry range (last successfully processed block)
1499        to_block: u64,
1500    },
1501    /// Query result exceeds the response size limit.
1502    #[error(
1503        "query exceeds max response size {max_bytes} bytes, retry with the range {from_block}-{to_block}"
1504    )]
1505    QueryExceedsMaxResponseSize {
1506        /// Maximum response size in bytes
1507        max_bytes: usize,
1508        /// Start block of the suggested retry range
1509        from_block: u64,
1510        /// End block of the suggested retry range (last block before the response may no longer
1511        /// fit)
1512        to_block: u64,
1513    },
1514    /// Error serving request in `eth_` namespace.
1515    #[error(transparent)]
1516    EthAPIError(#[from] EthApiError),
1517    /// Error thrown when a spawned task failed to deliver a response.
1518    #[error("internal filter error")]
1519    InternalError,
1520    /// The maximum number of active filters is reached.
1521    #[error("too many active filters, max {0}")]
1522    TooManyFilters(usize),
1523}
1524
1525impl From<EthFilterError> for jsonrpsee::types::error::ErrorObject<'static> {
1526    fn from(err: EthFilterError) -> Self {
1527        match err {
1528            // geth and Nethermind answer -32000 for unknown filter ids
1529            EthFilterError::FilterNotFound(_) => rpc_error_with_code(
1530                jsonrpsee::types::error::CALL_EXECUTION_FAILED_CODE,
1531                "filter not found",
1532            ),
1533            err @ EthFilterError::InternalError => {
1534                rpc_error_with_code(jsonrpsee::types::error::INTERNAL_ERROR_CODE, err.to_string())
1535            }
1536            err @ EthFilterError::TooManyFilters(_) => {
1537                rpc_error_with_code(LIMIT_EXCEEDED_CODE, err.to_string())
1538            }
1539            EthFilterError::EthAPIError(err) => err.into(),
1540            err @ EthFilterError::ReceiptsUnavailable(_) => {
1541                rpc_error_with_code(EthRpcErrorCode::PrunedHistory.code(), err.to_string())
1542            }
1543            err @ (EthFilterError::InvalidBlockRangeParams |
1544            EthFilterError::QueryExceedsMaxBlocks(_) |
1545            EthFilterError::QueryExceedsMaxResults { .. } |
1546            EthFilterError::QueryExceedsMaxResponseSize { .. } |
1547            EthFilterError::BlockRangeExceedsHead { .. }) => {
1548                rpc_error_with_code(jsonrpsee::types::error::INVALID_PARAMS_CODE, err.to_string())
1549            }
1550        }
1551    }
1552}
1553
1554impl From<ProviderError> for EthFilterError {
1555    fn from(err: ProviderError) -> Self {
1556        Self::EthAPIError(err.into())
1557    }
1558}
1559
1560impl From<logs_utils::FilterBlockRangeError> for EthFilterError {
1561    fn from(err: logs_utils::FilterBlockRangeError) -> Self {
1562        match err {
1563            logs_utils::FilterBlockRangeError::InvalidBlockRange => Self::InvalidBlockRangeParams,
1564            logs_utils::FilterBlockRangeError::BlockRangeExceedsHead { requested, head } => {
1565                Self::BlockRangeExceedsHead { requested, head }
1566            }
1567        }
1568    }
1569}
1570
1571/// Helper type for the common pattern of returning receipts, block and the original header that is
1572/// a match for the filter.
1573struct ReceiptBlockResult<P>
1574where
1575    P: BlockReader,
1576{
1577    /// We always need the entire receipts for the matching block.
1578    receipts: Arc<Vec<ProviderReceipt<P>>>,
1579    /// Block can be optional and we can fetch it lazily when needed.
1580    recovered_block: Option<Arc<reth_primitives_traits::RecoveredBlock<ProviderBlock<P>>>>,
1581    /// The header of the block.
1582    header: SealedHeader<<P as HeaderProvider>::Header>,
1583}
1584
1585/// Represents different modes for processing block ranges when filtering logs
1586enum RangeMode<
1587    Eth: RpcNodeCoreExt<Provider: BlockIdReader, Pool: TransactionPool> + LoadReceipt + EthBlocks,
1588> {
1589    /// Use cache-based processing for recent blocks
1590    Cached(CachedMode<Eth>),
1591    /// Use range-based processing for older blocks
1592    Range(RangeBlockMode<Eth>),
1593}
1594
1595impl<
1596        Eth: RpcNodeCoreExt<Provider: BlockIdReader, Pool: TransactionPool> + LoadReceipt + EthBlocks,
1597    > RangeMode<Eth>
1598{
1599    /// Creates a new `RangeMode`.
1600    fn new(
1601        filter_inner: Arc<EthFilterInner<Eth>>,
1602        sealed_headers: Vec<SealedHeader<<Eth::Provider as HeaderProvider>::Header>>,
1603        from_block: u64,
1604        to_block: u64,
1605        max_headers_range: u64,
1606        chain_tip: u64,
1607    ) -> Self {
1608        let block_count = to_block - from_block + 1;
1609        let distance_from_tip = chain_tip.saturating_sub(to_block);
1610
1611        // Determine if we should use cached mode based on range characteristics
1612        let use_cached_mode =
1613            Self::should_use_cached_mode(&sealed_headers, block_count, distance_from_tip);
1614
1615        // Fetching receipts in parallel is only worth the extra tasks when most of the window has
1616        // them to read; the sequential path serves the rest from the receipt cache where it can
1617        let parallel = sealed_headers.len() >= PARALLEL_PROCESSING_THRESHOLD;
1618
1619        if use_cached_mode && !sealed_headers.is_empty() {
1620            Self::Cached(CachedMode { filter_inner, headers_iter: sealed_headers.into_iter() })
1621        } else {
1622            Self::Range(RangeBlockMode {
1623                filter_inner,
1624                iter: sealed_headers.into_iter().peekable(),
1625                next: VecDeque::new(),
1626                max_range: (max_headers_range as usize).min(MAX_PARALLEL_BATCH_SIZE),
1627                parallel,
1628                pending_tasks: FuturesOrdered::new(),
1629            })
1630        }
1631    }
1632
1633    /// Determines whether to use cached mode based on bloom filter matches and range size
1634    const fn should_use_cached_mode(
1635        headers: &[SealedHeader<<Eth::Provider as HeaderProvider>::Header>],
1636        block_count: u64,
1637        distance_from_tip: u64,
1638    ) -> bool {
1639        // Headers are already filtered by bloom, so count equals length
1640        let bloom_matches = headers.len();
1641
1642        // Calculate adjusted threshold based on bloom matches
1643        let adjusted_threshold = Self::calculate_adjusted_threshold(block_count, bloom_matches);
1644
1645        block_count <= adjusted_threshold && distance_from_tip <= adjusted_threshold
1646    }
1647
1648    /// Calculates the adjusted cache threshold based on bloom filter matches
1649    const fn calculate_adjusted_threshold(block_count: u64, bloom_matches: usize) -> u64 {
1650        // Only apply adjustments for larger ranges
1651        if block_count <= BLOOM_ADJUSTMENT_MIN_BLOCKS {
1652            return CACHED_MODE_BLOCK_THRESHOLD;
1653        }
1654
1655        match bloom_matches {
1656            n if n > HIGH_BLOOM_MATCH_THRESHOLD => CACHED_MODE_BLOCK_THRESHOLD / 2,
1657            n if n > MODERATE_BLOOM_MATCH_THRESHOLD => (CACHED_MODE_BLOCK_THRESHOLD * 3) / 4,
1658            _ => CACHED_MODE_BLOCK_THRESHOLD,
1659        }
1660    }
1661
1662    /// Gets the next (receipts, `maybe_block`, header, `block_hash`) tuple.
1663    async fn next(&mut self) -> Result<Option<ReceiptBlockResult<Eth::Provider>>, EthFilterError> {
1664        match self {
1665            Self::Cached(cached) => cached.next().await,
1666            Self::Range(range) => range.next().await,
1667        }
1668    }
1669}
1670
1671/// Mode for processing blocks using cache optimization for recent blocks
1672struct CachedMode<
1673    Eth: RpcNodeCoreExt<Provider: BlockIdReader, Pool: TransactionPool> + LoadReceipt + EthBlocks,
1674> {
1675    filter_inner: Arc<EthFilterInner<Eth>>,
1676    headers_iter: std::vec::IntoIter<SealedHeader<<Eth::Provider as HeaderProvider>::Header>>,
1677}
1678
1679impl<
1680        Eth: RpcNodeCoreExt<Provider: BlockIdReader, Pool: TransactionPool> + LoadReceipt + EthBlocks,
1681    > CachedMode<Eth>
1682{
1683    async fn next(&mut self) -> Result<Option<ReceiptBlockResult<Eth::Provider>>, EthFilterError> {
1684        let Some(header) = self.headers_iter.next() else { return Ok(None) };
1685
1686        // Use get_receipts_and_maybe_block which has automatic fallback to provider
1687        let Some((receipts, maybe_block)) =
1688            self.filter_inner.eth_cache().get_receipts_and_maybe_block(header.hash()).await?
1689        else {
1690            return Err(EthFilterError::ReceiptsUnavailable(header.number()))
1691        };
1692
1693        Ok(Some(ReceiptBlockResult { receipts, recovered_block: maybe_block, header }))
1694    }
1695}
1696
1697/// Type alias for parallel receipt fetching task futures used in `RangeBlockMode`
1698type ReceiptFetchFuture<P> =
1699    Pin<Box<dyn Future<Output = Result<Vec<ReceiptBlockResult<P>>, EthFilterError>> + Send>>;
1700
1701/// Mode for processing blocks using range queries for older blocks
1702struct RangeBlockMode<
1703    Eth: RpcNodeCoreExt<Provider: BlockIdReader, Pool: TransactionPool> + LoadReceipt + EthBlocks,
1704> {
1705    filter_inner: Arc<EthFilterInner<Eth>>,
1706    iter: Peekable<std::vec::IntoIter<SealedHeader<<Eth::Provider as HeaderProvider>::Header>>>,
1707    next: VecDeque<ReceiptBlockResult<Eth::Provider>>,
1708    /// Maximum number of consecutive blocks fetched by one batch of parallel tasks
1709    max_range: usize,
1710    /// Whether receipts are fetched in parallel batches of consecutive blocks
1711    parallel: bool,
1712    // Stream of ongoing receipt fetching tasks
1713    pending_tasks: FuturesOrdered<ReceiptFetchFuture<Eth::Provider>>,
1714}
1715
1716impl<
1717        Eth: RpcNodeCoreExt<Provider: BlockIdReader, Pool: TransactionPool> + LoadReceipt + EthBlocks,
1718    > RangeBlockMode<Eth>
1719{
1720    async fn next(&mut self) -> Result<Option<ReceiptBlockResult<Eth::Provider>>, EthFilterError> {
1721        loop {
1722            // First, try to return any already processed result from buffer
1723            if let Some(result) = self.next.pop_front() {
1724                return Ok(Some(result));
1725            }
1726
1727            // Try to get a completed task result if there are pending tasks
1728            if let Some(task_result) = self.pending_tasks.next().await {
1729                self.next.extend(task_result?);
1730                continue;
1731            }
1732
1733            // No pending tasks - try to generate more work
1734            let Some(next_header) = self.iter.next() else {
1735                // No more headers to process
1736                return Ok(None);
1737            };
1738
1739            if !self.parallel {
1740                // Process the block on its own so that only one block's receipts are held
1741                if let Some(result) = self.process_small_range(vec![next_header]).await? {
1742                    return Ok(Some(result));
1743                }
1744                // Continue loop to check for more work
1745                continue;
1746            }
1747
1748            let mut range_headers = Vec::with_capacity(self.max_range.min(self.iter.len() + 1));
1749            range_headers.push(next_header);
1750
1751            // Collect consecutive blocks up to max_range size
1752            while range_headers.len() < self.max_range {
1753                let Some(peeked) = self.iter.peek() else { break };
1754                let Some(last_header) = range_headers.last() else { break };
1755
1756                let expected_next = last_header.number() + 1;
1757                if peeked.number() != expected_next {
1758                    trace!(
1759                        target: "rpc::eth::filter",
1760                        last_block = last_header.number(),
1761                        next_block = peeked.number(),
1762                        expected = expected_next,
1763                        range_size = range_headers.len(),
1764                        "Non-consecutive block detected, stopping range collection"
1765                    );
1766                    break; // Non-consecutive block, stop here
1767                }
1768
1769                let Some(next_header) = self.iter.next() else { break };
1770                range_headers.push(next_header);
1771            }
1772
1773            self.spawn_parallel_tasks(range_headers);
1774            // Continue loop to await the spawned tasks
1775        }
1776    }
1777
1778    /// Process a small range of headers sequentially
1779    ///
1780    /// This is used for ranges below [`PARALLEL_PROCESSING_THRESHOLD`], one block at a time.
1781    async fn process_small_range(
1782        &mut self,
1783        range_headers: Vec<SealedHeader<<Eth::Provider as HeaderProvider>::Header>>,
1784    ) -> Result<Option<ReceiptBlockResult<Eth::Provider>>, EthFilterError> {
1785        // Process each header individually to avoid queuing for all receipts
1786        for header in range_headers {
1787            // First check if already cached to avoid unnecessary provider calls
1788            let (maybe_block, maybe_receipts) = self
1789                .filter_inner
1790                .eth_cache()
1791                .maybe_cached_block_and_receipts(header.hash())
1792                .await?;
1793
1794            let receipts = match maybe_receipts {
1795                Some(receipts) => receipts,
1796                None => {
1797                    // Not cached - fetch directly from provider
1798                    match self.filter_inner.provider().receipts_by_block(header.hash().into())? {
1799                        Some(receipts) => Arc::new(receipts),
1800                        None => return Err(EthFilterError::ReceiptsUnavailable(header.number())),
1801                    }
1802                }
1803            };
1804
1805            if !receipts.is_empty() {
1806                self.next.push_back(ReceiptBlockResult {
1807                    receipts,
1808                    recovered_block: maybe_block,
1809                    header,
1810                });
1811            }
1812        }
1813
1814        Ok(self.next.pop_front())
1815    }
1816
1817    /// Spawn parallel tasks for processing a large range of headers
1818    ///
1819    /// This is used for ranges of at least [`PARALLEL_PROCESSING_THRESHOLD`] blocks.
1820    fn spawn_parallel_tasks(
1821        &mut self,
1822        range_headers: Vec<SealedHeader<<Eth::Provider as HeaderProvider>::Header>>,
1823    ) {
1824        // Split headers into chunks
1825        let chunk_size = range_headers.len().div_ceil(DEFAULT_PARALLEL_CONCURRENCY).max(1);
1826        let header_chunks = range_headers
1827            .into_iter()
1828            .chunks(chunk_size)
1829            .into_iter()
1830            .map(|chunk| chunk.collect::<Vec<_>>())
1831            .collect::<Vec<_>>();
1832
1833        // Spawn each chunk as a separate task directly into the FuturesOrdered stream
1834        for chunk_headers in header_chunks {
1835            let filter_inner = self.filter_inner.clone();
1836            let fetch = move || Self::fetch_chunk_receipts(&filter_inner, chunk_headers);
1837
1838            // A parallel task occupies an additional blocking thread, so it needs its own share
1839            // of the blocking IO budget. Without one the chunk is fetched on this task instead.
1840            let chunk_task: ReceiptFetchFuture<Eth::Provider> = match self
1841                .filter_inner
1842                .eth_api
1843                .blocking_io_task_guard()
1844                .clone()
1845                .try_acquire_owned()
1846            {
1847                Ok(permit) => Box::pin(async move {
1848                    let chunk_task = reth_tasks::spawn_blocking(move || {
1849                        let _permit = permit;
1850                        fetch()
1851                    });
1852
1853                    // Await the blocking task and handle the result
1854                    match chunk_task.await {
1855                        Ok(chunk_results) => chunk_results,
1856                        Err(join_err) => {
1857                            trace!(target: "rpc::eth::filter", error = ?join_err, "Task join error");
1858                            Err(EthFilterError::InternalError)
1859                        }
1860                    }
1861                }),
1862                Err(_) => Box::pin(async move { fetch() }),
1863            };
1864
1865            self.pending_tasks.push_back(chunk_task);
1866        }
1867    }
1868
1869    /// Fetches the receipts of the given blocks from the provider.
1870    fn fetch_chunk_receipts(
1871        filter_inner: &EthFilterInner<Eth>,
1872        chunk_headers: Vec<SealedHeader<<Eth::Provider as HeaderProvider>::Header>>,
1873    ) -> Result<Vec<ReceiptBlockResult<Eth::Provider>>, EthFilterError> {
1874        let mut chunk_results = Vec::with_capacity(chunk_headers.len());
1875
1876        for header in chunk_headers {
1877            // Fetch directly from provider - RangeMode is used for older blocks
1878            // unlikely to be cached
1879            let receipts = match filter_inner.provider().receipts_by_block(header.hash().into())? {
1880                Some(receipts) => Arc::new(receipts),
1881                None => return Err(EthFilterError::ReceiptsUnavailable(header.number())),
1882            };
1883
1884            if !receipts.is_empty() {
1885                chunk_results.push(ReceiptBlockResult { receipts, recovered_block: None, header });
1886            }
1887        }
1888
1889        Ok(chunk_results)
1890    }
1891}
1892
1893#[cfg(test)]
1894mod tests {
1895    use super::*;
1896    use crate::{eth::EthApi, EthApiBuilder};
1897    use alloy_consensus::TxLegacy;
1898    use alloy_eips::BlockId;
1899    use alloy_network::{Ethereum, TransactionResponse};
1900    use alloy_primitives::{Address, Bloom, Bytes, FixedBytes, Log, LogData, Signature, B256};
1901    use futures::stream;
1902    use jsonrpsee::{types::Id, MethodResponse, ResponsePayload};
1903    use rand::Rng;
1904    use reth_chainspec::{ChainSpec, ChainSpecProvider};
1905    use reth_db_api::models::StoredBlockBodyIndices;
1906    use reth_ethereum_primitives::{Block, BlockBody, Receipt, TransactionSigned, TxType};
1907    use reth_evm_ethereum::EthEvmConfig;
1908    use reth_network_api::noop::NoopNetwork;
1909    use reth_provider::test_utils::MockEthProvider;
1910    use reth_rpc_convert::RpcConverter;
1911    use reth_rpc_eth_api::{helpers::SpawnBlocking, node::RpcNodeCoreAdapter, RpcNodeCore};
1912    use reth_rpc_eth_types::receipt::EthReceiptConverter;
1913    use reth_tasks::Runtime;
1914    use reth_testing_utils::generators;
1915    use reth_transaction_pool::{
1916        test_utils::{testing_pool, MockTransaction, TestPool, TestPoolBuilder},
1917        PoolConfig, TransactionOrigin,
1918    };
1919    use std::{collections::VecDeque, sync::Arc};
1920
1921    #[test]
1922    fn receipts_unavailable_error_matches_geth() {
1923        let err: jsonrpsee::types::error::ErrorObject<'static> =
1924            EthFilterError::ReceiptsUnavailable(100).into();
1925        assert_eq!(err.code(), 4444);
1926        assert_eq!(err.message(), "pruned history unavailable");
1927    }
1928
1929    #[test]
1930    fn test_block_range_iter() {
1931        let mut rng = generators::rng();
1932
1933        let start = rng.random::<u32>() as u64;
1934        let end = start.saturating_add(rng.random::<u32>() as u64);
1935        let step = rng.random::<u16>() as u64;
1936        let range = start..=end;
1937        let mut iter = BlockRangeInclusiveIter::new(range.clone(), step);
1938        let (from, mut end) = iter.next().unwrap();
1939        assert_eq!(from, start);
1940        assert_eq!(end, (from + step).min(*range.end()));
1941
1942        for (next_from, next_end) in iter {
1943            // ensure range starts with previous end + 1
1944            assert_eq!(next_from, end + 1);
1945            end = next_end;
1946        }
1947
1948        assert_eq!(end, *range.end());
1949    }
1950
1951    type TestEthApi = EthApi<
1952        RpcNodeCoreAdapter<MockEthProvider, TestPool, NoopNetwork, EthEvmConfig>,
1953        RpcConverter<Ethereum, EthEvmConfig, EthReceiptConverter<ChainSpec>>,
1954    >;
1955
1956    // Helper function to create a test EthApi instance
1957    fn build_test_eth_api(provider: MockEthProvider) -> TestEthApi {
1958        build_test_eth_api_with_pool(provider, testing_pool())
1959    }
1960
1961    fn build_test_eth_api_with_pool(provider: MockEthProvider, pool: TestPool) -> TestEthApi {
1962        EthApiBuilder::new(
1963            provider.clone(),
1964            pool,
1965            NoopNetwork::default(),
1966            EthEvmConfig::new(provider.chain_spec()),
1967        )
1968        .build()
1969    }
1970
1971    /// Adds one block per number in `blocks`, each with a single legacy transaction whose receipt
1972    /// emits one log, so that a `Filter::default()` matches exactly one log per block.
1973    fn add_blocks_with_log(provider: &MockEthProvider, blocks: RangeInclusive<u64>) {
1974        add_blocks_with_logs(provider, blocks, 1)
1975    }
1976
1977    /// Adds one block per number in `blocks`, each with a single legacy transaction whose receipt
1978    /// emits `logs_per_block` logs that a `Filter::default()` matches.
1979    ///
1980    /// The block body indices assume the added blocks form a range anchored at 0, which is what
1981    /// `MockEthProvider::transaction_by_id` resolves against.
1982    fn add_blocks_with_logs(
1983        provider: &MockEthProvider,
1984        blocks: RangeInclusive<u64>,
1985        logs_per_block: usize,
1986    ) {
1987        let tx = TransactionSigned::new_unhashed(
1988            TxLegacy {
1989                chain_id: Some(1),
1990                gas_price: 21_000,
1991                gas_limit: 21_000,
1992                ..Default::default()
1993            }
1994            .into(),
1995            Signature::test_signature(),
1996        );
1997        let log =
1998            Log { address: Address::ZERO, data: LogData::new_unchecked(vec![], Bytes::new()) };
1999        let receipt = Receipt {
2000            tx_type: TxType::Legacy,
2001            cumulative_gas_used: 21_000,
2002            logs: vec![log; logs_per_block],
2003            success: true,
2004        };
2005
2006        let mut parent_hash = blocks
2007            .start()
2008            .checked_sub(1)
2009            .and_then(|parent| provider.header_by_number(parent).unwrap())
2010            .map(|parent| parent.hash_slow())
2011            .unwrap_or_default();
2012        for number in blocks {
2013            let header = alloy_consensus::Header {
2014                number,
2015                parent_hash,
2016                logs_bloom: Bloom::from([1u8; 256]),
2017                ..Default::default()
2018            };
2019            let hash = header.hash_slow();
2020            let block = Block {
2021                header,
2022                body: BlockBody { transactions: vec![tx.clone()], ..Default::default() },
2023            };
2024            provider.add_block(hash, block);
2025            provider.add_receipts(number, vec![receipt.clone()]);
2026            provider.add_block_body_indices(
2027                number,
2028                StoredBlockBodyIndices { first_tx_num: number, tx_count: 1 },
2029            );
2030            parent_hash = hash;
2031        }
2032    }
2033
2034    /// Polls the filter and returns the block numbers of the delivered logs.
2035    async fn poll_log_blocks<Eth>(eth_filter: &EthFilter<Eth>, id: &FilterId) -> Vec<u64>
2036    where
2037        Eth: FullEthApiTypes<Provider: BlockReader + BlockIdReader>
2038            + RpcNodeCoreExt
2039            + LoadReceipt
2040            + EthBlocks
2041            + 'static,
2042        RpcLog<Eth::NetworkTypes>: Into<alloy_rpc_types_eth::Log>,
2043    {
2044        match eth_filter.filter_changes(id.clone()).await.unwrap() {
2045            FilterChanges::Logs(logs) => {
2046                logs.into_iter().map(|log| log.into().block_number.unwrap()).collect()
2047            }
2048            FilterChanges::Empty => Vec::new(),
2049            changes => panic!("unexpected changes: {changes:?}"),
2050        }
2051    }
2052
2053    #[tokio::test]
2054    async fn test_logs_for_filter_from_block_beyond_head() {
2055        let provider = MockEthProvider::default();
2056        provider.add_header(FixedBytes::random(), alloy_consensus::Header::default());
2057        let eth_api = build_test_eth_api(provider);
2058
2059        let eth_filter =
2060            super::EthFilter::new(eth_api, EthFilterConfig::default(), Runtime::test());
2061
2062        let filter = Filter::new().from_block(100u64).to_block(BlockNumberOrTag::Latest);
2063        let result = eth_filter.inner.clone().logs_for_filter(filter, QueryLimits::default()).await;
2064        assert!(matches!(result, Err(EthFilterError::InvalidBlockRangeParams)), "{result:?}");
2065    }
2066
2067    #[tokio::test]
2068    async fn test_range_block_mode_empty_range() {
2069        let provider = MockEthProvider::default();
2070        let eth_api = build_test_eth_api(provider);
2071
2072        let eth_filter =
2073            super::EthFilter::new(eth_api, EthFilterConfig::default(), Runtime::test());
2074        let filter_inner = eth_filter.inner;
2075
2076        let headers = vec![];
2077        let max_range = 100;
2078
2079        let mut range_mode = RangeBlockMode {
2080            filter_inner,
2081            iter: headers.into_iter().peekable(),
2082            next: VecDeque::new(),
2083            max_range,
2084            parallel: false,
2085
2086            pending_tasks: FuturesOrdered::new(),
2087        };
2088
2089        let result = range_mode.next().await;
2090        assert!(result.is_ok());
2091        assert!(result.unwrap().is_none());
2092    }
2093
2094    #[tokio::test]
2095    async fn test_range_block_mode_queued_results_priority() {
2096        let provider = MockEthProvider::default();
2097
2098        let headers = vec![
2099            SealedHeader::new(
2100                alloy_consensus::Header { number: 100, ..Default::default() },
2101                FixedBytes::random(),
2102            ),
2103            SealedHeader::new(
2104                alloy_consensus::Header { number: 101, ..Default::default() },
2105                FixedBytes::random(),
2106            ),
2107        ];
2108        for header in &headers {
2109            provider.add_header(header.hash(), header.header().clone());
2110            provider.add_receipts(header.number(), vec![]);
2111        }
2112
2113        let eth_api = build_test_eth_api(provider);
2114
2115        let eth_filter =
2116            super::EthFilter::new(eth_api, EthFilterConfig::default(), Runtime::test());
2117        let filter_inner = eth_filter.inner;
2118
2119        // create specific mock results to test ordering
2120        let expected_block_hash_1 = FixedBytes::from([1u8; 32]);
2121        let expected_block_hash_2 = FixedBytes::from([2u8; 32]);
2122
2123        // create mock receipts to test receipt handling
2124        let mock_receipt_1 = reth_ethereum_primitives::Receipt {
2125            tx_type: TxType::Legacy,
2126            cumulative_gas_used: 100_000,
2127            logs: vec![],
2128            success: true,
2129        };
2130        let mock_receipt_2 = reth_ethereum_primitives::Receipt {
2131            tx_type: TxType::Eip1559,
2132            cumulative_gas_used: 200_000,
2133            logs: vec![],
2134            success: true,
2135        };
2136        let mock_receipt_3 = reth_ethereum_primitives::Receipt {
2137            tx_type: TxType::Eip2930,
2138            cumulative_gas_used: 150_000,
2139            logs: vec![],
2140            success: false, // Different success status
2141        };
2142
2143        let mock_result_1 = ReceiptBlockResult {
2144            receipts: Arc::new(vec![mock_receipt_1.clone(), mock_receipt_2.clone()]),
2145            recovered_block: None,
2146            header: SealedHeader::new(
2147                alloy_consensus::Header { number: 42, ..Default::default() },
2148                expected_block_hash_1,
2149            ),
2150        };
2151
2152        let mock_result_2 = ReceiptBlockResult {
2153            receipts: Arc::new(vec![mock_receipt_3.clone()]),
2154            recovered_block: None,
2155            header: SealedHeader::new(
2156                alloy_consensus::Header { number: 43, ..Default::default() },
2157                expected_block_hash_2,
2158            ),
2159        };
2160
2161        let mut range_mode = RangeBlockMode {
2162            filter_inner,
2163            iter: headers.into_iter().peekable(),
2164            next: VecDeque::from([mock_result_1, mock_result_2]), // Queue two results
2165            max_range: 100,
2166            parallel: false,
2167
2168            pending_tasks: FuturesOrdered::new(),
2169        };
2170
2171        // first call should return the first queued result (FIFO order)
2172        let result1 = range_mode.next().await;
2173        assert!(result1.is_ok());
2174        let receipt_result1 = result1.unwrap().unwrap();
2175        assert_eq!(receipt_result1.header.hash(), expected_block_hash_1);
2176        assert_eq!(receipt_result1.header.number, 42);
2177
2178        // verify receipts
2179        assert_eq!(receipt_result1.receipts.len(), 2);
2180        assert_eq!(receipt_result1.receipts[0].tx_type, mock_receipt_1.tx_type);
2181        assert_eq!(
2182            receipt_result1.receipts[0].cumulative_gas_used,
2183            mock_receipt_1.cumulative_gas_used
2184        );
2185        assert_eq!(receipt_result1.receipts[0].success, mock_receipt_1.success);
2186        assert_eq!(receipt_result1.receipts[1].tx_type, mock_receipt_2.tx_type);
2187        assert_eq!(
2188            receipt_result1.receipts[1].cumulative_gas_used,
2189            mock_receipt_2.cumulative_gas_used
2190        );
2191        assert_eq!(receipt_result1.receipts[1].success, mock_receipt_2.success);
2192
2193        // second call should return the second queued result
2194        let result2 = range_mode.next().await;
2195        assert!(result2.is_ok());
2196        let receipt_result2 = result2.unwrap().unwrap();
2197        assert_eq!(receipt_result2.header.hash(), expected_block_hash_2);
2198        assert_eq!(receipt_result2.header.number, 43);
2199
2200        // verify receipts
2201        assert_eq!(receipt_result2.receipts.len(), 1);
2202        assert_eq!(receipt_result2.receipts[0].tx_type, mock_receipt_3.tx_type);
2203        assert_eq!(
2204            receipt_result2.receipts[0].cumulative_gas_used,
2205            mock_receipt_3.cumulative_gas_used
2206        );
2207        assert_eq!(receipt_result2.receipts[0].success, mock_receipt_3.success);
2208
2209        // queue should now be empty
2210        assert!(range_mode.next.is_empty());
2211
2212        let result3 = range_mode.next().await;
2213        assert!(result3.is_ok());
2214    }
2215
2216    #[tokio::test]
2217    async fn test_range_block_mode_single_block_missing_receipts() {
2218        let provider = MockEthProvider::default();
2219        let eth_api = build_test_eth_api(provider);
2220
2221        let eth_filter =
2222            super::EthFilter::new(eth_api, EthFilterConfig::default(), Runtime::test());
2223        let filter_inner = eth_filter.inner;
2224
2225        let headers = vec![SealedHeader::new(
2226            alloy_consensus::Header { number: 100, ..Default::default() },
2227            FixedBytes::random(),
2228        )];
2229
2230        let mut range_mode = RangeBlockMode {
2231            filter_inner,
2232            iter: headers.into_iter().peekable(),
2233            next: VecDeque::new(),
2234            max_range: 100,
2235            parallel: false,
2236
2237            pending_tasks: FuturesOrdered::new(),
2238        };
2239
2240        // a block whose header matched the filter but whose receipts are gone must not be
2241        // silently skipped
2242        let Err(err) = range_mode.next().await else { panic!("missing receipts must be an error") };
2243        assert!(matches!(err, EthFilterError::ReceiptsUnavailable(100)), "{err:?}");
2244    }
2245
2246    #[tokio::test]
2247    async fn test_range_block_mode_provider_receipts() {
2248        let provider = MockEthProvider::default();
2249
2250        let header_1 = alloy_consensus::Header { number: 100, ..Default::default() };
2251        let header_2 = alloy_consensus::Header { number: 101, ..Default::default() };
2252        let header_3 = alloy_consensus::Header { number: 102, ..Default::default() };
2253
2254        let block_hash_1 = FixedBytes::random();
2255        let block_hash_2 = FixedBytes::random();
2256        let block_hash_3 = FixedBytes::random();
2257
2258        provider.add_header(block_hash_1, header_1.clone());
2259        provider.add_header(block_hash_2, header_2.clone());
2260        provider.add_header(block_hash_3, header_3.clone());
2261
2262        // create mock receipts to test provider fetching with mock logs
2263        let mock_log = alloy_primitives::Log {
2264            address: alloy_primitives::Address::ZERO,
2265            data: alloy_primitives::LogData::new_unchecked(vec![], alloy_primitives::Bytes::new()),
2266        };
2267
2268        let receipt_100_1 = reth_ethereum_primitives::Receipt {
2269            tx_type: TxType::Legacy,
2270            cumulative_gas_used: 21_000,
2271            logs: vec![mock_log.clone()],
2272            success: true,
2273        };
2274        let receipt_100_2 = reth_ethereum_primitives::Receipt {
2275            tx_type: TxType::Eip1559,
2276            cumulative_gas_used: 42_000,
2277            logs: vec![mock_log.clone()],
2278            success: true,
2279        };
2280        let receipt_101_1 = reth_ethereum_primitives::Receipt {
2281            tx_type: TxType::Eip2930,
2282            cumulative_gas_used: 30_000,
2283            logs: vec![mock_log.clone()],
2284            success: false,
2285        };
2286
2287        provider.add_receipts(100, vec![receipt_100_1.clone(), receipt_100_2.clone()]);
2288        provider.add_receipts(101, vec![receipt_101_1.clone()]);
2289        // a block without transactions, which a provider reports as an empty list
2290        provider.add_receipts(102, vec![]);
2291
2292        let eth_api = build_test_eth_api(provider);
2293
2294        let eth_filter =
2295            super::EthFilter::new(eth_api, EthFilterConfig::default(), Runtime::test());
2296        let filter_inner = eth_filter.inner;
2297
2298        let headers = vec![
2299            SealedHeader::new(header_1, block_hash_1),
2300            SealedHeader::new(header_2, block_hash_2),
2301            SealedHeader::new(header_3, block_hash_3),
2302        ];
2303
2304        let mut range_mode = RangeBlockMode {
2305            filter_inner,
2306            iter: headers.into_iter().peekable(),
2307            next: VecDeque::new(),
2308            max_range: 3, // include the 3 blocks in the first queried results
2309            parallel: false,
2310
2311            pending_tasks: FuturesOrdered::new(),
2312        };
2313
2314        // first call should fetch receipts from provider and return first block with receipts
2315        let result = range_mode.next().await;
2316        assert!(result.is_ok());
2317        let receipt_result = result.unwrap().unwrap();
2318
2319        assert_eq!(receipt_result.header.hash(), block_hash_1);
2320        assert_eq!(receipt_result.header.number, 100);
2321        assert_eq!(receipt_result.receipts.len(), 2);
2322
2323        // verify receipts
2324        assert_eq!(receipt_result.receipts[0].tx_type, receipt_100_1.tx_type);
2325        assert_eq!(
2326            receipt_result.receipts[0].cumulative_gas_used,
2327            receipt_100_1.cumulative_gas_used
2328        );
2329        assert_eq!(receipt_result.receipts[0].success, receipt_100_1.success);
2330
2331        assert_eq!(receipt_result.receipts[1].tx_type, receipt_100_2.tx_type);
2332        assert_eq!(
2333            receipt_result.receipts[1].cumulative_gas_used,
2334            receipt_100_2.cumulative_gas_used
2335        );
2336        assert_eq!(receipt_result.receipts[1].success, receipt_100_2.success);
2337
2338        // second call should return the second block with receipts
2339        let result2 = range_mode.next().await;
2340        assert!(result2.is_ok());
2341        let receipt_result2 = result2.unwrap().unwrap();
2342
2343        assert_eq!(receipt_result2.header.hash(), block_hash_2);
2344        assert_eq!(receipt_result2.header.number, 101);
2345        assert_eq!(receipt_result2.receipts.len(), 1);
2346
2347        // verify receipts
2348        assert_eq!(receipt_result2.receipts[0].tx_type, receipt_101_1.tx_type);
2349        assert_eq!(
2350            receipt_result2.receipts[0].cumulative_gas_used,
2351            receipt_101_1.cumulative_gas_used
2352        );
2353        assert_eq!(receipt_result2.receipts[0].success, receipt_101_1.success);
2354
2355        // third call should return None since no more blocks with receipts
2356        let result3 = range_mode.next().await;
2357        assert!(result3.is_ok());
2358        assert!(result3.unwrap().is_none());
2359    }
2360
2361    #[tokio::test]
2362    async fn test_range_block_mode_iterator_exhaustion() {
2363        let provider = MockEthProvider::default();
2364
2365        let header_100 = alloy_consensus::Header { number: 100, ..Default::default() };
2366        let header_101 = alloy_consensus::Header { number: 101, ..Default::default() };
2367
2368        let block_hash_100 = FixedBytes::random();
2369        let block_hash_101 = FixedBytes::random();
2370
2371        // Associate headers with hashes first
2372        provider.add_header(block_hash_100, header_100.clone());
2373        provider.add_header(block_hash_101, header_101.clone());
2374
2375        // Add mock receipts so headers are actually processed
2376        let mock_receipt = reth_ethereum_primitives::Receipt {
2377            tx_type: TxType::Legacy,
2378            cumulative_gas_used: 21_000,
2379            logs: vec![],
2380            success: true,
2381        };
2382        provider.add_receipts(100, vec![mock_receipt.clone()]);
2383        provider.add_receipts(101, vec![mock_receipt.clone()]);
2384
2385        let eth_api = build_test_eth_api(provider);
2386
2387        let eth_filter =
2388            super::EthFilter::new(eth_api, EthFilterConfig::default(), Runtime::test());
2389        let filter_inner = eth_filter.inner;
2390
2391        let headers = vec![
2392            SealedHeader::new(header_100, block_hash_100),
2393            SealedHeader::new(header_101, block_hash_101),
2394        ];
2395
2396        let mut range_mode = RangeBlockMode {
2397            filter_inner,
2398            iter: headers.into_iter().peekable(),
2399            next: VecDeque::new(),
2400            max_range: 1,
2401            parallel: false,
2402
2403            pending_tasks: FuturesOrdered::new(),
2404        };
2405
2406        let result1 = range_mode.next().await;
2407        assert!(result1.is_ok());
2408        assert!(result1.unwrap().is_some()); // Should have processed block 100
2409
2410        assert!(range_mode.iter.peek().is_some()); // Should still have block 101
2411
2412        let result2 = range_mode.next().await;
2413        assert!(result2.is_ok());
2414        assert!(result2.unwrap().is_some()); // Should have processed block 101
2415
2416        // now iterator should be exhausted
2417        assert!(range_mode.iter.peek().is_none());
2418
2419        // further calls should return None
2420        let result3 = range_mode.next().await;
2421        assert!(result3.is_ok());
2422        assert!(result3.unwrap().is_none());
2423    }
2424
2425    #[tokio::test]
2426    async fn test_cached_mode_with_mock_receipts() {
2427        // create test data
2428        let test_hash = FixedBytes::from([42u8; 32]);
2429        let test_block_number = 100u64;
2430        let test_header = SealedHeader::new(
2431            alloy_consensus::Header {
2432                number: test_block_number,
2433                gas_used: 50_000,
2434                ..Default::default()
2435            },
2436            test_hash,
2437        );
2438
2439        // add a mock receipt to the provider with a mock log
2440        let mock_log = alloy_primitives::Log {
2441            address: alloy_primitives::Address::ZERO,
2442            data: alloy_primitives::LogData::new_unchecked(vec![], alloy_primitives::Bytes::new()),
2443        };
2444
2445        let mock_receipt = reth_ethereum_primitives::Receipt {
2446            tx_type: TxType::Legacy,
2447            cumulative_gas_used: 21_000,
2448            logs: vec![mock_log],
2449            success: true,
2450        };
2451
2452        let provider = MockEthProvider::default();
2453        provider.add_header(test_hash, test_header.header().clone());
2454        provider.add_receipts(test_block_number, vec![mock_receipt.clone()]);
2455
2456        let eth_api = build_test_eth_api(provider);
2457        let eth_filter =
2458            super::EthFilter::new(eth_api, EthFilterConfig::default(), Runtime::test());
2459        let filter_inner = eth_filter.inner;
2460
2461        let headers = vec![test_header.clone()];
2462
2463        let mut cached_mode = CachedMode { filter_inner, headers_iter: headers.into_iter() };
2464
2465        // should find the receipt from provider fallback (cache will be empty)
2466        let result = cached_mode.next().await.expect("next should succeed");
2467        let receipt_block_result = result.expect("should have receipt result");
2468        assert_eq!(receipt_block_result.header.hash(), test_hash);
2469        assert_eq!(receipt_block_result.header.number, test_block_number);
2470        assert_eq!(receipt_block_result.receipts.len(), 1);
2471        assert_eq!(receipt_block_result.receipts[0].tx_type, mock_receipt.tx_type);
2472        assert_eq!(
2473            receipt_block_result.receipts[0].cumulative_gas_used,
2474            mock_receipt.cumulative_gas_used
2475        );
2476        assert_eq!(receipt_block_result.receipts[0].success, mock_receipt.success);
2477
2478        // iterator should be exhausted
2479        let result2 = cached_mode.next().await;
2480        assert!(result2.is_ok());
2481        assert!(result2.unwrap().is_none());
2482    }
2483
2484    #[tokio::test]
2485    async fn test_cached_mode_empty_headers() {
2486        let provider = MockEthProvider::default();
2487        let eth_api = build_test_eth_api(provider);
2488
2489        let eth_filter =
2490            super::EthFilter::new(eth_api, EthFilterConfig::default(), Runtime::test());
2491        let filter_inner = eth_filter.inner;
2492
2493        let headers: Vec<SealedHeader<alloy_consensus::Header>> = vec![];
2494
2495        let mut cached_mode = CachedMode { filter_inner, headers_iter: headers.into_iter() };
2496
2497        // should immediately return None for empty headers
2498        let result = cached_mode.next().await.expect("next should succeed");
2499        assert!(result.is_none());
2500    }
2501
2502    /// Returns a provider with blocks 100 to 102, each with one log with one topic and `data`.
2503    fn provider_with_one_log_per_block(data: alloy_primitives::Bytes) -> MockEthProvider {
2504        let provider = MockEthProvider::default();
2505
2506        let tx_inner = TxLegacy {
2507            chain_id: Some(1),
2508            nonce: 0,
2509            gas_price: 21_000,
2510            gas_limit: 21_000,
2511            to: alloy_primitives::TxKind::Call(alloy_primitives::Address::ZERO),
2512            value: alloy_primitives::U256::ZERO,
2513            input: alloy_primitives::Bytes::new(),
2514        };
2515        let signature = alloy_primitives::Signature::test_signature();
2516        let tx = TransactionSigned::new_unhashed(tx_inner.into(), signature);
2517
2518        let mock_log = alloy_primitives::Log {
2519            address: alloy_primitives::Address::ZERO,
2520            data: alloy_primitives::LogData::new_unchecked(vec![FixedBytes::ZERO], data),
2521        };
2522
2523        let receipt = reth_ethereum_primitives::Receipt {
2524            tx_type: TxType::Legacy,
2525            cumulative_gas_used: 21_000,
2526            logs: vec![mock_log],
2527            success: true,
2528        };
2529
2530        let mut prev_hash = alloy_primitives::B256::default();
2531        for (idx, block_number) in (100u64..=102).enumerate() {
2532            let header = alloy_consensus::Header {
2533                number: block_number,
2534                parent_hash: prev_hash,
2535                logs_bloom: Bloom::repeat_byte(1u8),
2536                ..Default::default()
2537            };
2538            let hash = header.hash_slow();
2539            prev_hash = hash;
2540
2541            let block = reth_ethereum_primitives::Block {
2542                header,
2543                body: reth_ethereum_primitives::BlockBody {
2544                    transactions: vec![tx.clone()],
2545                    ..Default::default()
2546                },
2547            };
2548            provider.add_block(hash, block);
2549            provider.add_receipts(block_number, vec![receipt.clone()]);
2550            provider.add_block_body_indices(
2551                block_number,
2552                StoredBlockBodyIndices { first_tx_num: idx as u64, tx_count: 1 },
2553            );
2554        }
2555
2556        provider
2557    }
2558
2559    #[tokio::test]
2560    async fn test_log_limit_retry_range_excludes_overflow_block() {
2561        let provider = provider_with_one_log_per_block(alloy_primitives::Bytes::new());
2562        let eth_api = build_test_eth_api(provider);
2563        let eth_filter = EthFilter::new(eth_api, EthFilterConfig::default(), Runtime::test());
2564        let err = eth_filter
2565            .inner
2566            .clone()
2567            .get_logs_in_block_range(
2568                Filter::default(),
2569                100,
2570                102,
2571                QueryLimits { max_logs_per_response: Some(2), ..Default::default() },
2572            )
2573            .await
2574            .expect_err("range should exceed max logs");
2575
2576        let EthFilterError::QueryExceedsMaxResults { max_logs, from_block, to_block } = err else {
2577            panic!("unexpected error: {err:?}");
2578        };
2579
2580        assert_eq!(max_logs, 2);
2581        assert_eq!(from_block, 100);
2582        assert_eq!(to_block, 101);
2583    }
2584
2585    #[tokio::test]
2586    async fn test_response_size_retry_range_excludes_overflow_block() {
2587        // Each log is at least 300 + 2 * 1_032 and at most 436 + 2 * 1_032 bytes.
2588        let provider = provider_with_one_log_per_block(vec![0u8; 1_000].into());
2589        let eth_api = build_test_eth_api(provider);
2590        let eth_filter = EthFilter::new(eth_api, EthFilterConfig::default(), Runtime::test());
2591        let transport_accepts = |logs, max_response_size| {
2592            MethodResponse::response(
2593                Id::Number(1),
2594                ResponsePayload::success(logs),
2595                max_response_size,
2596            )
2597            .is_success()
2598        };
2599
2600        // The limit, the end of the retry range and whether the transport accepts that range:
2601        // three blocks exceed 7_000, two blocks may exceed 5_000 and 4_800, and the first block
2602        // alone exceeds 2_000, which is left to the transport like any single block.
2603        for (max_response_size, retry_to_block, accepted) in
2604            [(7_000, 101, true), (5_000, 100, true), (4_800, 100, true), (2_000, 100, false)]
2605        {
2606            let limits =
2607                QueryLimits { max_response_size: Some(max_response_size), ..Default::default() };
2608            let err = eth_filter
2609                .inner
2610                .clone()
2611                .get_logs_in_block_range(Filter::default(), 100, 102, limits)
2612                .await
2613                .expect_err("range should exceed max response size");
2614            let EthFilterError::QueryExceedsMaxResponseSize { max_bytes, from_block, to_block } =
2615                err
2616            else {
2617                panic!("unexpected error: {err:?}");
2618            };
2619            assert_eq!((max_bytes, from_block, to_block), (max_response_size, 100, retry_to_block));
2620
2621            let logs = eth_filter
2622                .inner
2623                .clone()
2624                .get_logs_in_block_range(Filter::default(), 100, retry_to_block, limits)
2625                .await
2626                .unwrap();
2627            assert_eq!(logs.len(), (100..=retry_to_block).count());
2628            assert_eq!(transport_accepts(logs, max_response_size), accepted);
2629        }
2630
2631        // The lower bound alone admits two blocks at 4_800, which the transport rejects.
2632        let limits = QueryLimits { max_response_size: Some(4_800), ..Default::default() };
2633        let logs = eth_filter
2634            .inner
2635            .clone()
2636            .get_logs_in_block_range(Filter::default(), 100, 101, limits)
2637            .await
2638            .unwrap();
2639        assert!(!transport_accepts(logs, 4_800));
2640    }
2641
2642    #[test]
2643    fn test_log_json_size_bounds() {
2644        let rpc_log = |topics, data_len, quantity, block_timestamp| alloy_rpc_types_eth::Log {
2645            inner: alloy_primitives::Log {
2646                address: alloy_primitives::Address::ZERO,
2647                data: alloy_primitives::LogData::new_unchecked(
2648                    vec![FixedBytes::ZERO; topics],
2649                    vec![0u8; data_len].into(),
2650                ),
2651            },
2652            block_hash: Some(FixedBytes::ZERO),
2653            block_number: Some(quantity),
2654            block_timestamp,
2655            transaction_hash: Some(FixedBytes::ZERO),
2656            transaction_index: Some(quantity),
2657            log_index: Some(quantity),
2658            removed: false,
2659        };
2660        // The smallest and the widest encoding of a log.
2661        let smallest = rpc_log(0, 0, 0, None);
2662        let widest = rpc_log(4, 1_000, u64::MAX, Some(u64::MAX));
2663        let hex_len = |log: &alloy_rpc_types_eth::Log| {
2664            (size_of_val(log.topics()) + log.data().data.len()) * 2
2665        };
2666
2667        for log in [&smallest, &widest] {
2668            let (min, max) = (MIN_LOG_JSON_SIZE + hex_len(log), MAX_LOG_JSON_SIZE + hex_len(log));
2669            let json_size = serde_json::to_vec(log).unwrap().len();
2670            // The upper bound includes the separator to the next log.
2671            assert!(min <= json_size && json_size < max, "{min} <= {json_size} < {max}");
2672        }
2673
2674        // The envelope allowance covers the widest numeric request id.
2675        let max = MAX_RESPONSE_ENVELOPE_SIZE + MAX_LOG_JSON_SIZE + hex_len(&widest);
2676        let response = MethodResponse::response(
2677            Id::Number(u64::MAX),
2678            ResponsePayload::success(vec![widest]),
2679            usize::MAX,
2680        );
2681        assert!(response.into_json().len() <= max);
2682    }
2683
2684    #[tokio::test]
2685    async fn test_non_consecutive_headers_after_bloom_filter() {
2686        let provider = MockEthProvider::default();
2687
2688        // Create 4 headers where only blocks 100 and 102 will match bloom filter
2689        let mut expected_hashes = vec![];
2690        let mut prev_hash = alloy_primitives::B256::default();
2691
2692        // Create a transaction for blocks that will have receipts
2693        let tx_inner = TxLegacy {
2694            chain_id: Some(1),
2695            nonce: 0,
2696            gas_price: 21_000,
2697            gas_limit: 21_000,
2698            to: alloy_primitives::TxKind::Call(alloy_primitives::Address::ZERO),
2699            value: alloy_primitives::U256::ZERO,
2700            input: alloy_primitives::Bytes::new(),
2701        };
2702        let signature = alloy_primitives::Signature::test_signature();
2703        let tx = TransactionSigned::new_unhashed(tx_inner.into(), signature);
2704
2705        for i in 100u64..=103 {
2706            let header = alloy_consensus::Header {
2707                number: i,
2708                parent_hash: prev_hash,
2709                // Set bloom to match filter only for blocks 100 and 102
2710                logs_bloom: if i == 100 || i == 102 {
2711                    Bloom::repeat_byte(1u8)
2712                } else {
2713                    alloy_primitives::Bloom::default()
2714                },
2715                ..Default::default()
2716            };
2717
2718            let hash = header.hash_slow();
2719            expected_hashes.push(hash);
2720            prev_hash = hash;
2721
2722            // Add transaction to blocks that will have receipts (100 and 102)
2723            let transactions = if i == 100 || i == 102 { vec![tx.clone()] } else { vec![] };
2724
2725            let block = reth_ethereum_primitives::Block {
2726                header,
2727                body: reth_ethereum_primitives::BlockBody { transactions, ..Default::default() },
2728            };
2729            provider.add_block(hash, block);
2730        }
2731
2732        // Add receipts with logs only to blocks that match bloom
2733        let mock_log = alloy_primitives::Log {
2734            address: alloy_primitives::Address::ZERO,
2735            data: alloy_primitives::LogData::new_unchecked(vec![], alloy_primitives::Bytes::new()),
2736        };
2737
2738        let receipt = reth_ethereum_primitives::Receipt {
2739            tx_type: TxType::Legacy,
2740            cumulative_gas_used: 21_000,
2741            logs: vec![mock_log],
2742            success: true,
2743        };
2744
2745        provider.add_receipts(100, vec![receipt.clone()]);
2746        provider.add_receipts(101, vec![]);
2747        provider.add_receipts(102, vec![receipt.clone()]);
2748        provider.add_receipts(103, vec![]);
2749
2750        // Add block body indices for each block so receipts can be fetched
2751        provider
2752            .add_block_body_indices(100, StoredBlockBodyIndices { first_tx_num: 0, tx_count: 1 });
2753        provider
2754            .add_block_body_indices(101, StoredBlockBodyIndices { first_tx_num: 1, tx_count: 0 });
2755        provider
2756            .add_block_body_indices(102, StoredBlockBodyIndices { first_tx_num: 1, tx_count: 1 });
2757        provider
2758            .add_block_body_indices(103, StoredBlockBodyIndices { first_tx_num: 2, tx_count: 0 });
2759
2760        let eth_api = build_test_eth_api(provider);
2761        let eth_filter = EthFilter::new(eth_api, EthFilterConfig::default(), Runtime::test());
2762
2763        // Use default filter which will match any non-empty bloom
2764        let filter = Filter::default();
2765
2766        // Get logs in the range - this will trigger the bloom filtering
2767        let logs = eth_filter
2768            .inner
2769            .clone()
2770            .get_logs_in_block_range(filter, 100, 103, QueryLimits::default())
2771            .await
2772            .expect("should succeed");
2773
2774        // We should get logs from blocks 100 and 102 only (bloom filtered)
2775        assert_eq!(logs.len(), 2);
2776
2777        assert_eq!(logs[0].block_number, Some(100));
2778        assert_eq!(logs[1].block_number, Some(102));
2779
2780        // Each block hash should be the hash of its own header, not derived from any other header
2781        assert_eq!(logs[0].block_hash, Some(expected_hashes[0])); // block 100
2782        assert_eq!(logs[1].block_hash, Some(expected_hashes[2])); // block 102
2783    }
2784
2785    #[tokio::test]
2786    async fn test_range_scan_waits_for_blocking_io_permit() {
2787        let provider = MockEthProvider::default();
2788        let header = alloy_consensus::Header::default();
2789        provider.add_header(header.hash_slow(), header);
2790        provider.add_receipts(0, vec![]);
2791        let eth_api = build_test_eth_api(provider);
2792
2793        // take every permit so the scan has to wait for one
2794        let guard = eth_api.blocking_io_task_guard().clone();
2795        let permits =
2796            guard.clone().acquire_many_owned(guard.available_permits() as u32).await.unwrap();
2797
2798        let eth_filter = EthFilter::new(eth_api, EthFilterConfig::default(), Runtime::test());
2799        let scan = eth_filter.inner.clone().get_logs_in_block_range(
2800            Filter::default(),
2801            0,
2802            0,
2803            QueryLimits::default(),
2804        );
2805        tokio::pin!(scan);
2806        assert!(
2807            tokio::time::timeout(Duration::from_millis(100), &mut scan).await.is_err(),
2808            "scan must wait for a blocking IO permit"
2809        );
2810
2811        drop(permits);
2812        assert!(scan.await.unwrap().is_empty());
2813    }
2814
2815    #[tokio::test]
2816    async fn test_range_scan_across_windows() {
2817        let provider = MockEthProvider::default();
2818        let tx = TransactionSigned::new_unhashed(
2819            TxLegacy {
2820                chain_id: Some(1),
2821                gas_price: 21_000,
2822                gas_limit: 21_000,
2823                ..Default::default()
2824            }
2825            .into(),
2826            Signature::test_signature(),
2827        );
2828        let receipt = Receipt {
2829            tx_type: TxType::Legacy,
2830            cumulative_gas_used: 21_000,
2831            logs: vec![Log {
2832                address: Address::ZERO,
2833                data: LogData::new_unchecked(vec![], Bytes::new()),
2834            }],
2835            success: true,
2836        };
2837
2838        // an empty filter matches every header, so every window is fetched in parallel while
2839        // only three blocks have logs to return
2840        let matching_blocks = [5u64, 1_200, 2_400];
2841        let mut parent_hash = FixedBytes::default();
2842        for number in 0..=2_500u64 {
2843            let matches = matching_blocks.contains(&number);
2844            let header = alloy_consensus::Header {
2845                number,
2846                parent_hash,
2847                logs_bloom: if matches { Bloom::repeat_byte(1u8) } else { Bloom::default() },
2848                ..Default::default()
2849            };
2850            parent_hash = header.hash_slow();
2851            let transactions = if matches { vec![tx.clone()] } else { Vec::new() };
2852            provider.add_block(
2853                parent_hash,
2854                Block { header, body: BlockBody { transactions, ..Default::default() } },
2855            );
2856            if matches {
2857                let tx_num = matching_blocks.iter().position(|b| *b == number).unwrap() as u64;
2858                provider.add_receipts(number, vec![receipt.clone()]);
2859                provider.add_block_body_indices(
2860                    number,
2861                    StoredBlockBodyIndices { first_tx_num: tx_num, tx_count: 1 },
2862                );
2863            } else {
2864                provider.add_receipts(number, vec![]);
2865            }
2866        }
2867
2868        let eth_filter = EthFilter::new(
2869            build_test_eth_api(provider),
2870            EthFilterConfig::default(),
2871            Runtime::test(),
2872        );
2873        let logs = eth_filter
2874            .inner
2875            .clone()
2876            .get_logs_in_block_range(Filter::default(), 0, 2_500, QueryLimits::default())
2877            .await
2878            .unwrap();
2879        let blocks = logs.iter().map(|log| log.block_number.unwrap()).collect::<Vec<_>>();
2880        assert_eq!(blocks, matching_blocks);
2881
2882        // the log limit ends the scan in the window that exceeds it and names the last block that
2883        // fit as the range to retry with
2884        let err = eth_filter
2885            .inner
2886            .clone()
2887            .get_logs_in_block_range(
2888                Filter::default(),
2889                0,
2890                2_500,
2891                QueryLimits { max_logs_per_response: Some(1), ..Default::default() },
2892            )
2893            .await
2894            .unwrap_err();
2895        assert!(
2896            matches!(
2897                err,
2898                EthFilterError::QueryExceedsMaxResults {
2899                    max_logs: 1,
2900                    from_block: 0,
2901                    to_block: 1_199
2902                }
2903            ),
2904            "{err:?}"
2905        );
2906    }
2907
2908    #[tokio::test]
2909    async fn test_logs_for_filter_pending_to_block_ends_at_head() {
2910        let provider = MockEthProvider::default();
2911        let header = alloy_consensus::Header { number: 2, ..Default::default() };
2912        let hash = header.hash_slow();
2913        provider.add_header(hash, header);
2914        provider.add_receipts(2, vec![]);
2915        // the engine holds a payload that is not canonical yet
2916        provider.set_pending_block_num_hash(Some(alloy_eips::BlockNumHash::new(3, hash)));
2917
2918        let eth_filter = EthFilter::new(
2919            build_test_eth_api(provider),
2920            EthFilterConfig::default(),
2921            Runtime::test(),
2922        );
2923        for filter in [
2924            Filter::new().from_block(0u64).to_block(BlockNumberOrTag::Pending),
2925            Filter::new().select(BlockNumberOrTag::Pending..),
2926        ] {
2927            let logs = eth_filter
2928                .inner
2929                .clone()
2930                .logs_for_filter(filter, QueryLimits::default())
2931                .await
2932                .unwrap();
2933            assert!(logs.is_empty());
2934        }
2935    }
2936
2937    #[tokio::test]
2938    async fn test_logs_for_filter_over_pruned_receipts() {
2939        let provider = MockEthProvider::default();
2940        let mut parent_hash = FixedBytes::default();
2941        for number in 0..=2u64 {
2942            let header = alloy_consensus::Header {
2943                number,
2944                parent_hash,
2945                logs_bloom: Bloom::repeat_byte(1u8),
2946                ..Default::default()
2947            };
2948            parent_hash = header.hash_slow();
2949            provider.add_block(
2950                parent_hash,
2951                reth_ethereum_primitives::Block { header, body: Default::default() },
2952            );
2953            // the receipts of block 1 were pruned
2954            if number != 1 {
2955                provider.add_receipts(number, vec![]);
2956            }
2957        }
2958
2959        let eth_filter = EthFilter::new(
2960            build_test_eth_api(provider),
2961            EthFilterConfig::default(),
2962            Runtime::test(),
2963        );
2964
2965        // a range that reaches the pruned block is rejected instead of served incompletely
2966        let err = eth_filter
2967            .inner
2968            .clone()
2969            .logs_for_filter(Filter::new().from_block(0u64).to_block(2u64), QueryLimits::default())
2970            .await
2971            .unwrap_err();
2972        assert!(matches!(err, EthFilterError::ReceiptsUnavailable(1)), "{err:?}");
2973
2974        // a range that avoids it is served
2975        let logs = eth_filter
2976            .inner
2977            .clone()
2978            .logs_for_filter(Filter::new().from_block(2u64).to_block(2u64), QueryLimits::default())
2979            .await
2980            .unwrap();
2981        assert!(logs.is_empty());
2982    }
2983
2984    /// How long a test waits for the feed to deliver or stop.
2985    const TIMEOUT: Duration = Duration::from_secs(5);
2986
2987    /// Returns a provider that has a best block, which installing a filter reads.
2988    fn provider_with_head() -> MockEthProvider {
2989        let provider = MockEthProvider::default();
2990        provider.add_header(FixedBytes::random(), alloy_consensus::Header::default());
2991        provider
2992    }
2993
2994    fn hash_feed_sender<Eth: EthApiTypes>(
2995        filter: &EthFilter<Eth>,
2996    ) -> Option<broadcast::Sender<TxHash>> {
2997        filter.inner.pending_transaction_hashes.sender.lock().as_ref()?.upgrade()
2998    }
2999
3000    /// Returns the kind of the pending transaction filter with the given id.
3001    async fn pending_kind<Eth: EthApiTypes + 'static>(
3002        filter: &EthFilter<Eth>,
3003        id: &FilterId,
3004    ) -> PendingTransactionKind<RpcTransaction<Eth::NetworkTypes>> {
3005        match filter.active_filters().inner.lock().await.get(id).unwrap().kind.clone() {
3006            FilterKind::PendingTransaction(kind) => kind,
3007            kind => panic!("not a pending transaction filter: {kind:?}"),
3008        }
3009    }
3010
3011    /// Drains the hash filter until it returned `count` hashes.
3012    async fn drain_hashes<Eth: EthApiTypes + 'static>(
3013        filter: &EthFilter<Eth>,
3014        id: &FilterId,
3015        count: usize,
3016    ) -> Vec<TxHash> {
3017        let kind = pending_kind(filter, id).await;
3018        tokio::time::timeout(TIMEOUT, async {
3019            let mut hashes = Vec::new();
3020            while hashes.len() < count {
3021                match kind.drain().await {
3022                    FilterChanges::Hashes(new) => hashes.extend(new),
3023                    changes => panic!("unexpected changes {changes:?}"),
3024                }
3025                tokio::time::sleep(Duration::from_millis(5)).await;
3026            }
3027            hashes
3028        })
3029        .await
3030        .expect("filter did not receive the transactions")
3031    }
3032
3033    /// Waits until the hash feed has stopped.
3034    async fn wait_for_feed_stop<Eth: EthApiTypes>(filter: &EthFilter<Eth>) {
3035        tokio::time::timeout(TIMEOUT, async {
3036            while hash_feed_sender(filter).is_some() {
3037                tokio::time::sleep(Duration::from_millis(5)).await;
3038            }
3039        })
3040        .await
3041        .expect("feed did not stop")
3042    }
3043
3044    #[tokio::test]
3045    async fn pending_hash_filters_share_a_feed() {
3046        let eth_api = build_test_eth_api(provider_with_head());
3047        let pool = eth_api.pool().clone();
3048        let eth_filter = EthFilter::new(eth_api, EthFilterConfig::default(), Runtime::test());
3049
3050        assert!(hash_feed_sender(&eth_filter).is_none());
3051        let first = eth_filter.new_pending_transaction_filter(None).await.unwrap();
3052        let second = eth_filter.new_pending_transaction_filter(None).await.unwrap();
3053        assert_eq!(hash_feed_sender(&eth_filter).unwrap().receiver_count(), 2);
3054
3055        let hash = pool
3056            .add_transaction(TransactionOrigin::External, MockTransaction::eip1559())
3057            .await
3058            .unwrap()
3059            .hash;
3060        assert_eq!(drain_hashes(&eth_filter, &first, 1).await, [hash]);
3061        assert_eq!(drain_hashes(&eth_filter, &second, 1).await, [hash]);
3062
3063        // A filter only sees the transactions that arrive after it was created.
3064        let third = eth_filter.new_pending_transaction_filter(None).await.unwrap();
3065        let next_hash = pool
3066            .add_transaction(TransactionOrigin::External, MockTransaction::eip1559())
3067            .await
3068            .unwrap()
3069            .hash;
3070        for id in [&first, &second, &third] {
3071            assert_eq!(drain_hashes(&eth_filter, id, 1).await, [next_hash]);
3072        }
3073    }
3074
3075    #[tokio::test]
3076    async fn pending_hash_feed_stops_with_its_last_filter() {
3077        let eth_api = build_test_eth_api(provider_with_head());
3078        let pool = eth_api.pool().clone();
3079        let eth_filter = EthFilter::new(eth_api, EthFilterConfig::default(), Runtime::test());
3080
3081        let first = eth_filter.new_pending_transaction_filter(None).await.unwrap();
3082        let second = eth_filter.new_pending_transaction_filter(None).await.unwrap();
3083
3084        // The feed outlives a filter that is uninstalled.
3085        assert!(eth_filter.uninstall_filter(first).await.unwrap());
3086        assert_eq!(hash_feed_sender(&eth_filter).unwrap().receiver_count(), 1);
3087
3088        // It stops once the last filter is evicted as stale.
3089        eth_filter.clear_stale_filters(Instant::now() + Duration::from_secs(3600)).await;
3090        assert!(!eth_filter.active_filters().contains(&second).await);
3091        wait_for_feed_stop(&eth_filter).await;
3092
3093        // A later filter starts a new producer.
3094        let third = eth_filter.new_pending_transaction_filter(None).await.unwrap();
3095        let hash = pool
3096            .add_transaction(TransactionOrigin::External, MockTransaction::eip1559())
3097            .await
3098            .unwrap()
3099            .hash;
3100        assert_eq!(drain_hashes(&eth_filter, &third, 1).await, [hash]);
3101    }
3102
3103    #[tokio::test]
3104    async fn lagging_hash_filter_keeps_the_newest_hashes() {
3105        const CAPACITY: usize = 4;
3106
3107        let hashes = (0..10u8).map(|byte| TxHash::repeat_byte(byte + 1)).collect::<Vec<_>>();
3108        let feed = Arc::new(TxFeed::new());
3109        let runtime = Runtime::test();
3110        // The source ends after it is forwarded, which stops the producer, and the filter has
3111        // not been polled until then.
3112        let receiver = PendingTransactionsReceiver::new(
3113            feed.subscribe(&runtime, || (stream::iter(hashes.clone()), CAPACITY)),
3114        );
3115        tokio::time::timeout(TIMEOUT, async {
3116            while feed.sender.lock().is_some() {
3117                tokio::time::sleep(Duration::from_millis(5)).await;
3118            }
3119        })
3120        .await
3121        .expect("feed did not stop");
3122
3123        let FilterChanges::Hashes(drained) = receiver.drain::<()>().await else {
3124            panic!("expected hashes")
3125        };
3126        assert_eq!(drained, hashes[hashes.len() - CAPACITY..]);
3127        assert!(
3128            matches!(receiver.drain::<()>().await, FilterChanges::Hashes(hashes) if hashes.is_empty())
3129        );
3130    }
3131
3132    #[tokio::test]
3133    async fn hash_feed_holds_as_many_hashes_as_the_pool_listener() {
3134        // More than the default listener buffer of 2048, which a fixed-size feed would cap at.
3135        const BUFFER: usize = 4096;
3136        const TXS: usize = 3000;
3137
3138        let pool = TestPool::from(TestPoolBuilder::default().with_config(PoolConfig {
3139            pending_tx_listener_buffer_size: BUFFER,
3140            ..Default::default()
3141        }));
3142        let eth_api = build_test_eth_api_with_pool(provider_with_head(), pool.clone());
3143        let eth_filter = EthFilter::new(eth_api, EthFilterConfig::default(), Runtime::test());
3144        let id = eth_filter.new_pending_transaction_filter(None).await.unwrap();
3145
3146        let txs = (0..TXS).map(|_| MockTransaction::eip1559()).collect::<Vec<_>>();
3147        let hashes = txs.iter().map(|tx| *tx.hash()).collect::<Vec<_>>();
3148        for result in pool.add_transactions(TransactionOrigin::External, txs).await {
3149            result.unwrap();
3150        }
3151
3152        // Poll only once the feed holds every hash, so the filter has to keep all of them.
3153        let sender = hash_feed_sender(&eth_filter).unwrap();
3154        tokio::time::timeout(TIMEOUT, async {
3155            while sender.len() < TXS {
3156                tokio::time::sleep(Duration::from_millis(5)).await;
3157            }
3158        })
3159        .await
3160        .expect("feed did not hold every hash");
3161        assert_eq!(drain_hashes(&eth_filter, &id, TXS).await, hashes);
3162    }
3163
3164    #[tokio::test]
3165    async fn feeds_cap_a_huge_pool_listener_buffer() {
3166        // The pool's listener channels never allocate their buffer, but a feed of this capacity
3167        // could not be allocated.
3168        const BUFFER: usize = usize::MAX >> 4;
3169
3170        let pool = TestPool::from(TestPoolBuilder::default().with_config(PoolConfig {
3171            pending_tx_listener_buffer_size: BUFFER,
3172            new_tx_listener_buffer_size: BUFFER,
3173            ..Default::default()
3174        }));
3175        let eth_api = build_test_eth_api_with_pool(provider_with_head(), pool.clone());
3176        let eth_filter = EthFilter::new(eth_api, EthFilterConfig::default(), Runtime::test());
3177
3178        let id = eth_filter.new_pending_transaction_filter(None).await.unwrap();
3179        eth_filter
3180            .new_pending_transaction_filter(Some(PendingTransactionFilterKind::Full))
3181            .await
3182            .unwrap();
3183        let hash = pool
3184            .add_transaction(TransactionOrigin::External, MockTransaction::eip1559())
3185            .await
3186            .unwrap()
3187            .hash;
3188        assert_eq!(drain_hashes(&eth_filter, &id, 1).await, [hash]);
3189    }
3190
3191    #[tokio::test]
3192    async fn full_pending_filters_share_a_feed() {
3193        let eth_api = build_test_eth_api(provider_with_head());
3194        let pool = eth_api.pool().clone();
3195        let eth_filter = EthFilter::new(eth_api, EthFilterConfig::default(), Runtime::test());
3196
3197        let first = eth_filter
3198            .new_pending_transaction_filter(Some(PendingTransactionFilterKind::Full))
3199            .await
3200            .unwrap();
3201        let second = eth_filter
3202            .new_pending_transaction_filter(Some(PendingTransactionFilterKind::Full))
3203            .await
3204            .unwrap();
3205
3206        let hash = pool
3207            .add_transaction(TransactionOrigin::External, MockTransaction::eip1559())
3208            .await
3209            .unwrap()
3210            .hash;
3211
3212        for id in [&first, &second] {
3213            let kind = pending_kind(&eth_filter, id).await;
3214            let txs = tokio::time::timeout(TIMEOUT, async {
3215                loop {
3216                    match kind.drain().await {
3217                        FilterChanges::Transactions(txs) if !txs.is_empty() => break txs,
3218                        FilterChanges::Transactions(_) => {
3219                            tokio::time::sleep(Duration::from_millis(5)).await
3220                        }
3221                        changes => panic!("unexpected changes {changes:?}"),
3222                    }
3223                }
3224            })
3225            .await
3226            .expect("filter did not receive the transaction");
3227            assert_eq!(txs.iter().map(|tx| tx.tx_hash()).collect::<Vec<_>>(), [hash]);
3228        }
3229    }
3230
3231    #[tokio::test]
3232    async fn full_pending_filter_is_served_through_filter_changes() {
3233        let eth_api = build_test_eth_api(provider_with_head());
3234        let pool = eth_api.pool().clone();
3235        let eth_filter = EthFilter::new(eth_api, EthFilterConfig::default(), Runtime::test());
3236
3237        let id = eth_filter
3238            .new_pending_transaction_filter(Some(PendingTransactionFilterKind::Full))
3239            .await
3240            .unwrap();
3241        let hash = pool
3242            .add_transaction(TransactionOrigin::External, MockTransaction::eip1559())
3243            .await
3244            .unwrap()
3245            .hash;
3246
3247        // The feed forwards the transaction asynchronously, so poll until it arrives.
3248        let txs = tokio::time::timeout(TIMEOUT, async {
3249            loop {
3250                match eth_filter.filter_changes(id.clone()).await.unwrap() {
3251                    FilterChanges::Transactions(txs) if !txs.is_empty() => break txs,
3252                    FilterChanges::Transactions(_) => {
3253                        tokio::time::sleep(Duration::from_millis(5)).await
3254                    }
3255                    changes => panic!("unexpected changes {changes:?}"),
3256                }
3257            }
3258        })
3259        .await
3260        .expect("filter did not receive the transaction");
3261        assert_eq!(txs.iter().map(|tx| tx.tx_hash()).collect::<Vec<_>>(), [hash]);
3262    }
3263
3264    #[tokio::test]
3265    async fn too_many_filters_are_rejected() {
3266        let eth_api = build_test_eth_api(provider_with_head());
3267        let config = EthFilterConfig::default().max_active_filters(Some(2));
3268        let eth_filter = EthFilter::new(eth_api, config, Runtime::test());
3269
3270        let block_filter = eth_filter.new_block_filter().await.unwrap();
3271        eth_filter.new_filter(Filter::new()).await.unwrap();
3272
3273        for kind in [None, Some(PendingTransactionFilterKind::Full)] {
3274            let err = eth_filter.new_pending_transaction_filter(kind).await.unwrap_err();
3275            assert_eq!(err.code(), LIMIT_EXCEEDED_CODE);
3276            assert_eq!(err.message(), "too many active filters, max 2");
3277        }
3278        assert_eq!(eth_filter.new_block_filter().await.unwrap_err().code(), LIMIT_EXCEEDED_CODE);
3279        assert_eq!(
3280            eth_filter.new_filter(Filter::new()).await.unwrap_err().code(),
3281            LIMIT_EXCEEDED_CODE
3282        );
3283        assert_eq!(eth_filter.active_filters().len().await, 2);
3284
3285        // A rejected pending filter must not start a feed.
3286        assert!(hash_feed_sender(&eth_filter).is_none());
3287        assert!(eth_filter.inner.full_pending_transactions.get().is_none());
3288
3289        // Uninstalling frees a slot for any kind.
3290        assert!(eth_filter.uninstall_filter(block_filter).await.unwrap());
3291        eth_filter.new_pending_transaction_filter(None).await.unwrap();
3292        assert!(hash_feed_sender(&eth_filter).is_some());
3293        assert_eq!(
3294            eth_filter.new_block_filter().await.unwrap_err().message(),
3295            "too many active filters, max 2"
3296        );
3297    }
3298
3299    #[tokio::test]
3300    async fn unlimited_filters_when_no_maximum_is_configured() {
3301        let eth_api = build_test_eth_api(provider_with_head());
3302        let config = EthFilterConfig::default().max_active_filters(None);
3303        let eth_filter = EthFilter::new(eth_api, config, Runtime::test());
3304
3305        for _ in 0..50 {
3306            eth_filter.new_block_filter().await.unwrap();
3307        }
3308        assert_eq!(eth_filter.active_filters().len().await, 50);
3309    }
3310
3311    /// Adds a block with logs in two of its five receipts to the provider, but not to the cache.
3312    fn add_block_with_logs(
3313        provider: &MockEthProvider,
3314    ) -> (SealedHeader<alloy_consensus::Header>, Vec<Receipt>) {
3315        let transactions = (0..5)
3316            .map(|nonce| {
3317                TransactionSigned::new_unhashed(
3318                    TxLegacy {
3319                        chain_id: Some(1),
3320                        nonce,
3321                        gas_price: 21_000,
3322                        gas_limit: 21_000,
3323                        ..Default::default()
3324                    }
3325                    .into(),
3326                    Signature::test_signature(),
3327                )
3328            })
3329            .collect();
3330        let log = |address: u8, topic: u8| Log {
3331            address: Address::repeat_byte(address),
3332            data: LogData::new_unchecked(vec![B256::repeat_byte(topic)], Bytes::new()),
3333        };
3334        let receipts = vec![
3335            Receipt {
3336                tx_type: TxType::Legacy,
3337                cumulative_gas_used: 21_000,
3338                logs: vec![log(1, 1), log(2, 2)],
3339                success: true,
3340            },
3341            Receipt {
3342                tx_type: TxType::Legacy,
3343                cumulative_gas_used: 42_000,
3344                logs: vec![],
3345                success: true,
3346            },
3347            Receipt {
3348                tx_type: TxType::Legacy,
3349                cumulative_gas_used: 63_000,
3350                logs: vec![log(1, 2), log(3, 1), log(1, 1)],
3351                success: true,
3352            },
3353            Receipt {
3354                tx_type: TxType::Legacy,
3355                cumulative_gas_used: 84_000,
3356                logs: vec![],
3357                success: true,
3358            },
3359            Receipt {
3360                tx_type: TxType::Legacy,
3361                cumulative_gas_used: 105_000,
3362                logs: vec![],
3363                success: true,
3364            },
3365        ];
3366
3367        let mut logs_bloom = Bloom::default();
3368        for log in receipts.iter().flat_map(|receipt| &receipt.logs) {
3369            logs_bloom.accrue_log(log);
3370        }
3371        let header = alloy_consensus::Header {
3372            number: 7,
3373            timestamp: 1_234,
3374            logs_bloom,
3375            ..Default::default()
3376        };
3377        let hash = header.hash_slow();
3378        provider.add_block(
3379            hash,
3380            Block {
3381                header: header.clone(),
3382                body: BlockBody { transactions, ..Default::default() },
3383            },
3384        );
3385        provider.add_receipts(7, receipts.clone());
3386        provider.add_block_body_indices(7, StoredBlockBodyIndices { first_tx_num: 0, tx_count: 5 });
3387
3388        (SealedHeader::new(header, hash), receipts)
3389    }
3390
3391    #[reth_concurrency::test]
3392    async fn test_logs_at_block_hash_from_provider() {
3393        let provider = MockEthProvider::default();
3394        let (header, receipts) = add_block_with_logs(&provider);
3395        let eth_api = build_test_eth_api(provider.clone());
3396        let eth_filter =
3397            EthFilter::new(eth_api.clone(), EthFilterConfig::default(), Runtime::test());
3398
3399        let logs = eth_filter
3400            .logs_for_filter(Filter::new().at_block_hash(header.hash()), QueryLimits::default())
3401            .await
3402            .unwrap();
3403        let tx_hashes = provider
3404            .transactions_by_block(header.hash().into())
3405            .unwrap()
3406            .unwrap()
3407            .iter()
3408            .map(|tx| *tx.tx_hash())
3409            .collect::<Vec<_>>();
3410        assert_eq!(
3411            logs.iter()
3412                .map(|log| (
3413                    log.transaction_hash.unwrap(),
3414                    log.transaction_index.unwrap(),
3415                    log.log_index.unwrap()
3416                ))
3417                .collect::<Vec<_>>(),
3418            [
3419                (tx_hashes[0], 0, 0),
3420                (tx_hashes[0], 0, 1),
3421                (tx_hashes[2], 2, 2),
3422                (tx_hashes[2], 2, 3),
3423                (tx_hashes[2], 2, 4),
3424            ]
3425        );
3426        assert_eq!(
3427            logs.iter().map(|log| log.inner.clone()).collect::<Vec<_>>(),
3428            receipts.iter().flat_map(|receipt| receipt.logs.clone()).collect::<Vec<_>>()
3429        );
3430        for log in &logs {
3431            assert_eq!(log.block_hash, Some(header.hash()));
3432            assert_eq!(log.block_number, Some(7));
3433            assert_eq!(log.block_timestamp, Some(1_234));
3434            assert!(!log.removed);
3435        }
3436
3437        for filter in [
3438            Filter::new(),
3439            Filter::new().address(Address::repeat_byte(1)),
3440            Filter::new().event_signature(B256::repeat_byte(1)),
3441            Filter::new().address(Address::repeat_byte(1)).event_signature(B256::repeat_byte(2)),
3442            Filter::new().address(Address::repeat_byte(3)).event_signature(B256::repeat_byte(2)),
3443            Filter::new().address(Address::repeat_byte(4)),
3444        ] {
3445            let filter = filter.at_block_hash(header.hash());
3446            let logs =
3447                eth_filter.logs_for_filter(filter.clone(), QueryLimits::default()).await.unwrap();
3448
3449            // the logs looking up each transaction by its id produces.
3450            let mut expected = Vec::new();
3451            append_matching_block_logs(
3452                &mut expected,
3453                eth_api.converter(),
3454                ProviderOrBlock::Provider(&provider),
3455                &filter,
3456                &header,
3457                &receipts,
3458                false,
3459            )
3460            .unwrap();
3461            assert_eq!(logs, expected, "{filter:?}");
3462
3463            // `eth_getFilterLogs` serves an installed filter the same way.
3464            let id = EthFilterApiServer::new_filter(&eth_filter, filter).await.unwrap();
3465            assert_eq!(EthFilter::filter_logs(&eth_filter, id).await.unwrap(), expected);
3466        }
3467    }
3468
3469    #[tokio::test]
3470    async fn test_logs_at_block_hash_rejects_replaced_block() {
3471        let provider = MockEthProvider::default();
3472        let (header, receipts) = add_block_with_logs(&provider);
3473        let eth_api = build_test_eth_api(provider);
3474
3475        // a block at the same height whose hash no longer resolves, as after a reorg, must not be
3476        // served with the transactions found at that height, whether they are read for the whole
3477        // block or for the one receipt with a matching log.
3478        let replaced = SealedHeader::new(header.clone_header(), B256::repeat_byte(0xab));
3479        // a block at a height that no longer exists makes the lookups fail, which is reported the
3480        // same way.
3481        let dropped = SealedHeader::new(
3482            alloy_consensus::Header { number: 8, ..header.clone_header() },
3483            B256::repeat_byte(0xab),
3484        );
3485        for (replaced, filter) in [
3486            (&replaced, Filter::new()),
3487            (&replaced, Filter::new().address(Address::repeat_byte(3))),
3488            (&dropped, Filter::new().address(Address::repeat_byte(3))),
3489        ] {
3490            let err = EthFilterInner::block_logs_from_provider(
3491                &eth_api,
3492                &filter.at_block_hash(replaced.hash()),
3493                replaced,
3494                &receipts,
3495            )
3496            .unwrap_err();
3497            assert!(
3498                matches!(
3499                    &err,
3500                    EthFilterError::EthAPIError(EthApiError::HeaderNotFound(id))
3501                        if *id == BlockId::from(replaced.hash())
3502                ),
3503                "{err:?}"
3504            );
3505        }
3506    }
3507
3508    #[reth_concurrency::test]
3509    async fn test_logs_at_block_hash_caches_receipts() {
3510        let provider = MockEthProvider::default();
3511        let (header, _) = add_block_with_logs(&provider);
3512        let eth_api = build_test_eth_api(provider);
3513        let eth_filter =
3514            EthFilter::new(eth_api.clone(), EthFilterConfig::default(), Runtime::test());
3515        let cached_receipts = async || {
3516            eth_api.cache().maybe_cached_block_and_receipts(header.hash()).await.unwrap().1
3517        };
3518
3519        // a filter the bloom rules out leaves the receipts unread.
3520        let filter = Filter::new().address(Address::repeat_byte(9)).at_block_hash(header.hash());
3521        let logs = eth_filter.logs_for_filter(filter, QueryLimits::default()).await.unwrap();
3522        assert!(logs.is_empty());
3523        assert!(cached_receipts().await.is_none());
3524
3525        // a matching filter reads them through the cache, which keeps them for later queries.
3526        let filter = Filter::new().at_block_hash(header.hash());
3527        let logs = eth_filter.logs_for_filter(filter, QueryLimits::default()).await.unwrap();
3528        assert_eq!(logs.len(), 5);
3529        assert!(cached_receipts().await.is_some());
3530
3531        // with the receipts cached, the bloom still rules out a filter.
3532        let filter = Filter::new().address(Address::repeat_byte(9)).at_block_hash(header.hash());
3533        let logs = eth_filter.logs_for_filter(filter, QueryLimits::default()).await.unwrap();
3534        assert!(logs.is_empty());
3535    }
3536
3537    #[reth_concurrency::test]
3538    async fn test_logs_at_block_hash_cached_block() {
3539        let provider = MockEthProvider::default();
3540        let (header, _) = add_block_with_logs(&provider);
3541        let eth_api = build_test_eth_api(provider);
3542        let eth_filter =
3543            EthFilter::new(eth_api.clone(), EthFilterConfig::default(), Runtime::test());
3544        let filter = Filter::new().at_block_hash(header.hash());
3545
3546        let uncached =
3547            eth_filter.logs_for_filter(filter.clone(), QueryLimits::default()).await.unwrap();
3548        eth_api.cache().get_recovered_block(header.hash()).await.unwrap().unwrap();
3549
3550        // a cached block is served without a blocking IO permit.
3551        let guard = eth_api.blocking_io_task_guard().clone();
3552        let _permits =
3553            guard.clone().acquire_many_owned(guard.available_permits() as u32).await.unwrap();
3554        let cached = tokio::time::timeout(
3555            Duration::from_secs(5),
3556            eth_filter.logs_for_filter(filter, QueryLimits::default()),
3557        )
3558        .await
3559        .expect("a cached block must not wait for a blocking IO permit")
3560        .unwrap();
3561        assert_eq!(cached, uncached);
3562    }
3563
3564    #[reth_concurrency::test]
3565    async fn test_logs_at_block_hash_waits_for_blocking_io_permit() {
3566        let provider = MockEthProvider::default();
3567        let (header, _) = add_block_with_logs(&provider);
3568        let eth_api = build_test_eth_api(provider);
3569
3570        // take every permit so the provider reads have to wait for one.
3571        let guard = eth_api.blocking_io_task_guard().clone();
3572        let permits =
3573            guard.clone().acquire_many_owned(guard.available_permits() as u32).await.unwrap();
3574
3575        let eth_filter =
3576            EthFilter::new(eth_api.clone(), EthFilterConfig::default(), Runtime::test());
3577        let logs = eth_filter
3578            .logs_for_filter(Filter::new().at_block_hash(header.hash()), QueryLimits::default());
3579        tokio::pin!(logs);
3580        assert!(futures::poll!(&mut logs).is_pending());
3581        // Cache requests are FIFO. Once this reply arrives, the log lookup can reach the permit.
3582        eth_api.cache().maybe_cached_block_and_receipts(header.hash()).await.unwrap();
3583        assert!(futures::poll!(&mut logs).is_pending());
3584
3585        let total = permits.num_permits();
3586        drop(permits);
3587        assert_eq!(guard.available_permits(), total - 1);
3588        assert_eq!(logs.await.unwrap().len(), 5);
3589    }
3590
3591    #[reth_concurrency::test]
3592    async fn test_logs_at_block_hash_errors() {
3593        let provider = MockEthProvider::default();
3594        let header = alloy_consensus::Header { number: 3, ..Default::default() };
3595        let hash = header.hash_slow();
3596        // a block whose receipts were pruned.
3597        provider.add_block(hash, Block { header, body: Default::default() });
3598        let eth_filter = EthFilter::new(
3599            build_test_eth_api(provider),
3600            EthFilterConfig::default(),
3601            Runtime::test(),
3602        );
3603
3604        let err = eth_filter
3605            .logs_for_filter(Filter::new().at_block_hash(hash), QueryLimits::default())
3606            .await
3607            .unwrap_err();
3608        assert!(matches!(err, EthFilterError::ReceiptsUnavailable(3)), "{err:?}");
3609
3610        let unknown = B256::repeat_byte(0xab);
3611        let err = eth_filter
3612            .logs_for_filter(Filter::new().at_block_hash(unknown), QueryLimits::default())
3613            .await
3614            .unwrap_err();
3615        assert!(
3616            matches!(
3617                &err,
3618                EthFilterError::EthAPIError(EthApiError::HeaderNotFound(id))
3619                    if *id == BlockId::from(unknown)
3620            ),
3621            "{err:?}"
3622        );
3623    }
3624
3625    #[reth_concurrency::test]
3626    async fn test_logs_at_block_hash_bloom_miss_skips_receipts() {
3627        let provider = MockEthProvider::default();
3628        let header = alloy_consensus::Header { number: 3, ..Default::default() };
3629        let hash = header.hash_slow();
3630        // a block whose receipts were pruned.
3631        provider.add_block(hash, Block { header, body: Default::default() });
3632        let eth_api = build_test_eth_api(provider);
3633        let eth_filter =
3634            EthFilter::new(eth_api.clone(), EthFilterConfig::default(), Runtime::test());
3635
3636        for cached in [false, true] {
3637            if cached {
3638                eth_api.cache().get_recovered_block(hash).await.unwrap().unwrap();
3639            }
3640
3641            // the empty bloom rules out the address, so the receipts are not needed.
3642            let logs = eth_filter
3643                .logs_for_filter(
3644                    Filter::new().address(Address::repeat_byte(1)).at_block_hash(hash),
3645                    QueryLimits::default(),
3646                )
3647                .await
3648                .unwrap();
3649            assert!(logs.is_empty(), "cached: {cached}");
3650
3651            let err = eth_filter
3652                .logs_for_filter(Filter::new().at_block_hash(hash), QueryLimits::default())
3653                .await
3654                .unwrap_err();
3655            assert!(
3656                matches!(err, EthFilterError::ReceiptsUnavailable(3)),
3657                "cached: {cached}, {err:?}"
3658            );
3659        }
3660    }
3661
3662    #[reth_concurrency::test]
3663    async fn test_logs_at_block_hash_cached_receipts() {
3664        let provider = MockEthProvider::default();
3665        let (header, _) = add_block_with_logs(&provider);
3666        let eth_api = build_test_eth_api(provider.clone());
3667        let eth_filter =
3668            EthFilter::new(eth_api.clone(), EthFilterConfig::default(), Runtime::test());
3669        let filter = Filter::new().at_block_hash(header.hash());
3670
3671        let expected =
3672            eth_filter.logs_for_filter(filter.clone(), QueryLimits::default()).await.unwrap();
3673        assert_eq!(expected.len(), 5);
3674
3675        // only the cache holds the receipts from here on, the block is not cached.
3676        eth_api.cache().get_receipts(header.hash()).await.unwrap().unwrap();
3677        provider.receipts.lock().remove(&header.number());
3678
3679        let logs = eth_filter.logs_for_filter(filter, QueryLimits::default()).await.unwrap();
3680        assert_eq!(logs, expected);
3681    }
3682
3683    #[reth_concurrency::test]
3684    async fn test_logs_at_block_hash_expired_history() {
3685        let provider = MockEthProvider::default();
3686        let (header, _) = add_block_with_logs(&provider);
3687        provider.set_earliest_block_number(header.number() + 1);
3688        let eth_api = build_test_eth_api(provider);
3689        let eth_filter =
3690            EthFilter::new(eth_api.clone(), EthFilterConfig::default(), Runtime::test());
3691
3692        for cached in [false, true] {
3693            if cached {
3694                eth_api.cache().get_recovered_block(header.hash()).await.unwrap().unwrap();
3695            }
3696
3697            // the bloom rules out the second filter, expired history is still reported first.
3698            for filter in [Filter::new(), Filter::new().address(Address::repeat_byte(4))] {
3699                let err = eth_filter
3700                    .logs_for_filter(filter.at_block_hash(header.hash()), QueryLimits::default())
3701                    .await
3702                    .unwrap_err();
3703                assert!(
3704                    matches!(
3705                        err,
3706                        EthFilterError::EthAPIError(EthApiError::PrunedHistoryUnavailable {
3707                            requested: 7,
3708                            earliest_available: 8
3709                        })
3710                    ),
3711                    "cached: {cached}, {err:?}"
3712                );
3713            }
3714        }
3715    }
3716
3717    #[reth_concurrency::test]
3718    async fn test_logs_at_block_hash_reorged_out() {
3719        let provider = MockEthProvider::default();
3720        let (header, _) = add_block_with_logs(&provider);
3721        let eth_api = build_test_eth_api(provider.clone());
3722        let eth_filter =
3723            EthFilter::new(eth_api.clone(), EthFilterConfig::default(), Runtime::test());
3724
3725        // the cache still holds the block after the provider dropped it.
3726        eth_api.cache().get_recovered_block(header.hash()).await.unwrap().unwrap();
3727        provider.headers.lock().remove(&header.hash());
3728
3729        // a matching filter needs the receipts, which are gone with the block.
3730        let err = eth_filter
3731            .logs_for_filter(Filter::new().at_block_hash(header.hash()), QueryLimits::default())
3732            .await
3733            .unwrap_err();
3734        assert!(
3735            matches!(
3736                &err,
3737                EthFilterError::EthAPIError(EthApiError::HeaderNotFound(id))
3738                    if *id == BlockId::from(header.hash())
3739            ),
3740            "{err:?}"
3741        );
3742    }
3743
3744    #[tokio::test]
3745    async fn test_filter_changes_only_delivers_new_logs() {
3746        let provider = MockEthProvider::default();
3747        add_blocks_with_log(&provider, 0..=3);
3748        let eth_filter = EthFilter::new(
3749            build_test_eth_api(provider.clone()),
3750            EthFilterConfig::default(),
3751            Runtime::test(),
3752        );
3753
3754        // an explicit `fromBlock` bounds the filter but must not be rescanned on every poll
3755        let id = eth_filter.new_filter(Filter::new().from_block(0u64)).await.unwrap();
3756
3757        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![3]);
3758        assert_eq!(poll_log_blocks(&eth_filter, &id).await, Vec::<u64>::new());
3759
3760        add_blocks_with_log(&provider, 4..=5);
3761        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![4, 5]);
3762        assert_eq!(poll_log_blocks(&eth_filter, &id).await, Vec::<u64>::new());
3763
3764        // `eth_getFilterLogs` still returns the filter's entire range
3765        assert_eq!(eth_filter.filter_logs(id).await.unwrap().len(), 6);
3766    }
3767
3768    #[tokio::test]
3769    async fn test_filter_changes_clamps_future_to_block() {
3770        let provider = MockEthProvider::default();
3771        add_blocks_with_log(&provider, 0..=3);
3772        let eth_filter = EthFilter::new(
3773            build_test_eth_api(provider.clone()),
3774            EthFilterConfig::default(),
3775            Runtime::test(),
3776        );
3777
3778        // a `toBlock` beyond the head bounds future polls instead of failing them
3779        let id = eth_filter.new_filter(Filter::new().to_block(100u64)).await.unwrap();
3780        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![3]);
3781
3782        add_blocks_with_log(&provider, 4..=5);
3783        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![4, 5]);
3784    }
3785
3786    #[tokio::test]
3787    async fn test_filter_changes_latest_tag_covers_all_new_blocks() {
3788        let provider = MockEthProvider::default();
3789        add_blocks_with_log(&provider, 0..=3);
3790        let eth_filter = EthFilter::new(
3791            build_test_eth_api(provider.clone()),
3792            EthFilterConfig::default(),
3793            Runtime::test(),
3794        );
3795
3796        // `fromBlock: latest` means from the installation onwards, not only the head at poll time
3797        let id =
3798            eth_filter.new_filter(Filter::new().select(BlockNumberOrTag::Latest..)).await.unwrap();
3799        add_blocks_with_log(&provider, 4..=5);
3800        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![3, 4, 5]);
3801    }
3802
3803    #[reth_concurrency::test]
3804    async fn test_block_hash_filter_changes_delivers_once() {
3805        let provider = MockEthProvider::default();
3806        add_blocks_with_log(&provider, 0..=3);
3807        let eth_filter = EthFilter::new(
3808            build_test_eth_api(provider.clone()),
3809            EthFilterConfig::default(),
3810            Runtime::test(),
3811        );
3812
3813        // a `blockHash` filter's block never changes, so it is delivered once and neither a
3814        // repeated poll nor a new head brings it back
3815        let hash = provider.header_by_number(1).unwrap().unwrap().hash_slow();
3816        let id = eth_filter.new_filter(Filter::new().at_block_hash(hash)).await.unwrap();
3817        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![1]);
3818        assert_eq!(poll_log_blocks(&eth_filter, &id).await, Vec::<u64>::new());
3819
3820        add_blocks_with_log(&provider, 4..=5);
3821        assert_eq!(poll_log_blocks(&eth_filter, &id).await, Vec::<u64>::new());
3822
3823        // a block that is not canonical fails every poll instead of exhausting the filter
3824        let unknown = B256::repeat_byte(0xab);
3825        let id = eth_filter.new_filter(Filter::new().at_block_hash(unknown)).await.unwrap();
3826        for _ in 0..2 {
3827            let err = eth_filter.filter_changes(id.clone()).await.unwrap_err();
3828            assert!(
3829                matches!(
3830                    &err,
3831                    EthFilterError::EthAPIError(EthApiError::HeaderNotFound(id))
3832                        if *id == unknown.into()
3833                ),
3834                "{err:?}"
3835            );
3836        }
3837    }
3838
3839    #[tokio::test]
3840    async fn test_filter_changes_pages_over_log_limit() {
3841        let provider = MockEthProvider::default();
3842        add_blocks_with_log(&provider, 0..=0);
3843        let eth_filter = EthFilter::new(
3844            build_test_eth_api(provider.clone()),
3845            EthFilterConfig::default().max_logs_per_response(1),
3846            Runtime::test(),
3847        );
3848        let id = eth_filter.new_filter(Filter::default()).await.unwrap();
3849        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![0]);
3850
3851        // three blocks with one log each exceed the cap, so each poll delivers the prefix that
3852        // fits and the next poll continues from there without losing or repeating a block
3853        add_blocks_with_log(&provider, 1..=3);
3854        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![1]);
3855        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![2]);
3856        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![3]);
3857        assert_eq!(poll_log_blocks(&eth_filter, &id).await, Vec::<u64>::new());
3858    }
3859
3860    #[tokio::test]
3861    async fn test_filter_changes_pages_over_response_size() {
3862        let provider = MockEthProvider::default();
3863        add_blocks_with_log(&provider, 0..=0);
3864        let eth_filter = EthFilter::new(
3865            build_test_eth_api(provider.clone()),
3866            EthFilterConfig::default().max_response_size(Some(5_000)),
3867            Runtime::test(),
3868        );
3869        let id = eth_filter.new_filter(Filter::default()).await.unwrap();
3870        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![0]);
3871
3872        // ten logs take at least 3_000 bytes, so two such blocks exceed the limit and each poll
3873        // delivers one block, without losing or repeating a block
3874        add_blocks_with_logs(&provider, 1..=3, 10);
3875        for block in 1..=3 {
3876            assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![block; 10]);
3877        }
3878        assert_eq!(poll_log_blocks(&eth_filter, &id).await, Vec::<u64>::new());
3879    }
3880
3881    #[tokio::test]
3882    async fn test_filter_changes_fit_transport_limit() {
3883        let provider = MockEthProvider::default();
3884        add_blocks_with_log(&provider, 0..=0);
3885        let eth_filter = EthFilter::new(
3886            build_test_eth_api(provider.clone()),
3887            EthFilterConfig::default().max_response_size(Some(5_000)),
3888            Runtime::test(),
3889        );
3890        let id = eth_filter.new_filter(Filter::default()).await.unwrap();
3891        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![0]);
3892
3893        // two blocks of eight logs take at least 4_800 bytes, under the limit, but up to 7_104
3894        // bytes in the response, so each poll returns one block, which the transport accepts.
3895        add_blocks_with_logs(&provider, 1..=2, 8);
3896        for block in 1..=2 {
3897            let changes = eth_filter.filter_changes(id.clone()).await.unwrap();
3898            let FilterChanges::Logs(logs) = &changes else { panic!("{changes:?}") };
3899            assert_eq!(
3900                logs.iter().map(|log| log.block_number.unwrap()).collect::<Vec<_>>(),
3901                vec![block; 8]
3902            );
3903            let response =
3904                MethodResponse::response(Id::Number(1), ResponsePayload::success(changes), 5_000);
3905            assert!(response.is_success());
3906        }
3907        assert_eq!(poll_log_blocks(&eth_filter, &id).await, Vec::<u64>::new());
3908    }
3909
3910    #[tokio::test]
3911    async fn test_failed_filter_poll_is_retried() {
3912        let provider = MockEthProvider::default();
3913        add_blocks_with_log(&provider, 0..=0);
3914        let eth_api = build_test_eth_api(provider.clone());
3915        let guard = eth_api.blocking_io_task_guard().clone();
3916        // The first scan can send its result before its worker releases the permit.
3917        let capacity = guard.available_permits();
3918        let eth_filter = EthFilter::new(eth_api, EthFilterConfig::default(), Runtime::test());
3919        let id = eth_filter.new_filter(Filter::default()).await.unwrap();
3920        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![0]);
3921
3922        // a poll whose request is dropped before its scan completes does not consume the new
3923        // block.
3924        add_blocks_with_log(&provider, 1..=1);
3925        {
3926            let permits = guard.clone().acquire_many_owned(capacity as u32).await.unwrap();
3927            let changes = eth_filter.filter_changes(id.clone());
3928            tokio::pin!(changes);
3929            assert!(futures::poll!(&mut changes).is_pending());
3930            drop(permits);
3931            assert_eq!(guard.available_permits(), capacity - 1);
3932        }
3933
3934        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![1]);
3935    }
3936
3937    #[tokio::test]
3938    async fn test_filter_poll_skips_pruned_receipts() {
3939        let provider = MockEthProvider::default();
3940        add_blocks_with_log(&provider, 0..=0);
3941        let eth_filter = EthFilter::new(
3942            build_test_eth_api(provider.clone()),
3943            EthFilterConfig::default(),
3944            Runtime::test(),
3945        );
3946        let id = eth_filter.new_filter(Filter::default()).await.unwrap();
3947        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![0]);
3948
3949        // the receipts of block 1 were pruned before the filter got to them.
3950        add_blocks_with_log(&provider, 1..=2);
3951        provider.receipts.lock().remove(&1);
3952        let err = eth_filter.filter_changes(id.clone()).await.unwrap_err();
3953        assert!(matches!(err, EthFilterError::ReceiptsUnavailable(1)), "{err:?}");
3954
3955        // the failed poll's range is skipped instead of failing every later poll.
3956        add_blocks_with_log(&provider, 3..=3);
3957        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![3]);
3958    }
3959
3960    #[tokio::test]
3961    async fn test_filter_changes_delivers_oversized_block_whole() {
3962        let provider = MockEthProvider::default();
3963        add_blocks_with_log(&provider, 0..=0);
3964        let eth_filter = EthFilter::new(
3965            build_test_eth_api(provider.clone()),
3966            EthFilterConfig::default().max_logs_per_response(1),
3967            Runtime::test(),
3968        );
3969        let id = eth_filter.new_filter(Filter::default()).await.unwrap();
3970        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![0]);
3971
3972        // a block with more logs than the cap is delivered whole, as by `eth_getLogs`, instead of
3973        // stalling the filter on it, and the next poll moves on
3974        add_blocks_with_logs(&provider, 1..=1, 2);
3975        add_blocks_with_log(&provider, 2..=2);
3976        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![1, 1]);
3977        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![2]);
3978        assert_eq!(poll_log_blocks(&eth_filter, &id).await, Vec::<u64>::new());
3979    }
3980
3981    #[tokio::test]
3982    async fn test_filter_changes_pages_over_block_limit() {
3983        let provider = MockEthProvider::default();
3984        add_blocks_with_log(&provider, 0..=0);
3985        let eth_filter = EthFilter::new(
3986            build_test_eth_api(provider.clone()),
3987            EthFilterConfig::default().max_blocks_per_filter(1),
3988            Runtime::test(),
3989        );
3990        let id = eth_filter.new_filter(Filter::default()).await.unwrap();
3991
3992        // a backlog wider than the block limit is delivered over successive polls instead of
3993        // failing them all with `QueryExceedsMaxBlocks`; the limit bounds `to - from` as in
3994        // `eth_getLogs`, so a poll covers at most `max + 1` blocks
3995        add_blocks_with_log(&provider, 1..=3);
3996        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![0, 1]);
3997        assert_eq!(poll_log_blocks(&eth_filter, &id).await, vec![2, 3]);
3998        assert_eq!(poll_log_blocks(&eth_filter, &id).await, Vec::<u64>::new());
3999    }
4000
4001    #[tokio::test]
4002    async fn test_filter_changes_reports_an_invalid_range() {
4003        let provider = MockEthProvider::default();
4004        add_blocks_with_log(&provider, 0..=3);
4005        let eth_filter = EthFilter::new(
4006            build_test_eth_api(provider),
4007            EthFilterConfig::default(),
4008            Runtime::test(),
4009        );
4010
4011        // a filter that can never match must not look like one the cursor exhausted
4012        let id =
4013            eth_filter.new_filter(Filter::new().from_block(3u64).to_block(1u64)).await.unwrap();
4014        let err = eth_filter.filter_changes(id).await.unwrap_err();
4015        assert!(matches!(err, EthFilterError::InvalidBlockRangeParams), "{err:?}");
4016    }
4017
4018    #[tokio::test]
4019    async fn test_filter_changes_without_new_block() {
4020        let provider = MockEthProvider::default();
4021        provider.add_header(FixedBytes::random(), alloy_consensus::Header::default());
4022        let eth_filter = EthFilter::new(
4023            build_test_eth_api(provider),
4024            EthFilterConfig::default(),
4025            Runtime::test(),
4026        );
4027        let block_filter = eth_filter.new_block_filter().await.unwrap();
4028        let pending_filter = eth_filter.new_pending_transaction_filter(None).await.unwrap();
4029
4030        // The first poll advances the filters past the head.
4031        eth_filter.filter_changes(block_filter.clone()).await.unwrap();
4032        eth_filter.filter_changes(pending_filter.clone()).await.unwrap();
4033
4034        let tx = MockTransaction::eip1559();
4035        let hash = *tx.hash();
4036        eth_filter.pool().add_transaction(TransactionOrigin::External, tx).await.unwrap();
4037
4038        // A block filter waits for the next block, a pending transaction filter does not.
4039        assert_eq!(eth_filter.filter_changes(block_filter).await.unwrap(), FilterChanges::Empty);
4040        // The feed forwards the transaction asynchronously, so poll until it arrives.
4041        let hashes = tokio::time::timeout(TIMEOUT, async {
4042            loop {
4043                match eth_filter.filter_changes(pending_filter.clone()).await.unwrap() {
4044                    FilterChanges::Hashes(hashes) if !hashes.is_empty() => break hashes,
4045                    FilterChanges::Hashes(_) => tokio::time::sleep(Duration::from_millis(5)).await,
4046                    changes => panic!("unexpected changes {changes:?}"),
4047                }
4048            }
4049        })
4050        .await
4051        .expect("filter did not receive the transaction");
4052        assert_eq!(hashes, [hash]);
4053    }
4054
4055    #[tokio::test]
4056    async fn test_filter_poll_without_new_block_keeps_filter_alive() {
4057        let provider = MockEthProvider::default();
4058        provider.add_header(FixedBytes::random(), alloy_consensus::Header::default());
4059        let eth_filter = EthFilter::new(
4060            build_test_eth_api(provider),
4061            EthFilterConfig::default(),
4062            Runtime::test(),
4063        );
4064        let ttl = eth_filter.inner.stale_filter_ttl;
4065        let active_filters = eth_filter.active_filters();
4066        let ids = [
4067            eth_filter.new_block_filter().await.unwrap(),
4068            eth_filter.new_pending_transaction_filter(None).await.unwrap(),
4069        ];
4070
4071        for id in &ids {
4072            // The first poll advances the filter past the head, so the second one sees no new
4073            // block.
4074            eth_filter.filter_changes(id.clone()).await.unwrap();
4075            // Unless the second poll refreshes it, the filter is stale at `now + ttl / 2`.
4076            active_filters.inner.lock().await.get_mut(id).unwrap().last_poll_timestamp -= ttl;
4077            eth_filter.filter_changes(id.clone()).await.unwrap();
4078        }
4079
4080        eth_filter.clear_stale_filters(Instant::now() + ttl / 2).await;
4081        for id in &ids {
4082            assert!(active_filters.contains(id).await, "{id:?} was evicted");
4083        }
4084    }
4085
4086    #[tokio::test(start_paused = true)]
4087    async fn expired_filter_frees_its_slot_at_the_next_sweep() {
4088        let eth_api = build_test_eth_api(provider_with_head());
4089        let config = EthFilterConfig::default().max_active_filters(Some(1));
4090        let eth_filter = EthFilter::new(eth_api, config, Runtime::test());
4091        let ttl = eth_filter.inner.stale_filter_ttl;
4092
4093        let id = eth_filter.new_block_filter().await.unwrap();
4094        eth_filter.active_filters().inner.lock().await.get_mut(&id).unwrap().last_poll_timestamp -=
4095            ttl;
4096        assert_eq!(eth_filter.new_block_filter().await.unwrap_err().code(), LIMIT_EXCEEDED_CODE);
4097
4098        tokio::time::sleep(ttl / STALE_FILTER_SWEEPS_PER_TTL).await;
4099        tokio::task::yield_now().await;
4100
4101        assert!(!eth_filter.active_filters().contains(&id).await);
4102        eth_filter.new_block_filter().await.unwrap();
4103    }
4104
4105    #[tokio::test(start_paused = true)]
4106    async fn tiny_stale_filter_ttl_keeps_the_sweeper_running() {
4107        let config = EthFilterConfig::default().stale_filter_ttl(Duration::from_nanos(3));
4108        let eth_filter =
4109            EthFilter::new(build_test_eth_api(provider_with_head()), config, Runtime::test());
4110
4111        // A zero sweep period would panic here instead of sweeping until the timeout.
4112        tokio::time::timeout(Duration::from_millis(10), eth_filter.watch_and_clear_stale_filters())
4113            .await
4114            .unwrap_err();
4115    }
4116
4117    // Runs on one thread, so a poll that blocked the thread on the receiver would deadlock.
4118    #[tokio::test(flavor = "current_thread")]
4119    async fn concurrent_poll_of_a_pending_filter_yields() {
4120        let eth_filter = EthFilter::new(
4121            build_test_eth_api(provider_with_head()),
4122            EthFilterConfig::default(),
4123            Runtime::test(),
4124        );
4125        let id = eth_filter.new_pending_transaction_filter(None).await.unwrap();
4126        let PendingTransactionKind::Hashes(receiver) = pending_kind(&eth_filter, &id).await else {
4127            panic!("expected a hash filter")
4128        };
4129
4130        let guard = receiver.txs_receiver.lock().await;
4131        let poll = tokio::spawn({
4132            let eth_filter = eth_filter.clone();
4133            async move { eth_filter.filter_changes(id).await }
4134        });
4135        tokio::task::yield_now().await;
4136        assert!(!poll.is_finished());
4137
4138        drop(guard);
4139        assert_eq!(poll.await.unwrap().unwrap(), FilterChanges::Hashes(Vec::new()));
4140    }
4141}