Skip to main content

reth_network/
eth_requests.rs

1//! Blocks/Headers management for the p2p network.
2
3use crate::{
4    budget::DEFAULT_BUDGET_TRY_DRAIN_DOWNLOADERS, metered_poll_nested_stream_with_budget,
5    metrics::EthRequestHandlerMetrics,
6};
7use alloy_consensus::{constants::KECCAK_EMPTY, BlockHeader, ReceiptWithBloom};
8use alloy_eips::BlockHashOrNumber;
9use alloy_primitives::{map::B256Set, Bytes, B256};
10use alloy_rlp::{length_of_length, Encodable};
11use futures::StreamExt;
12use reth_eth_wire::{
13    message::MAX_MESSAGE_SIZE,
14    snap::{
15        AccountData, AccountRangeMessage, BlockAccessListsMessage, ByteCodesMessage,
16        GetAccountRangeMessage, GetStorageRangesMessage, SnapProtocolMessage, StorageData,
17        StorageRangesMessage,
18    },
19    BlockAccessLists, BlockBodies, BlockHeaders, CellMasks, Cells, EthNetworkPrimitives,
20    GetBlockAccessLists, GetBlockBodies, GetBlockHeaders, GetCells, GetNodeData, GetReceipts,
21    GetReceipts70, HeadersDirection, NetworkPrimitives, NodeData, Receipts, Receipts69, Receipts70,
22};
23use reth_network_p2p::{
24    error::{RequestError, RequestResult},
25    snap::client::SnapResponse,
26};
27use reth_network_peers::PeerId;
28use reth_primitives_traits::Block;
29use reth_storage_api::{
30    errors::provider::ProviderResult, BalProvider, BlockReader, BytecodeReader,
31    GetBlockAccessListLimit, HeaderProvider, RangeEnd, RangeResponse, StateProviderFactory,
32    StateRangeProviderFactory,
33};
34use reth_transaction_pool::{blobstore::NoopBlobStore, BlobStore};
35use std::{
36    collections::VecDeque,
37    future::Future,
38    pin::Pin,
39    task::{Context, Poll},
40    time::Duration,
41};
42use tokio::{
43    sync::{mpsc::Receiver, oneshot},
44    task::JoinHandle,
45    time::{sleep_until, Instant, Sleep},
46};
47use tokio_stream::wrappers::ReceiverStream;
48use tracing::{debug, error, Span};
49
50// Limits: <https://github.com/ethereum/go-ethereum/blob/b0d44338bbcefee044f1f635a84487cbbd8f0538/eth/protocols/eth/handler.go#L34-L56>
51
52/// Maximum number of receipts to serve.
53///
54/// Used to limit lookups.
55pub const MAX_RECEIPTS_SERVE: usize = 1024;
56
57/// Maximum number of block headers to serve.
58///
59/// Used to limit lookups.
60pub const MAX_HEADERS_SERVE: usize = 1024;
61
62/// Maximum number of block headers to serve.
63///
64/// Used to limit lookups. With 24KB block sizes nowadays, the practical limit will always be
65/// `SOFT_RESPONSE_LIMIT`.
66pub const MAX_BODIES_SERVE: usize = 1024;
67
68/// Maximum number of block access lists to serve.
69///
70/// Used to limit lookups.
71pub const MAX_BLOCK_ACCESS_LISTS_SERVE: usize = 1024;
72
73/// Maximum number of cell lookups to serve.
74///
75/// Used to limit lookups.
76pub const MAX_CELLS_SERVE: usize = 1024;
77
78/// Maximum number of blobs to serve cells for in a single response.
79///
80/// A blob stored in full has all its cells computed, whatever the mask selects, so the response
81/// size alone doesn't bound the work. The handler stops after the transaction that brings the
82/// response to 128 blobs or more.
83pub const MAX_CELL_BLOBS_SERVE: usize = 128;
84
85/// Maximum number of bytecode lookups to serve.
86///
87/// Used to limit lookups.
88pub const MAX_BYTE_CODES_SERVE: usize = 1024;
89
90/// Maximum number of storage range account lookups to serve.
91pub const MAX_STORAGE_RANGE_ACCOUNTS_SERVE: usize = 1024;
92
93/// Maximum size of replies to data retrievals: 2MB
94pub const SOFT_RESPONSE_LIMIT: usize = 2 * 1024 * 1024;
95
96/// Maximum number of `snap/2` account and storage range requests served at once.
97///
98/// Serving an old root can rewind the trie block by block, so these requests run off the handler
99/// task and are capped to keep them from starving other blocking work.
100const MAX_CONCURRENT_STATE_RANGE_REQUESTS: usize = 2;
101
102/// Maximum number of `snap/2` range requests waiting for a serving slot, one per peer.
103///
104/// They wait because snap clients read an empty response as the root being unavailable, and then
105/// leave the peer alone until they retry.
106const MAX_QUEUED_STATE_RANGE_REQUESTS: usize = 16;
107
108/// How long a `snap/2` range request may wait for a serving slot before it is answered empty.
109///
110/// A requester's timeout adapts down to two seconds and also covers transit and serving, so the
111/// wait takes only a fraction of it. A slot is otherwise spent on a response nobody awaits.
112const STATE_RANGE_REQUEST_QUEUE_TIMEOUT: Duration = Duration::from_millis(500);
113
114/// Upper bound on the headers reserved once the first requested header resolves.
115///
116/// Header responses are bound by [`MAX_HEADERS_SERVE`] rather than by size, so a full batch reaches
117/// its final capacity within a few doublings while a batch that runs past the local tip wastes at
118/// most this many slots.
119const MAX_HEADERS_RESERVE: usize = 64;
120
121/// Upper bound on the block bodies or receipt lists reserved once the first requested block
122/// resolves.
123///
124/// These responses are bound by [`SOFT_RESPONSE_LIMIT`], so the first block's size predicts how
125/// many fit and this only caps the estimate for tiny blocks.
126const MAX_BLOCKS_RESERVE: usize = 16;
127
128/// Manages eth related requests on top of the p2p network.
129///
130/// This can be spawned to another task and is supposed to be run as background service.
131#[derive(Debug)]
132#[must_use = "Manager does nothing unless polled."]
133pub struct EthRequestHandler<C, N: NetworkPrimitives = EthNetworkPrimitives> {
134    /// The client type that can interact with the chain.
135    client: C,
136    /// Blob store used for serving blob cell requests.
137    blob_store: Box<dyn BlobStore>,
138    /// Incoming request from the [`NetworkManager`](crate::NetworkManager).
139    incoming_requests: ReceiverStream<IncomingEthRequest<N>>,
140    /// Metrics for the eth request handler.
141    metrics: EthRequestHandlerMetrics,
142    /// `snap/2` range requests running or waiting off the handler task.
143    state_range_requests: StateRangeRequests,
144}
145
146// === impl EthRequestHandler ===
147impl<C, N: NetworkPrimitives> EthRequestHandler<C, N> {
148    /// Create a new instance
149    pub fn new(client: C, incoming: Receiver<IncomingEthRequest<N>>) -> Self {
150        Self {
151            client,
152            blob_store: Box::<NoopBlobStore>::default(),
153            incoming_requests: ReceiverStream::new(incoming),
154            metrics: Default::default(),
155            state_range_requests: Default::default(),
156        }
157    }
158
159    /// Set blob store for the request handler
160    pub fn with_blob_store(mut self, blob_store: Box<dyn BlobStore>) -> Self {
161        self.blob_store = blob_store;
162        self
163    }
164}
165
166impl<C, N> EthRequestHandler<C, N>
167where
168    N: NetworkPrimitives,
169    C: BlockReader,
170{
171    /// Returns the list of requested headers
172    fn get_headers_response(&self, request: GetBlockHeaders) -> Vec<C::Header> {
173        let GetBlockHeaders { start_block, limit, skip, direction } = request;
174
175        let mut headers = Vec::new();
176
177        let mut block: BlockHashOrNumber = match start_block {
178            BlockHashOrNumber::Hash(start) => start.into(),
179            BlockHashOrNumber::Number(num) => {
180                let Some(hash) = self.client.block_hash(num).unwrap_or_default() else {
181                    return headers
182                };
183                hash.into()
184            }
185        };
186
187        let skip = skip as u64;
188        let mut total_bytes = 0;
189
190        for _ in 0..limit {
191            if let Some(header) = self.client.header_by_hash_or_number(block).unwrap_or_default() {
192                let number = header.number();
193                let parent_hash = header.parent_hash();
194                let len = header.length();
195
196                if headers.is_empty() {
197                    let count = limit.min(MAX_HEADERS_SERVE as u64) as usize;
198                    headers.reserve(response_reserve_hint(count, len, MAX_HEADERS_RESERVE));
199                }
200
201                total_bytes += len;
202                headers.push(header);
203
204                if headers.len() >= MAX_HEADERS_SERVE || total_bytes > SOFT_RESPONSE_LIMIT {
205                    break
206                }
207
208                match direction {
209                    HeadersDirection::Rising => {
210                        if let Some(next) = number.checked_add(1).and_then(|n| n.checked_add(skip))
211                        {
212                            block = next.into()
213                        } else {
214                            break
215                        }
216                    }
217                    HeadersDirection::Falling => {
218                        if skip > 0 {
219                            // prevent under flows for block.number == 0 and `block.number - skip <
220                            // 0`
221                            if let Some(next) =
222                                number.checked_sub(1).and_then(|num| num.checked_sub(skip))
223                            {
224                                block = next.into()
225                            } else {
226                                break
227                            }
228                        } else {
229                            block = parent_hash.into()
230                        }
231                    }
232                }
233            } else {
234                break
235            }
236        }
237
238        headers
239    }
240
241    fn on_headers_request(
242        &self,
243        _peer_id: PeerId,
244        request: GetBlockHeaders,
245        response: oneshot::Sender<RequestResult<BlockHeaders<C::Header>>>,
246    ) {
247        self.metrics.eth_headers_requests_received_total.increment(1);
248        let headers = self.get_headers_response(request);
249        let _ = response.send(Ok(BlockHeaders(headers)));
250    }
251
252    fn on_bodies_request(
253        &self,
254        _peer_id: PeerId,
255        request: GetBlockBodies,
256        response: oneshot::Sender<RequestResult<BlockBodies<<C::Block as Block>::Body>>>,
257    ) {
258        self.metrics.eth_bodies_requests_received_total.increment(1);
259        let count = request.0.len();
260        let mut bodies = Vec::new();
261
262        let mut total_bytes = 0;
263
264        for hash in request {
265            if let Some(block) = self.client.block_by_hash(hash).unwrap_or_default() {
266                let body = block.into_body();
267                let len = body.length();
268                if bodies.is_empty() {
269                    bodies.reserve(response_reserve_hint(count, len, MAX_BLOCKS_RESERVE));
270                }
271                total_bytes += len;
272                bodies.push(body);
273
274                if bodies.len() >= MAX_BODIES_SERVE || total_bytes > SOFT_RESPONSE_LIMIT {
275                    break
276                }
277            } else {
278                break
279            }
280        }
281
282        let _ = response.send(Ok(BlockBodies(bodies)));
283    }
284
285    /// Replies to `GetNodeData`.
286    ///
287    /// State serving via eth `GetNodeData` was removed; answer with an empty payload so eth/66
288    /// peers receive a response instead of hanging until the request timeout when the oneshot is
289    /// dropped unanswered.
290    fn on_node_data_request(
291        &self,
292        _peer_id: PeerId,
293        _request: GetNodeData,
294        response: oneshot::Sender<RequestResult<NodeData>>,
295    ) {
296        self.metrics.eth_node_data_requests_received_total.increment(1);
297        let _ = response.send(Ok(NodeData(vec![])));
298    }
299
300    fn on_receipts_request(
301        &self,
302        _peer_id: PeerId,
303        request: GetReceipts,
304        response: oneshot::Sender<RequestResult<Receipts<C::Receipt>>>,
305    ) {
306        self.metrics.eth_receipts_requests_received_total.increment(1);
307
308        let receipts = self.get_receipts_response(request, |receipts_by_block| {
309            receipts_by_block.into_iter().map(ReceiptWithBloom::from).collect::<Vec<_>>()
310        });
311
312        let _ = response.send(Ok(Receipts(receipts)));
313    }
314
315    fn on_receipts69_request(
316        &self,
317        _peer_id: PeerId,
318        request: GetReceipts,
319        response: oneshot::Sender<RequestResult<Receipts69<C::Receipt>>>,
320    ) {
321        self.metrics.eth_receipts_requests_received_total.increment(1);
322
323        let receipts = self.get_receipts_response(request, |receipts_by_block| {
324            // skip bloom filter for eth69
325            receipts_by_block
326        });
327
328        let _ = response.send(Ok(Receipts69(receipts)));
329    }
330
331    /// Handles partial responses for [`GetReceipts70`] queries.
332    ///
333    /// Whole blocks are packed until the response reaches [`SOFT_RESPONSE_LIMIT`]. The last block
334    /// is then served up to [`MAX_MESSAGE_SIZE`] and flagged incomplete only when its receipts
335    /// overflow that limit, as required by the devp2p spec. A response never ends with an empty
336    /// incomplete block: if not even the next receipt fits within the message, the response ends
337    /// after the last complete block. If the first receipt alone cannot fit within
338    /// [`MAX_MESSAGE_SIZE`], including the response framing, the response is empty and complete.
339    fn on_receipts70_request(
340        &self,
341        _peer_id: PeerId,
342        request: GetReceipts70,
343        response: oneshot::Sender<RequestResult<Receipts70<C::Receipt>>>,
344    ) {
345        self.metrics.eth_receipts_requests_received_total.increment(1);
346
347        let GetReceipts70 { first_block_receipt_index, block_hashes } = request;
348
349        let count = block_hashes.len();
350        let mut receipts = Vec::new();
351        let mut total_bytes = 0usize;
352        let mut last_block_incomplete = false;
353
354        // The request ID is unavailable here. Reserve the message code, the largest request ID,
355        // the incomplete flag, and the three RLP list headers to bound the full encoded response.
356        let max_receipts_size = MAX_MESSAGE_SIZE -
357            (1 + u64::MAX.length() + false.length() + 3 * length_of_length(MAX_MESSAGE_SIZE));
358
359        for (idx, hash) in block_hashes.into_iter().enumerate() {
360            if idx >= MAX_RECEIPTS_SERVE {
361                break
362            }
363
364            let Some(mut block_receipts) =
365                self.client.receipts_by_block(BlockHashOrNumber::Hash(hash)).unwrap_or_default()
366            else {
367                break
368            };
369
370            if idx == 0 && first_block_receipt_index > 0 {
371                let skip = first_block_receipt_index as usize;
372                if skip >= block_receipts.len() {
373                    block_receipts.clear();
374                } else {
375                    block_receipts.drain(0..skip);
376                }
377            }
378
379            let block_size = block_receipts.length();
380            if receipts.is_empty() {
381                receipts.reserve(response_reserve_hint(count, block_size, MAX_BLOCKS_RESERVE));
382            }
383
384            if total_bytes + block_size <= SOFT_RESPONSE_LIMIT {
385                total_bytes += block_size;
386                receipts.push(block_receipts);
387                continue;
388            }
389
390            // This block crosses the soft limit, so it is the last one served. The devp2p spec only
391            // allows `lastBlockIncomplete` when its receipts would overflow the message, so it gets
392            // the remaining message budget.
393            let remaining = block_receipts.len();
394            let mut partial_block = Vec::new();
395            for receipt in block_receipts {
396                let receipt_size = receipt.length();
397                if total_bytes + receipt_size > max_receipts_size {
398                    break;
399                }
400                total_bytes += receipt_size;
401                partial_block.push(receipt);
402            }
403
404            // An empty partial block delivers nothing, so it is never sent. The requester can
405            // simply continue with this block in its next request.
406            if !partial_block.is_empty() {
407                last_block_incomplete = partial_block.len() < remaining;
408                receipts.push(partial_block);
409            }
410            break;
411        }
412
413        let _ = response.send(Ok(Receipts70 { last_block_incomplete, receipts }));
414    }
415
416    #[inline]
417    fn get_receipts_response<T, F>(&self, request: GetReceipts, transform_fn: F) -> Vec<Vec<T>>
418    where
419        F: Fn(Vec<C::Receipt>) -> Vec<T>,
420        T: Encodable,
421    {
422        let count = request.0.len();
423        let mut receipts = Vec::new();
424        let mut total_bytes = 0;
425
426        for hash in request {
427            if let Some(receipts_by_block) =
428                self.client.receipts_by_block(BlockHashOrNumber::Hash(hash)).unwrap_or_default()
429            {
430                let transformed_receipts = transform_fn(receipts_by_block);
431                let len = transformed_receipts.length();
432                if receipts.is_empty() {
433                    receipts.reserve(response_reserve_hint(count, len, MAX_BLOCKS_RESERVE));
434                }
435                total_bytes += len;
436                receipts.push(transformed_receipts);
437
438                if receipts.len() >= MAX_RECEIPTS_SERVE || total_bytes > SOFT_RESPONSE_LIMIT {
439                    break
440                }
441            } else {
442                break
443            }
444        }
445
446        receipts
447    }
448
449    fn on_cells_request(
450        &self,
451        _peer_id: PeerId,
452        request: GetCells,
453        response: oneshot::Sender<RequestResult<Cells>>,
454    ) {
455        // Incoming requests can also be supplied directly, bypassing the wire decoder.
456        if request.cell_mask.validate(&request.hashes, false).is_err() {
457            let _ = response.send(Err(RequestError::InvalidRequest));
458            return
459        }
460        let mut cells_response = Cells {
461            cell_mask: match &request.cell_mask {
462                CellMasks::Shared(mask) => (*mask).into(),
463                CellMasks::Indexed { .. } => {
464                    CellMasks::Indexed { masks: Vec::new(), mask_ids: Bytes::new() }
465                }
466            },
467            ..Default::default()
468        };
469        let mut total_bytes = cells_response.length();
470        let mut response_ids = Vec::new();
471        let shared_mask = if request.cell_mask.is_indexed() { None } else { request.cell_mask(0) };
472        // Indexed requests are validated to have unique hashes, shared ones are not.
473        let mut seen = B256Set::default();
474        let mut blobs = 0;
475
476        for (index, &hash) in request.hashes.iter().take(MAX_CELLS_SERVE).enumerate() {
477            // Indexed tables were validated before any blob-store lookup or cell allocation.
478            let Some(cell_mask) = shared_mask.or_else(|| request.cell_mask(index)) else { break };
479            // An empty mask selects no cells, and a repeated hash adds nothing to the response.
480            if cell_mask.count() == 0 || (shared_mask.is_some() && !seen.insert(hash)) {
481                continue
482            }
483            let Some(cells) = self.blob_store.get_cells(hash, cell_mask).unwrap_or_default() else {
484                continue;
485            };
486
487            blobs += cells.len() / cell_mask.count();
488            total_bytes += hash.length() + cells.length();
489            if let CellMasks::Indexed { masks, .. } = &mut cells_response.cell_mask {
490                let Some(mask) = request.cell_mask.mask_at(index) else { break };
491                let id = masks.iter().position(|entry| *entry == mask).unwrap_or_else(|| {
492                    total_bytes += mask.length();
493                    masks.push(mask);
494                    masks.len() - 1
495                });
496                // At most 64 masks, enforced above.
497                response_ids.push(id as u8);
498                total_bytes += 1;
499            }
500            cells_response.hashes.push(hash);
501            cells_response.cells.push(cells);
502
503            if total_bytes > SOFT_RESPONSE_LIMIT || blobs >= MAX_CELL_BLOBS_SERVE {
504                break
505            }
506        }
507
508        if let CellMasks::Indexed { mask_ids, .. } = &mut cells_response.cell_mask {
509            *mask_ids = response_ids.into();
510        }
511        let _ = response.send(Ok(cells_response));
512    }
513}
514
515/// Number of response items to reserve once the first requested item has resolved.
516///
517/// Assumes the remaining items are about as large as the first one and reserves as many as fit into
518/// [`SOFT_RESPONSE_LIMIT`], bounded by the requested `count` and `max`.
519fn response_reserve_hint(count: usize, first_len: usize, max: usize) -> usize {
520    SOFT_RESPONSE_LIMIT.div_ceil(first_len.max(1)).min(count).min(max)
521}
522
523impl<C, N> EthRequestHandler<C, N>
524where
525    N: NetworkPrimitives,
526    C: BalProvider,
527{
528    /// Handles [`GetBlockAccessLists`] queries.
529    ///
530    /// EIP-8159 defines the final `BlockAccessLists` response semantics:
531    /// <https://eips.ethereum.org/EIPS/eip-8159>
532    fn on_block_access_lists_request(
533        &self,
534        _peer_id: PeerId,
535        mut request: GetBlockAccessLists,
536        response: oneshot::Sender<RequestResult<BlockAccessLists>>,
537    ) {
538        self.metrics.eth_block_access_lists_requests_received_total.increment(1);
539        request.0.truncate(MAX_BLOCK_ACCESS_LISTS_SERVE);
540
541        let limit = GetBlockAccessListLimit::ResponseSizeSoftLimit(SOFT_RESPONSE_LIMIT);
542        let access_lists =
543            self.client.get_bals_by_hashes_with_limit(&request.0, limit).unwrap_or_default();
544        let _ = response.send(Ok(BlockAccessLists(access_lists)));
545    }
546}
547
548impl<C, N> EthRequestHandler<C, N>
549where
550    N: NetworkPrimitives,
551    C: BalProvider + StateProviderFactory + StateRangeProviderFactory + Clone + 'static,
552{
553    /// Handles `snap/2` (EIP-8189) requests.
554    ///
555    /// `GetAccountRange`/`GetStorageRanges` are hash-native throughout and served from retained
556    /// canonical roots via [`StateRangeProviderFactory`], on blocking tasks so that rewinding an
557    /// old root doesn't stall other requests. `GetByteCodes` is content-addressed and
558    /// independent of any particular state root, so it's served directly.
559    /// `GetBlockAccessLists` is answered from the same [`BalProvider`] store eth71's
560    /// `GetBlockAccessLists` uses, since both serve the same underlying data.
561    fn on_snap_request(
562        &mut self,
563        peer_id: PeerId,
564        request: SnapProtocolMessage,
565        response: oneshot::Sender<RequestResult<SnapResponse>>,
566    ) {
567        self.metrics.snap_requests_received_total.increment(1);
568
569        let result = match request {
570            SnapProtocolMessage::GetAccountRange(req) => {
571                return self.on_state_range_request(
572                    peer_id,
573                    StateRangeRequest::Account(req),
574                    response,
575                )
576            }
577            SnapProtocolMessage::GetStorageRanges(mut req) => {
578                // Accounts past the serving limit are never read, so a queued request releases
579                // them along with the allocation the peer sized.
580                req.account_hashes.truncate(MAX_STORAGE_RANGE_ACCOUNTS_SERVE);
581                req.account_hashes.shrink_to_fit();
582                return self.on_state_range_request(
583                    peer_id,
584                    StateRangeRequest::Storage(req),
585                    response,
586                )
587            }
588            SnapProtocolMessage::GetByteCodes(req) => {
589                let codes = self
590                    .get_byte_codes_response(&req.hashes, req.response_bytes as usize)
591                    .unwrap_or_else(|error| {
592                        tracing::debug!(target: "net::snap", %error, "failed to serve bytecodes");
593                        Vec::new()
594                    });
595                Ok(SnapResponse::ByteCodes(ByteCodesMessage { request_id: req.request_id, codes }))
596            }
597            SnapProtocolMessage::GetBlockAccessLists(mut req) => {
598                req.block_hashes.truncate(MAX_BLOCK_ACCESS_LISTS_SERVE);
599                let limit = GetBlockAccessListLimit::ResponseSizeSoftLimit(
600                    (req.response_bytes as usize).min(SOFT_RESPONSE_LIMIT),
601                );
602                let block_access_lists = self
603                    .client
604                    .get_bals_by_hashes_with_limit(&req.block_hashes, limit)
605                    .unwrap_or_default();
606                Ok(SnapResponse::BlockAccessLists(BlockAccessListsMessage {
607                    request_id: req.request_id,
608                    block_access_lists: BlockAccessLists(block_access_lists),
609                }))
610            }
611            // The peer sent us a response-shaped message instead of a request; not something we
612            // asked for.
613            _ => Err(RequestError::BadResponse),
614        };
615
616        let _ = response.send(result);
617    }
618
619    /// Hands a `snap/2` range request to [`StateRangeRequests`].
620    fn on_state_range_request(
621        &mut self,
622        peer_id: PeerId,
623        request: StateRangeRequest,
624        response: oneshot::Sender<RequestResult<SnapResponse>>,
625    ) {
626        let incoming =
627            IncomingStateRangeRequest { peer_id, request, response, received: Instant::now() };
628        self.state_range_requests.admit(incoming, &self.client, &self.metrics);
629    }
630
631    /// Returns the bytecode for each of `hashes`, skipping hashes with no known code, stopping
632    /// once `response_bytes` (capped at [`SOFT_RESPONSE_LIMIT`]) is exceeded.
633    fn get_byte_codes_response(
634        &self,
635        hashes: &[B256],
636        response_bytes: usize,
637    ) -> ProviderResult<Vec<Bytes>> {
638        let state = self.client.latest()?;
639        let response_bytes = response_bytes.min(SOFT_RESPONSE_LIMIT);
640
641        let mut codes = Vec::new();
642        let mut total_bytes = 0;
643        for hash in hashes.iter().take(MAX_BYTE_CODES_SERVE) {
644            let bytes = if *hash == KECCAK_EMPTY {
645                Bytes::new()
646            } else {
647                match state.bytecode_by_hash(hash)? {
648                    Some(bytecode) => bytecode.original_bytes(),
649                    None => continue,
650                }
651            };
652            total_bytes += bytes.len();
653            codes.push(bytes);
654
655            if total_bytes > response_bytes {
656                break
657            }
658        }
659        Ok(codes)
660    }
661}
662
663/// Boundary-proof keys for a range reply: `origin`, plus the last returned item's key if any.
664fn boundary_proof_keys<T>(origin: B256, last: Option<&(B256, T)>) -> Vec<B256> {
665    match last {
666        Some((last, _)) => vec![origin, *last],
667        None => vec![origin],
668    }
669}
670
671/// An endless future.
672///
673/// This should be spawned or used as part of `tokio::select!`.
674impl<C, N> Future for EthRequestHandler<C, N>
675where
676    N: NetworkPrimitives,
677    C: BalProvider
678        + StateProviderFactory
679        + StateRangeProviderFactory
680        + BlockReader<Block = N::Block, Receipt = N::Receipt>
681        + HeaderProvider<Header = N::BlockHeader>
682        + Clone
683        + Unpin
684        + 'static,
685{
686    type Output = ();
687
688    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
689        let this = self.get_mut();
690
691        // Frees the slots of finished state range tasks first, so the requests admitted below see
692        // them and queued requests keep their turn.
693        this.state_range_requests.poll(cx, &this.client, &this.metrics);
694
695        let mut acc = Duration::ZERO;
696        let maybe_more_incoming_requests = metered_poll_nested_stream_with_budget!(
697            acc,
698            "net::eth",
699            "Incoming eth requests stream",
700            DEFAULT_BUDGET_TRY_DRAIN_DOWNLOADERS,
701            this.incoming_requests.poll_next_unpin(cx),
702            |incoming| {
703                match incoming {
704                    IncomingEthRequest::GetBlockHeaders { peer_id, request, response } => {
705                        this.on_headers_request(peer_id, request, response)
706                    }
707                    IncomingEthRequest::GetBlockBodies { peer_id, request, response } => {
708                        this.on_bodies_request(peer_id, request, response)
709                    }
710                    IncomingEthRequest::GetNodeData { peer_id, request, response } => {
711                        this.on_node_data_request(peer_id, request, response)
712                    }
713                    IncomingEthRequest::GetReceipts { peer_id, request, response } => {
714                        this.on_receipts_request(peer_id, request, response)
715                    }
716                    IncomingEthRequest::GetReceipts69 { peer_id, request, response } => {
717                        this.on_receipts69_request(peer_id, request, response)
718                    }
719                    IncomingEthRequest::GetReceipts70 { peer_id, request, response } => {
720                        this.on_receipts70_request(peer_id, request, response)
721                    }
722                    IncomingEthRequest::GetBlockAccessLists { peer_id, request, response } => {
723                        this.on_block_access_lists_request(peer_id, request, response)
724                    }
725                    IncomingEthRequest::GetCells { peer_id, request, response } => {
726                        this.on_cells_request(peer_id, request, response)
727                    }
728                    IncomingEthRequest::GetSnap { peer_id, request, response } => {
729                        this.on_snap_request(peer_id, request, response)
730                    }
731                }
732            },
733        );
734
735        this.metrics.acc_duration_poll_eth_req_handler.set(acc.as_secs_f64());
736
737        // Polled again so that the tasks and the queue timeout of requests admitted above wake this
738        // handler.
739        this.state_range_requests.poll(cx, &this.client, &this.metrics);
740
741        // stream is fully drained and import futures pending
742        if maybe_more_incoming_requests {
743            // make sure we're woken up again
744            cx.waker().wake_by_ref();
745        }
746
747        Poll::Pending
748    }
749}
750
751/// `snap/2` state range requests served off the handler task.
752///
753/// Unlike other requests, serving a range for an old root rewinds the state to that block, which
754/// can take seconds and would stall every peer if it ran on the handler task.
755///
756/// At most [`MAX_CONCURRENT_STATE_RANGE_REQUESTS`] run at once, one per peer. A request that can't
757/// start waits in a queue of at most [`MAX_QUEUED_STATE_RANGE_REQUESTS`], one place per peer, for
758/// at most [`STATE_RANGE_REQUEST_QUEUE_TIMEOUT`].
759#[derive(Debug, Default)]
760struct StateRangeRequests {
761    /// Requests being served on blocking tasks, with the peer each belongs to.
762    tasks: Vec<(PeerId, JoinHandle<()>)>,
763    /// Requests waiting for a slot in `tasks`, oldest first.
764    queue: VecDeque<IncomingStateRangeRequest>,
765    /// Wakes the handler when the oldest queued request times out.
766    queue_timeout: Option<Pin<Box<Sleep>>>,
767}
768
769impl StateRangeRequests {
770    /// Starts `incoming` or queues it until a slot is free.
771    ///
772    /// A request whose peer has already gone is dropped. One that finds the queue full, or its
773    /// peer already holding a place in it, is answered empty.
774    fn admit<C>(
775        &mut self,
776        incoming: IncomingStateRangeRequest,
777        client: &C,
778        metrics: &EthRequestHandlerMetrics,
779    ) where
780        C: StateRangeProviderFactory + Clone + Send + 'static,
781    {
782        if incoming.response.is_closed() {
783            return
784        }
785        if self.can_start(incoming.peer_id) {
786            return self.spawn(incoming, client)
787        }
788
789        self.remove_stale(metrics);
790        if self.queue.len() >= MAX_QUEUED_STATE_RANGE_REQUESTS ||
791            self.queue.iter().any(|queued| queued.peer_id == incoming.peer_id)
792        {
793            debug!(
794                target: "net::snap",
795                peer_id=?incoming.peer_id,
796                queued=self.queue.len(),
797                "no room to queue state range request"
798            );
799            return incoming.reply_empty(metrics)
800        }
801        self.queue.push_back(incoming);
802    }
803
804    /// Returns whether a request from `peer_id` can start now.
805    fn can_start(&self, peer_id: PeerId) -> bool {
806        self.tasks.len() < MAX_CONCURRENT_STATE_RANGE_REQUESTS &&
807            self.tasks.iter().all(|(running, _)| *running != peer_id)
808    }
809
810    /// Serves `incoming` on a blocking task, which holds its peer's slot until it finishes.
811    fn spawn<C>(&mut self, incoming: IncomingStateRangeRequest, client: &C)
812    where
813        C: StateRangeProviderFactory + Clone + Send + 'static,
814    {
815        let IncomingStateRangeRequest { peer_id, request, response, .. } = incoming;
816        let client = client.clone();
817        let span = Span::current();
818        let task = tokio::task::spawn_blocking(move || {
819            let _guard = span.enter();
820            let empty = request.empty_response();
821            let result = request.serve(&client).unwrap_or_else(|error| {
822                debug!(target: "net::snap", %error, "failed to serve state range");
823                empty
824            });
825            let _ = response.send(Ok(result));
826        });
827        self.tasks.push((peer_id, task));
828    }
829
830    /// Drops queued requests whose peer has gone, and answers empty those that waited longer than
831    /// [`STATE_RANGE_REQUEST_QUEUE_TIMEOUT`].
832    fn remove_stale(&mut self, metrics: &EthRequestHandlerMetrics) {
833        let mut index = 0;
834        while index < self.queue.len() {
835            let queued = &self.queue[index];
836            if queued.response.is_closed() {
837                self.queue.remove(index);
838            } else if queued.received.elapsed() < STATE_RANGE_REQUEST_QUEUE_TIMEOUT {
839                index += 1;
840            } else if let Some(incoming) = self.queue.remove(index) {
841                debug!(
842                    target: "net::snap",
843                    peer_id=?incoming.peer_id,
844                    "state range request timed out in queue"
845                );
846                incoming.reply_empty(metrics);
847            }
848        }
849    }
850
851    /// Frees the slots of finished tasks and starts queued requests, oldest first, in their place.
852    ///
853    /// Registers `cx` to be woken when a task finishes or the oldest queued request times out.
854    fn poll<C>(&mut self, cx: &mut Context<'_>, client: &C, metrics: &EthRequestHandlerMetrics)
855    where
856        C: StateRangeProviderFactory + Clone + Send + 'static,
857    {
858        // Runs again after starting queued requests so that their tasks wake this context, and
859        // after the queue timeout fires so that it is armed for the next request.
860        loop {
861            self.remove_stale(metrics);
862            self.tasks.retain_mut(|(_, task)| match Pin::new(task).poll(cx) {
863                Poll::Pending => true,
864                Poll::Ready(result) => {
865                    if let Err(error) = result {
866                        error!(target: "net::snap", %error, "state range task failed");
867                    }
868                    false
869                }
870            });
871
872            let mut spawned = false;
873            let mut index = 0;
874            while index < self.queue.len() && self.tasks.len() < MAX_CONCURRENT_STATE_RANGE_REQUESTS
875            {
876                // A peer with a request still running keeps its place and is passed over.
877                if !self.can_start(self.queue[index].peer_id) {
878                    index += 1;
879                } else if let Some(incoming) = self.queue.remove(index) {
880                    self.spawn(incoming, client);
881                    spawned = true;
882                }
883            }
884            if !spawned && !self.poll_queue_timeout(cx) {
885                break
886            }
887        }
888    }
889
890    /// Arms the timeout of the oldest queued request, returning whether it already fired.
891    fn poll_queue_timeout(&mut self, cx: &mut Context<'_>) -> bool {
892        let Some(oldest) = self.queue.front() else {
893            self.queue_timeout = None;
894            return false
895        };
896        let deadline = oldest.received + STATE_RANGE_REQUEST_QUEUE_TIMEOUT;
897        let timeout = self.queue_timeout.get_or_insert_with(|| Box::pin(sleep_until(deadline)));
898        timeout.as_mut().reset(deadline);
899        timeout.as_mut().poll(cx).is_ready()
900    }
901}
902
903/// A `snap/2` range request waiting for, or holding, a serving slot.
904#[derive(Debug)]
905struct IncomingStateRangeRequest {
906    /// Peer that sent the request.
907    peer_id: PeerId,
908    /// The range request the peer sent.
909    request: StateRangeRequest,
910    /// Channel the response is sent on.
911    response: oneshot::Sender<RequestResult<SnapResponse>>,
912    /// When the request arrived, which bounds how long it may wait in the queue.
913    received: Instant,
914}
915
916impl IncomingStateRangeRequest {
917    /// Answers the request empty without serving it.
918    fn reply_empty(self, metrics: &EthRequestHandlerMetrics) {
919        metrics.snap_state_range_requests_unserved_total.increment(1);
920        let _ = self.response.send(Ok(self.request.empty_response()));
921    }
922}
923
924/// A `snap/2` request for a range of state at a given root.
925#[derive(Debug)]
926enum StateRangeRequest {
927    /// A `GetAccountRange` request.
928    Account(GetAccountRangeMessage),
929    /// A `GetStorageRanges` request.
930    Storage(GetStorageRangesMessage),
931}
932
933impl StateRangeRequest {
934    /// Returns the response for a request that isn't served, which snap clients read as the root
935    /// being unavailable.
936    const fn empty_response(&self) -> SnapResponse {
937        match self {
938            Self::Account(req) => SnapResponse::AccountRange(AccountRangeMessage {
939                request_id: req.request_id,
940                accounts: Vec::new(),
941                proof: Vec::new(),
942            }),
943            Self::Storage(req) => SnapResponse::StorageRanges(StorageRangesMessage {
944                request_id: req.request_id,
945                slots: Vec::new(),
946                proof: Vec::new(),
947            }),
948        }
949    }
950
951    /// Serves the range from `client`.
952    fn serve(self, client: &impl StateRangeProviderFactory) -> ProviderResult<SnapResponse> {
953        match self {
954            Self::Account(req) => {
955                Self::serve_account_range(client, req).map(SnapResponse::AccountRange)
956            }
957            Self::Storage(req) => {
958                Self::serve_storage_ranges(client, req).map(SnapResponse::StorageRanges)
959            }
960        }
961    }
962
963    /// Serves a `GetAccountRange` request via [`StateRangeProviderFactory`].
964    ///
965    /// Fails the request if a storage root or proof becomes unavailable after the range lookup.
966    /// Proves the boundary between `starting_hash` and the last returned account, per snap/2's
967    /// boundary-proof requirement, unless the range is a zero-origin range that exhausted the
968    /// trie, in which case no proof is needed.
969    fn serve_account_range(
970        client: &impl StateRangeProviderFactory,
971        req: GetAccountRangeMessage,
972    ) -> ProviderResult<AccountRangeMessage> {
973        let empty = AccountRangeMessage {
974            request_id: req.request_id,
975            accounts: Vec::new(),
976            proof: Vec::new(),
977        };
978
979        let response_bytes = (req.response_bytes as usize).min(SOFT_RESPONSE_LIMIT);
980        let Some(state) = client.state_range_provider(req.root_hash)? else { return Ok(empty) };
981        let RangeResponse { items: accounts, end } =
982            state.account_range(req.starting_hash, req.limit_hash, response_bytes)?;
983
984        let proof = if req.starting_hash.is_zero() && end == RangeEnd::Exhausted {
985            Vec::new()
986        } else {
987            let boundary_keys = boundary_proof_keys(req.starting_hash, accounts.last());
988            state.account_range_proof(&boundary_keys)?
989        };
990
991        let mut account_data = Vec::with_capacity(accounts.len());
992        for (hash, account) in accounts {
993            let storage_root = state.storage_root_by_hash(hash)?;
994            account_data.push(AccountData::from_trie_account(
995                hash,
996                &account.into_trie_account(storage_root),
997            ));
998        }
999
1000        Ok(AccountRangeMessage { request_id: req.request_id, accounts: account_data, proof })
1001    }
1002
1003    /// Serves a `GetStorageRanges` request via [`StateRangeProviderFactory`].
1004    ///
1005    /// `starting_hash`/`limit_hash` apply only to the first account. An account unavailable at
1006    /// this root makes the whole response empty, rather than skipping it and shifting later
1007    /// accounts' positions. A proof stops the response at the first account that isn't a
1008    /// complete, zero-origin range.
1009    fn serve_storage_ranges(
1010        client: &impl StateRangeProviderFactory,
1011        req: GetStorageRangesMessage,
1012    ) -> ProviderResult<StorageRangesMessage> {
1013        let empty = StorageRangesMessage {
1014            request_id: req.request_id,
1015            slots: Vec::new(),
1016            proof: Vec::new(),
1017        };
1018        let Some(state) = client.state_range_provider(req.root_hash)? else { return Ok(empty) };
1019        let mut slots: Vec<Vec<StorageData>> = Vec::new();
1020        let mut proof = Vec::new();
1021        let mut remaining_bytes = (req.response_bytes as usize).min(SOFT_RESPONSE_LIMIT);
1022
1023        for (i, &hashed_address) in
1024            req.account_hashes.iter().take(MAX_STORAGE_RANGE_ACCOUNTS_SERVE).enumerate()
1025        {
1026            // Keeps traversing storage-empty accounts under a zero budget so a real slot still
1027            // gets served; worst case is a lookup per account, bounded by the take() above.
1028            if remaining_bytes == 0 && slots.iter().any(|range| !range.is_empty()) {
1029                break
1030            }
1031            let (origin, limit) = if i == 0 {
1032                (
1033                    req.starting_hash.unwrap_or(B256::ZERO),
1034                    req.limit_hash.unwrap_or(B256::repeat_byte(0xff)),
1035                )
1036            } else {
1037                (B256::ZERO, B256::repeat_byte(0xff))
1038            };
1039            let Some(RangeResponse { items: account_slots, end }) =
1040                state.storage_range(hashed_address, origin, limit, remaining_bytes)?
1041            else {
1042                return Ok(empty)
1043            };
1044
1045            remaining_bytes = remaining_bytes.saturating_sub(account_slots.len() * 64);
1046            let last = account_slots.last().map(|(hash, _)| *hash);
1047            let needs_proof = !origin.is_zero() || end != RangeEnd::Exhausted;
1048            slots.push(
1049                account_slots
1050                    .into_iter()
1051                    // snap clients verify proofs against RLP-encoded storage trie leaves.
1052                    .map(|(hash, value)| StorageData::from_value(hash, value))
1053                    .collect(),
1054            );
1055
1056            if needs_proof {
1057                let boundary_keys = match last {
1058                    Some(last) => vec![origin, last],
1059                    None => vec![origin],
1060                };
1061                proof = state.storage_range_proof(hashed_address, &boundary_keys)?;
1062                break
1063            }
1064        }
1065
1066        Ok(StorageRangesMessage { request_id: req.request_id, slots, proof })
1067    }
1068}
1069
1070/// All `eth` request related to blocks delegated by the network.
1071#[derive(Debug)]
1072pub enum IncomingEthRequest<N: NetworkPrimitives = EthNetworkPrimitives> {
1073    /// Request Block headers from the peer.
1074    ///
1075    /// The response should be sent through the channel.
1076    GetBlockHeaders {
1077        /// The ID of the peer to request block headers from.
1078        peer_id: PeerId,
1079        /// The specific block headers requested.
1080        request: GetBlockHeaders,
1081        /// The channel sender for the response containing block headers.
1082        response: oneshot::Sender<RequestResult<BlockHeaders<N::BlockHeader>>>,
1083    },
1084    /// Request Block bodies from the peer.
1085    ///
1086    /// The response should be sent through the channel.
1087    GetBlockBodies {
1088        /// The ID of the peer to request block bodies from.
1089        peer_id: PeerId,
1090        /// The specific block bodies requested.
1091        request: GetBlockBodies,
1092        /// The channel sender for the response containing block bodies.
1093        response: oneshot::Sender<RequestResult<BlockBodies<N::BlockBody>>>,
1094    },
1095    /// Request Node Data from the peer.
1096    ///
1097    /// The response should be sent through the channel.
1098    GetNodeData {
1099        /// The ID of the peer to request node data from.
1100        peer_id: PeerId,
1101        /// The specific node data requested.
1102        request: GetNodeData,
1103        /// The channel sender for the response containing node data.
1104        response: oneshot::Sender<RequestResult<NodeData>>,
1105    },
1106    /// Request Receipts from the peer.
1107    ///
1108    /// The response should be sent through the channel.
1109    GetReceipts {
1110        /// The ID of the peer to request receipts from.
1111        peer_id: PeerId,
1112        /// The specific receipts requested.
1113        request: GetReceipts,
1114        /// The channel sender for the response containing receipts.
1115        response: oneshot::Sender<RequestResult<Receipts<N::Receipt>>>,
1116    },
1117    /// Request Receipts from the peer without bloom filter.
1118    ///
1119    /// The response should be sent through the channel.
1120    GetReceipts69 {
1121        /// The ID of the peer to request receipts from.
1122        peer_id: PeerId,
1123        /// The specific receipts requested.
1124        request: GetReceipts,
1125        /// The channel sender for the response containing Receipts69.
1126        response: oneshot::Sender<RequestResult<Receipts69<N::Receipt>>>,
1127    },
1128    /// Request Receipts from the peer using eth/70.
1129    ///
1130    /// The response should be sent through the channel.
1131    GetReceipts70 {
1132        /// The ID of the peer to request receipts from.
1133        peer_id: PeerId,
1134        /// The specific receipts requested including the `firstBlockReceiptIndex`.
1135        request: GetReceipts70,
1136        /// The channel sender for the response containing Receipts70.
1137        response: oneshot::Sender<RequestResult<Receipts70<N::Receipt>>>,
1138    },
1139    /// Request Block Access Lists from the peer.
1140    ///
1141    /// The response should be sent through the channel.
1142    GetBlockAccessLists {
1143        /// The ID of the peer to request block access lists from.
1144        peer_id: PeerId,
1145        /// The requested block hashes.
1146        request: GetBlockAccessLists,
1147        /// The channel sender for the response containing block access lists.
1148        response: oneshot::Sender<RequestResult<BlockAccessLists>>,
1149    },
1150    /// Request Cells from the peer.
1151    ///
1152    /// The response should be sent through the channel.
1153    GetCells {
1154        /// The ID of the peer to request cells from.
1155        peer_id: PeerId,
1156        /// The requested block hashes.
1157        request: GetCells,
1158        /// The channel sender for the response containing cells.
1159        response: oneshot::Sender<RequestResult<Cells>>,
1160    },
1161    /// Request a `snap/2` message from the peer.
1162    ///
1163    /// The response should be sent through the channel.
1164    GetSnap {
1165        /// The ID of the peer to request from.
1166        peer_id: PeerId,
1167        /// The `snap/2` request.
1168        request: SnapProtocolMessage,
1169        /// The channel sender for the response.
1170        response: oneshot::Sender<RequestResult<SnapResponse>>,
1171    },
1172}
1173
1174#[cfg(test)]
1175mod tests {
1176    use super::*;
1177    use alloy_consensus::{constants::EMPTY_ROOT_HASH, Header, TxType};
1178    use alloy_eips::{
1179        eip4844::{BlobAndProofV1, BlobAndProofV2, BlobCellsAndProofsV1},
1180        eip7594::{BlobCellMask, BlobTransactionSidecarVariant, Cell, BYTES_PER_CELL},
1181    };
1182    use alloy_primitives::{keccak256, Address, Log, LogData, TxHash, B128, U256};
1183    use alloy_rlp::{Decodable, Encodable};
1184    use reth_eth_wire::{message::RequestPair, EthMessage, EthStreamInner, EthVersion};
1185    use reth_ethereum_primitives::Receipt;
1186    use reth_primitives_traits::Account;
1187    use reth_provider::test_utils::{ExtendedAccount, MockEthProvider};
1188    use reth_storage_api::noop::NoopProvider;
1189    use reth_transaction_pool::blobstore::{
1190        BlobStoreCleanupStat, BlobStoreError, PooledBlobSidecar,
1191    };
1192    use std::sync::{
1193        atomic::{AtomicUsize, Ordering},
1194        Arc,
1195    };
1196    use test_case::test_case;
1197    use tokio::sync::mpsc;
1198
1199    #[derive(Debug, Default)]
1200    struct CountingBlobStore {
1201        get_cells_calls: Arc<AtomicUsize>,
1202        expected_cell_mask: Option<BlobCellMask>,
1203        cell_responses: Vec<(B256, BlobCellMask, Vec<Cell>)>,
1204    }
1205
1206    impl BlobStore for CountingBlobStore {
1207        fn insert(&self, _tx: B256, _data: PooledBlobSidecar) -> Result<(), BlobStoreError> {
1208            Ok(())
1209        }
1210
1211        fn insert_all(&self, _txs: Vec<(B256, PooledBlobSidecar)>) -> Result<(), BlobStoreError> {
1212            Ok(())
1213        }
1214
1215        fn delete(&self, _tx: B256) -> Result<(), BlobStoreError> {
1216            Ok(())
1217        }
1218
1219        fn delete_all(&self, _txs: Vec<B256>) -> Result<(), BlobStoreError> {
1220            Ok(())
1221        }
1222
1223        fn cleanup(&self) -> BlobStoreCleanupStat {
1224            BlobStoreCleanupStat::default()
1225        }
1226
1227        fn get(
1228            &self,
1229            _tx: B256,
1230        ) -> Result<Option<Arc<BlobTransactionSidecarVariant>>, BlobStoreError> {
1231            Ok(None)
1232        }
1233
1234        fn contains(&self, _tx: B256) -> Result<bool, BlobStoreError> {
1235            Ok(false)
1236        }
1237
1238        fn get_all(
1239            &self,
1240            _txs: Vec<B256>,
1241        ) -> Result<Vec<(B256, Arc<BlobTransactionSidecarVariant>)>, BlobStoreError> {
1242            Ok(vec![])
1243        }
1244
1245        fn get_exact(
1246            &self,
1247            txs: Vec<B256>,
1248        ) -> Result<Vec<Arc<BlobTransactionSidecarVariant>>, BlobStoreError> {
1249            if txs.is_empty() {
1250                return Ok(vec![])
1251            }
1252
1253            Err(BlobStoreError::MissingSidecar(txs[0]))
1254        }
1255
1256        fn get_by_versioned_hashes_v1(
1257            &self,
1258            versioned_hashes: &[B256],
1259        ) -> Result<Vec<Option<BlobAndProofV1>>, BlobStoreError> {
1260            Ok(vec![None; versioned_hashes.len()])
1261        }
1262
1263        fn get_by_versioned_hashes_v2(
1264            &self,
1265            _versioned_hashes: &[B256],
1266        ) -> Result<Option<Vec<BlobAndProofV2>>, BlobStoreError> {
1267            Ok(None)
1268        }
1269
1270        fn get_by_versioned_hashes_v3(
1271            &self,
1272            versioned_hashes: &[B256],
1273        ) -> Result<Vec<Option<BlobAndProofV2>>, BlobStoreError> {
1274            Ok(vec![None; versioned_hashes.len()])
1275        }
1276
1277        fn get_by_versioned_hashes_v4(
1278            &self,
1279            versioned_hashes: &[B256],
1280            _cell_mask: BlobCellMask,
1281        ) -> Result<Vec<Option<BlobCellsAndProofsV1>>, BlobStoreError> {
1282            Ok(vec![None; versioned_hashes.len()])
1283        }
1284
1285        fn has_versioned_hashes(
1286            &self,
1287            versioned_hashes: &[B256],
1288        ) -> Result<Vec<bool>, BlobStoreError> {
1289            Ok(vec![false; versioned_hashes.len()])
1290        }
1291
1292        fn get_cells(
1293            &self,
1294            tx_hash: TxHash,
1295            cell_mask: BlobCellMask,
1296        ) -> Result<Option<Vec<Cell>>, BlobStoreError> {
1297            self.get_cells_calls.fetch_add(1, Ordering::Relaxed);
1298            if let Some((_, expected, cells)) =
1299                self.cell_responses.iter().find(|(hash, _, _)| *hash == tx_hash)
1300            {
1301                assert_eq!(cell_mask, *expected);
1302                return Ok(Some(cells.clone()))
1303            }
1304            if let Some(expected) = self.expected_cell_mask {
1305                assert_eq!(cell_mask, expected);
1306                return Ok(Some(vec![Cell::default()]))
1307            }
1308            Ok(None)
1309        }
1310
1311        fn data_size_hint(&self) -> Option<usize> {
1312            Some(0)
1313        }
1314
1315        fn blobs_len(&self) -> usize {
1316            0
1317        }
1318    }
1319
1320    #[tokio::test]
1321    async fn get_cells_request_limits_blob_store_lookups() {
1322        let (_incoming_tx, incoming_rx) = mpsc::channel(1);
1323        let get_cells_calls = Arc::new(AtomicUsize::new(0));
1324        let blob_store = CountingBlobStore {
1325            get_cells_calls: Arc::clone(&get_cells_calls),
1326            ..Default::default()
1327        };
1328        let handler = EthRequestHandler::<NoopProvider>::new(NoopProvider::default(), incoming_rx)
1329            .with_blob_store(Box::new(blob_store));
1330        let (response, rx) = oneshot::channel();
1331        let request = GetCells {
1332            hashes: (0..=MAX_CELLS_SERVE).map(|i| B256::from(U256::from(i))).collect(),
1333            cell_mask: B128::from(1u128.to_le_bytes()).into(),
1334        };
1335
1336        handler.on_cells_request(PeerId::default(), request, response);
1337
1338        let cells = rx.await.unwrap().unwrap();
1339        assert!(cells.hashes.is_empty());
1340        assert_eq!(get_cells_calls.load(Ordering::Relaxed), MAX_CELLS_SERVE);
1341    }
1342
1343    #[test_case(B128::ZERO, 0; "empty_mask")]
1344    #[test_case(B128::from(1u128.to_le_bytes()), 1; "duplicate_hashes")]
1345    #[tokio::test]
1346    async fn get_cells_request_skips_work_that_adds_no_cells(mask: B128, lookups: usize) {
1347        let (_incoming_tx, incoming_rx) = mpsc::channel(1);
1348        let get_cells_calls = Arc::new(AtomicUsize::new(0));
1349        let blob_store = CountingBlobStore {
1350            get_cells_calls: Arc::clone(&get_cells_calls),
1351            expected_cell_mask: Some(BlobCellMask::new(mask)),
1352            ..Default::default()
1353        };
1354        let handler = EthRequestHandler::<NoopProvider>::new(NoopProvider::default(), incoming_rx)
1355            .with_blob_store(Box::new(blob_store));
1356        let (response, rx) = oneshot::channel();
1357        let request =
1358            GetCells { hashes: vec![B256::ZERO; MAX_CELLS_SERVE], cell_mask: mask.into() };
1359
1360        handler.on_cells_request(PeerId::default(), request, response);
1361
1362        let cells = rx.await.unwrap().unwrap();
1363        assert_eq!(cells.hashes, vec![B256::ZERO; lookups]);
1364        assert_eq!(get_cells_calls.load(Ordering::Relaxed), lookups);
1365    }
1366
1367    #[tokio::test]
1368    async fn get_cells_request_limits_served_blobs() {
1369        let (_incoming_tx, incoming_rx) = mpsc::channel(1);
1370        let get_cells_calls = Arc::new(AtomicUsize::new(0));
1371        let mask = B128::from(3u128.to_le_bytes());
1372        let hashes =
1373            (0..=MAX_CELL_BLOBS_SERVE).map(|i| B256::from(U256::from(i))).collect::<Vec<_>>();
1374        // Each transaction has two blobs and the mask selects two cells of each, so counting
1375        // transactions or cells instead of blobs serves a different number of transactions.
1376        let blob_store = CountingBlobStore {
1377            get_cells_calls: Arc::clone(&get_cells_calls),
1378            cell_responses: hashes
1379                .iter()
1380                .map(|&hash| (hash, BlobCellMask::new(mask), vec![Cell::ZERO; 4]))
1381                .collect(),
1382            ..Default::default()
1383        };
1384        let handler = EthRequestHandler::<NoopProvider>::new(NoopProvider::default(), incoming_rx)
1385            .with_blob_store(Box::new(blob_store));
1386        let (response, rx) = oneshot::channel();
1387        let request = GetCells { hashes, cell_mask: mask.into() };
1388
1389        handler.on_cells_request(PeerId::default(), request, response);
1390
1391        let cells = rx.await.unwrap().unwrap();
1392        assert_eq!(cells.hashes.len(), MAX_CELL_BLOBS_SERVE / 2);
1393        assert_eq!(get_cells_calls.load(Ordering::Relaxed), MAX_CELL_BLOBS_SERVE / 2);
1394    }
1395
1396    #[test_case(0)]
1397    #[test_case(7)]
1398    #[test_case(8)]
1399    #[test_case(63)]
1400    #[test_case(64)]
1401    #[test_case(127)]
1402    #[tokio::test]
1403    async fn get_cells_request_uses_little_endian_wire_mask(index: u32) {
1404        let (_incoming_tx, incoming_rx) = mpsc::channel(1);
1405        let numeric_mask = 1u128 << index;
1406        let blob_store = CountingBlobStore {
1407            expected_cell_mask: Some(BlobCellMask::from_bits(numeric_mask)),
1408            ..Default::default()
1409        };
1410        let handler = EthRequestHandler::<NoopProvider>::new(NoopProvider::default(), incoming_rx)
1411            .with_blob_store(Box::new(blob_store));
1412        let wire_mask = B128::from(numeric_mask.to_le_bytes());
1413        let request = GetCells { hashes: vec![B256::ZERO], cell_mask: wire_mask.into() };
1414        let mut encoded = Vec::new();
1415        request.encode(&mut encoded);
1416        let request = GetCells::decode(&mut encoded.as_slice()).unwrap();
1417        let (response, rx) = oneshot::channel();
1418
1419        handler.on_cells_request(PeerId::default(), request, response);
1420
1421        let cells = rx.await.unwrap().unwrap();
1422        assert_eq!(cells.hashes, vec![B256::ZERO]);
1423        assert_eq!(cells.cells, vec![vec![Cell::default()]]);
1424        assert_eq!(cells.cell_mask, wire_mask.into());
1425        encoded.clear();
1426        cells.encode(&mut encoded);
1427        assert_eq!(Cells::decode(&mut encoded.as_slice()).unwrap(), cells);
1428    }
1429
1430    #[tokio::test]
1431    async fn indexed_cells_rebuilds_table_after_omissions() {
1432        let (_incoming_tx, incoming_rx) = mpsc::channel(1);
1433        let hashes = (0..5).map(B256::repeat_byte).collect::<Vec<_>>();
1434        let a = B128::from(1u128.to_le_bytes());
1435        let b = B128::from(2u128.to_le_bytes());
1436        let c = B128::from(4u128.to_le_bytes());
1437        let request = GetCells::from_masks(hashes.clone(), vec![a, b, a, c, b]).unwrap();
1438        let blob_store = CountingBlobStore {
1439            cell_responses: vec![
1440                (hashes[1], BlobCellMask::from_bits(2), vec![Cell::repeat_byte(1)]),
1441                (hashes[2], BlobCellMask::from_bits(1), vec![Cell::repeat_byte(2)]),
1442                (hashes[3], BlobCellMask::from_bits(4), vec![Cell::repeat_byte(3)]),
1443                (hashes[4], BlobCellMask::from_bits(2), vec![Cell::repeat_byte(4)]),
1444            ],
1445            ..Default::default()
1446        };
1447        let handler = EthRequestHandler::<NoopProvider>::new(NoopProvider::default(), incoming_rx)
1448            .with_blob_store(Box::new(blob_store));
1449        let (response, rx) = oneshot::channel();
1450        handler.on_cells_request(PeerId::default(), request.clone(), response);
1451        let cells = rx.await.unwrap().unwrap();
1452        assert_eq!(cells.hashes, hashes[1..]);
1453        assert_eq!(
1454            cells.cell_mask,
1455            CellMasks::Indexed {
1456                masks: vec![b, a, c],
1457                mask_ids: Bytes::from_static(&[0, 1, 2, 0]),
1458            }
1459        );
1460        assert_eq!(cells.validate_response(&request), Ok(()));
1461    }
1462
1463    #[tokio::test]
1464    async fn indexed_empty_response_preserves_form() {
1465        let (_incoming_tx, incoming_rx) = mpsc::channel(1);
1466        let handler = EthRequestHandler::<NoopProvider>::new(NoopProvider::default(), incoming_rx);
1467        let (response, rx) = oneshot::channel();
1468        let request = GetCells::from_masks(
1469            vec![B256::ZERO, B256::repeat_byte(1)],
1470            vec![B128::ZERO, B128::repeat_byte(1)],
1471        )
1472        .unwrap();
1473        handler.on_cells_request(PeerId::default(), request.clone(), response);
1474        let cells = rx.await.unwrap().unwrap();
1475        assert_eq!(
1476            cells,
1477            Cells {
1478                cell_mask: CellMasks::Indexed { masks: vec![], mask_ids: Bytes::new() },
1479                ..Default::default()
1480            }
1481        );
1482        assert_eq!(cells.validate_response(&request), Ok(()));
1483    }
1484
1485    #[test_case(1; "invalid_identifier")]
1486    #[test_case(0; "uniform_indexed_request")]
1487    #[tokio::test]
1488    async fn invalid_indexed_request_performs_no_lookups(id: u8) {
1489        let (_incoming_tx, incoming_rx) = mpsc::channel(1);
1490        let calls = Arc::new(AtomicUsize::new(0));
1491        let blob_store =
1492            CountingBlobStore { get_cells_calls: Arc::clone(&calls), ..Default::default() };
1493        let handler = EthRequestHandler::<NoopProvider>::new(NoopProvider::default(), incoming_rx)
1494            .with_blob_store(Box::new(blob_store));
1495        let (response, rx) = oneshot::channel();
1496        let request = GetCells {
1497            hashes: vec![B256::ZERO],
1498            cell_mask: CellMasks::Indexed { masks: vec![B128::ZERO], mask_ids: vec![id].into() },
1499        };
1500        handler.on_cells_request(PeerId::default(), request, response);
1501        assert_eq!(rx.await.unwrap(), Err(RequestError::InvalidRequest));
1502        assert_eq!(calls.load(Ordering::Relaxed), 0);
1503    }
1504
1505    #[test_case(false)]
1506    #[test_case(true)]
1507    #[tokio::test]
1508    async fn cells_forms_share_response_limit(indexed: bool) {
1509        let (_incoming_tx, incoming_rx) = mpsc::channel(1);
1510        let calls = Arc::new(AtomicUsize::new(0));
1511        let hashes = vec![B256::ZERO, B256::repeat_byte(1)];
1512        let mask = B128::from(1u128.to_le_bytes());
1513        let blob_store = CountingBlobStore {
1514            get_cells_calls: Arc::clone(&calls),
1515            cell_responses: vec![(
1516                hashes[0],
1517                BlobCellMask::from_bits(1),
1518                vec![Cell::ZERO; SOFT_RESPONSE_LIMIT / BYTES_PER_CELL + 1],
1519            )],
1520            ..Default::default()
1521        };
1522        let handler = EthRequestHandler::<NoopProvider>::new(NoopProvider::default(), incoming_rx)
1523            .with_blob_store(Box::new(blob_store));
1524        let (response, rx) = oneshot::channel();
1525        let request = GetCells {
1526            hashes: hashes.clone(),
1527            cell_mask: if indexed {
1528                CellMasks::Indexed {
1529                    masks: vec![mask, B128::from(2u128.to_le_bytes())],
1530                    mask_ids: Bytes::from_static(&[0, 1]),
1531                }
1532            } else {
1533                mask.into()
1534            },
1535        };
1536        handler.on_cells_request(PeerId::default(), request, response);
1537        let cells = rx.await.unwrap().unwrap();
1538        assert_eq!(cells.hashes, vec![hashes[0]]);
1539        assert_eq!(calls.load(Ordering::Relaxed), 1);
1540    }
1541
1542    #[tokio::test]
1543    async fn get_node_data_responds_with_empty_payload() {
1544        let (_incoming_tx, incoming_rx) = mpsc::channel(1);
1545        let handler = EthRequestHandler::<NoopProvider>::new(NoopProvider::default(), incoming_rx);
1546        let (response, rx) = oneshot::channel();
1547
1548        handler.on_node_data_request(PeerId::default(), GetNodeData(vec![B256::ZERO]), response);
1549
1550        let node_data = rx.await.expect("response channel must not be dropped").unwrap();
1551        assert!(node_data.0.is_empty(), "GetNodeData should reply with empty NodeData");
1552    }
1553
1554    /// Creates a request handler backed by the mock provider for snap response tests.
1555    fn snap_handler(
1556        provider: MockEthProvider,
1557    ) -> EthRequestHandler<MockEthProvider, EthNetworkPrimitives> {
1558        let (_incoming_tx, incoming_rx) = mpsc::channel(1);
1559        EthRequestHandler::new(provider, incoming_rx)
1560    }
1561
1562    #[test_case(
1563        SnapProtocolMessage::GetAccountRange(GetAccountRangeMessage {
1564            request_id: 1,
1565            root_hash: B256::ZERO,
1566            starting_hash: B256::ZERO,
1567            limit_hash: B256::repeat_byte(0xff),
1568            response_bytes: SOFT_RESPONSE_LIMIT as u64,
1569        }),
1570        SnapResponse::AccountRange(AccountRangeMessage {
1571            request_id: 1,
1572            accounts: Vec::new(),
1573            proof: Vec::new(),
1574        }); "account range"
1575    )]
1576    #[test_case(
1577        SnapProtocolMessage::GetStorageRanges(GetStorageRangesMessage {
1578            request_id: 2,
1579            root_hash: B256::ZERO,
1580            account_hashes: vec![B256::ZERO],
1581            starting_hash: B256::ZERO.into(),
1582            limit_hash: B256::repeat_byte(0xff).into(),
1583            response_bytes: SOFT_RESPONSE_LIMIT as u64,
1584        }),
1585        SnapResponse::StorageRanges(StorageRangesMessage {
1586            request_id: 2,
1587            slots: Vec::new(),
1588            proof: Vec::new(),
1589        }); "storage ranges"
1590    )]
1591    #[test_case(
1592        SnapProtocolMessage::GetByteCodes(reth_eth_wire::snap::GetByteCodesMessage {
1593            request_id: 3,
1594            hashes: vec![B256::repeat_byte(0x11)],
1595            response_bytes: SOFT_RESPONSE_LIMIT as u64,
1596        }),
1597        SnapResponse::ByteCodes(ByteCodesMessage { request_id: 3, codes: Vec::new() }); "bytecodes"
1598    )]
1599    #[tokio::test]
1600    async fn snap_requests_return_empty_responses_on_provider_errors(
1601        request: SnapProtocolMessage,
1602        expected: SnapResponse,
1603    ) {
1604        let provider = MockEthProvider::default();
1605        provider.set_snap_state_reads_fail(true);
1606        let mut handler = snap_handler(provider);
1607        let (response, rx) = oneshot::channel();
1608
1609        handler.on_snap_request(PeerId::default(), request, response);
1610
1611        assert_eq!(rx.await.unwrap(), Ok(expected));
1612    }
1613
1614    #[tokio::test]
1615    async fn unavailable_snap_state_returns_empty_response() {
1616        let provider = MockEthProvider::default();
1617        let mut handler = snap_handler(provider.clone());
1618        let (response, rx) = oneshot::channel();
1619        handler.on_snap_request(
1620            PeerId::default(),
1621            SnapProtocolMessage::GetAccountRange(GetAccountRangeMessage {
1622                request_id: 1,
1623                root_hash: B256::ZERO,
1624                starting_hash: B256::ZERO,
1625                limit_hash: B256::repeat_byte(0xff),
1626                response_bytes: SOFT_RESPONSE_LIMIT as u64,
1627            }),
1628            response,
1629        );
1630
1631        assert_eq!(
1632            rx.await.unwrap(),
1633            Ok(SnapResponse::AccountRange(AccountRangeMessage {
1634                request_id: 1,
1635                accounts: Vec::new(),
1636                proof: Vec::new(),
1637            }))
1638        );
1639        assert_eq!(provider.snap_state_range_resolutions(), 1);
1640    }
1641
1642    fn account_range_request() -> SnapProtocolMessage {
1643        SnapProtocolMessage::GetAccountRange(GetAccountRangeMessage {
1644            request_id: 1,
1645            root_hash: B256::ZERO,
1646            starting_hash: B256::ZERO,
1647            limit_hash: B256::repeat_byte(0xff),
1648            response_bytes: SOFT_RESPONSE_LIMIT as u64,
1649        })
1650    }
1651
1652    fn empty_account_range() -> SnapResponse {
1653        SnapResponse::AccountRange(AccountRangeMessage {
1654            request_id: 1,
1655            accounts: Vec::new(),
1656            proof: Vec::new(),
1657        })
1658    }
1659
1660    #[tokio::test]
1661    async fn busy_state_range_request_waits_for_a_slot() {
1662        let provider = MockEthProvider::default();
1663        let mut handler = snap_handler(provider.clone());
1664        // Every slot is taken, and the requesting peer holds the one that finishes on `release`.
1665        let peer_id = PeerId::default();
1666        let (release, released) = oneshot::channel::<()>();
1667        handler.state_range_requests.tasks.push((
1668            peer_id,
1669            tokio::spawn(async move {
1670                let _ = released.await;
1671            }),
1672        ));
1673        let busy_peer = PeerId::repeat_byte(1);
1674        for peer in std::iter::once(busy_peer).chain((2..).map(PeerId::repeat_byte)) {
1675            if handler.state_range_requests.tasks.len() == MAX_CONCURRENT_STATE_RANGE_REQUESTS {
1676                break
1677            }
1678            handler
1679                .state_range_requests
1680                .tasks
1681                .push((peer, tokio::spawn(futures::future::pending())));
1682        }
1683        // A peer whose request keeps running is queued first, and must be passed over.
1684        let (response, mut passed_over) = oneshot::channel();
1685        handler.on_snap_request(busy_peer, account_range_request(), response);
1686        let (response, mut rx) = oneshot::channel();
1687        handler.on_snap_request(peer_id, account_range_request(), response);
1688
1689        assert_eq!(handler.state_range_requests.queue.len(), 2);
1690        assert_eq!(provider.snap_state_range_resolutions(), 0);
1691
1692        release.send(()).unwrap();
1693        // Only the queue is polled, so the request it starts is served and its slot freed only if
1694        // that task wakes this one.
1695        let EthRequestHandler { state_range_requests, client, metrics, .. } = &mut handler;
1696        let wait = Duration::from_secs(5);
1697        let started = Instant::now();
1698        let mut served = None;
1699        tokio::time::timeout(
1700            wait,
1701            std::future::poll_fn(|cx| {
1702                state_range_requests.poll(cx, client, metrics);
1703                if served.is_none() {
1704                    served = rx.try_recv().ok();
1705                }
1706                if served.is_some() &&
1707                    state_range_requests.tasks.len() < MAX_CONCURRENT_STATE_RANGE_REQUESTS
1708                {
1709                    Poll::Ready(())
1710                } else {
1711                    Poll::Pending
1712                }
1713            }),
1714        )
1715        .await
1716        .expect("queued state range request must be served once a slot frees");
1717
1718        assert!(started.elapsed() < wait, "task started from the queue must wake the poller");
1719        assert_eq!(served, Some(Ok(empty_account_range())));
1720        assert_eq!(provider.snap_state_range_resolutions(), 1);
1721        assert_eq!(handler.state_range_requests.queue.len(), 1);
1722        assert_eq!(passed_over.try_recv(), Err(oneshot::error::TryRecvError::Empty));
1723    }
1724
1725    #[tokio::test]
1726    async fn stale_queued_state_range_requests_are_not_served() {
1727        let provider = MockEthProvider::default();
1728        let mut handler = snap_handler(provider.clone());
1729        for byte in 0..MAX_CONCURRENT_STATE_RANGE_REQUESTS as u8 {
1730            handler
1731                .state_range_requests
1732                .tasks
1733                .push((PeerId::repeat_byte(byte), tokio::spawn(futures::future::pending())));
1734        }
1735        // One peer goes away while its request is queued.
1736        let (response, gone) = oneshot::channel();
1737        handler.on_snap_request(PeerId::repeat_byte(0x80), account_range_request(), response);
1738        drop(gone);
1739        // Another request is about to time out, with nothing else left to wake the handler.
1740        let SnapProtocolMessage::GetAccountRange(request) = account_range_request() else {
1741            unreachable!("fixture is an account range request")
1742        };
1743        let (response, mut expired) = oneshot::channel();
1744        handler.state_range_requests.queue.push_back(IncomingStateRangeRequest {
1745            peer_id: PeerId::repeat_byte(0x81),
1746            request: StateRangeRequest::Account(request),
1747            response,
1748            received: Instant::now() + Duration::from_millis(50) -
1749                STATE_RANGE_REQUEST_QUEUE_TIMEOUT,
1750        });
1751
1752        // Only the queue is polled, so nothing but its timeout can wake this task before the wait
1753        // below gives up.
1754        let EthRequestHandler { state_range_requests, client, metrics, .. } = &mut handler;
1755        let wait = Duration::from_secs(5);
1756        let started = Instant::now();
1757        let answer = tokio::time::timeout(
1758            wait,
1759            std::future::poll_fn(|cx| {
1760                state_range_requests.poll(cx, client, metrics);
1761                Pin::new(&mut expired).poll(cx)
1762            }),
1763        )
1764        .await
1765        .expect("queued state range request must be answered when it times out");
1766
1767        assert!(started.elapsed() < wait, "queue timeout must wake the poller");
1768        assert_eq!(answer.unwrap(), Ok(empty_account_range()));
1769        assert!(handler.state_range_requests.queue.is_empty());
1770        assert_eq!(provider.snap_state_range_resolutions(), 0);
1771    }
1772
1773    #[tokio::test]
1774    async fn incoming_state_range_request_sees_slots_freed_since_the_last_poll() {
1775        let provider = MockEthProvider::default();
1776        let (incoming_tx, incoming_rx) = mpsc::channel(1);
1777        let mut handler = snap_handler(provider.clone());
1778        handler.incoming_requests = ReceiverStream::new(incoming_rx);
1779        // The peer's task finished after the last poll, and it has another request queued.
1780        let peer_id = PeerId::default();
1781        let finished = tokio::spawn(async {});
1782        while !finished.is_finished() {
1783            tokio::task::yield_now().await;
1784        }
1785        handler.state_range_requests.tasks.push((peer_id, finished));
1786        for byte in 1..MAX_CONCURRENT_STATE_RANGE_REQUESTS as u8 {
1787            handler
1788                .state_range_requests
1789                .tasks
1790                .push((PeerId::repeat_byte(byte), tokio::spawn(futures::future::pending())));
1791        }
1792        let (response, _queued) = oneshot::channel();
1793        handler.on_snap_request(peer_id, account_range_request(), response);
1794        assert_eq!(handler.state_range_requests.queue.len(), 1);
1795
1796        // Its next request arrives before the handler has noticed the finished task.
1797        let (response, mut rx) = oneshot::channel();
1798        incoming_tx
1799            .send(IncomingEthRequest::GetSnap {
1800                peer_id,
1801                request: account_range_request(),
1802                response,
1803            })
1804            .await
1805            .unwrap();
1806        tokio::time::timeout(
1807            Duration::from_secs(5),
1808            std::future::poll_fn(|cx| {
1809                let _ = Pin::new(&mut handler).poll(cx);
1810                Pin::new(&mut rx).poll(cx)
1811            }),
1812        )
1813        .await
1814        .expect("incoming state range request must be answered")
1815        .unwrap()
1816        .unwrap();
1817
1818        // Both requests were served in turn, neither was turned away.
1819        assert_eq!(provider.snap_state_range_resolutions(), 2);
1820    }
1821
1822    #[tokio::test]
1823    async fn overflowing_state_range_requests_return_empty_responses() {
1824        let provider = MockEthProvider::default();
1825        let mut handler = snap_handler(provider.clone());
1826        for byte in 0..MAX_CONCURRENT_STATE_RANGE_REQUESTS as u8 {
1827            handler
1828                .state_range_requests
1829                .tasks
1830                .push((PeerId::repeat_byte(byte), tokio::spawn(futures::future::pending())));
1831        }
1832        let queued_peer = |index: usize| PeerId::repeat_byte(0x80 + index as u8);
1833        let (response, queued) = oneshot::channel();
1834        handler.on_snap_request(queued_peer(0), account_range_request(), response);
1835
1836        // The peer already holds a place in the queue.
1837        let (response, rx) = oneshot::channel();
1838        handler.on_snap_request(queued_peer(0), account_range_request(), response);
1839        assert_eq!(rx.await.unwrap(), Ok(empty_account_range()));
1840
1841        // The queue is full.
1842        let mut waiting = vec![queued];
1843        for index in 1..MAX_QUEUED_STATE_RANGE_REQUESTS {
1844            let (response, rx) = oneshot::channel();
1845            handler.on_snap_request(queued_peer(index), account_range_request(), response);
1846            waiting.push(rx);
1847        }
1848        let (response, rx) = oneshot::channel();
1849        handler.on_snap_request(PeerId::repeat_byte(0xff), account_range_request(), response);
1850        assert_eq!(rx.await.unwrap(), Ok(empty_account_range()));
1851
1852        // Queued requests stay unanswered until a slot frees.
1853        assert!(waiting
1854            .iter_mut()
1855            .all(|rx| rx.try_recv() == Err(oneshot::error::TryRecvError::Empty)));
1856        assert_eq!(provider.snap_state_range_resolutions(), 0);
1857    }
1858
1859    #[tokio::test]
1860    async fn state_range_request_from_gone_peer_is_dropped() {
1861        let mut handler = snap_handler(MockEthProvider::default());
1862        let (response, rx) = oneshot::channel();
1863        drop(rx);
1864
1865        handler.on_snap_request(PeerId::default(), account_range_request(), response);
1866
1867        assert!(handler.state_range_requests.tasks.is_empty());
1868    }
1869
1870    #[tokio::test]
1871    async fn finished_state_range_request_frees_its_peer_slot() {
1872        let mut handler = snap_handler(MockEthProvider::default());
1873        let (response, rx) = oneshot::channel();
1874
1875        handler.on_snap_request(PeerId::default(), account_range_request(), response);
1876
1877        assert_eq!(handler.state_range_requests.tasks.len(), 1);
1878        rx.await.unwrap().unwrap();
1879        tokio::time::timeout(
1880            Duration::from_secs(5),
1881            std::future::poll_fn(|cx| {
1882                let _ = Pin::new(&mut handler).poll(cx);
1883                if handler.state_range_requests.tasks.is_empty() {
1884                    Poll::Ready(())
1885                } else {
1886                    Poll::Pending
1887                }
1888            }),
1889        )
1890        .await
1891        .expect("finished state range task must free its peer slot");
1892    }
1893
1894    #[tokio::test]
1895    async fn snap_requests_return_empty_responses_on_inconsistent_provider_results() {
1896        let missing_storage_root = MockEthProvider::default();
1897        missing_storage_root
1898            .set_snap_account_range(vec![(B256::ZERO, Account::default())], RangeEnd::Exhausted);
1899
1900        let missing_account_proof = MockEthProvider::default();
1901        missing_account_proof.set_snap_account_range(Vec::new(), RangeEnd::Exhausted);
1902
1903        let missing_storage_proof = MockEthProvider::default();
1904        missing_storage_proof
1905            .push_snap_storage_range(vec![(B256::ZERO, U256::ONE)], RangeEnd::ByteLimit);
1906
1907        let storage_disappears = MockEthProvider::default();
1908        storage_disappears.push_snap_storage_range(Vec::new(), RangeEnd::Exhausted);
1909        storage_disappears.push_unavailable_snap_storage_range();
1910
1911        let account_request = || {
1912            SnapProtocolMessage::GetAccountRange(GetAccountRangeMessage {
1913                request_id: 1,
1914                root_hash: B256::ZERO,
1915                starting_hash: B256::ZERO,
1916                limit_hash: B256::repeat_byte(0xff),
1917                response_bytes: SOFT_RESPONSE_LIMIT as u64,
1918            })
1919        };
1920        let storage_request = |account_hashes| {
1921            SnapProtocolMessage::GetStorageRanges(GetStorageRangesMessage {
1922                request_id: 2,
1923                root_hash: B256::ZERO,
1924                account_hashes,
1925                starting_hash: B256::ZERO.into(),
1926                limit_hash: B256::repeat_byte(0xff).into(),
1927                response_bytes: SOFT_RESPONSE_LIMIT as u64,
1928            })
1929        };
1930        let empty_accounts = SnapResponse::AccountRange(AccountRangeMessage {
1931            request_id: 1,
1932            accounts: Vec::new(),
1933            proof: Vec::new(),
1934        });
1935        let empty_storage = SnapResponse::StorageRanges(StorageRangesMessage {
1936            request_id: 2,
1937            slots: Vec::new(),
1938            proof: Vec::new(),
1939        });
1940        let cases = [
1941            (missing_storage_root, account_request(), empty_accounts.clone()),
1942            (missing_account_proof, account_request(), empty_accounts),
1943            (missing_storage_proof, storage_request(vec![B256::ZERO]), empty_storage.clone()),
1944            (storage_disappears, storage_request(vec![B256::ZERO, B256::ZERO]), empty_storage),
1945        ];
1946
1947        for (provider, request, expected) in cases {
1948            let mut handler = snap_handler(provider.clone());
1949            let (response, rx) = oneshot::channel();
1950            handler.on_snap_request(PeerId::default(), request, response);
1951            assert_eq!(rx.await.unwrap(), Ok(expected));
1952            assert_eq!(provider.snap_state_range_resolutions(), 1);
1953        }
1954    }
1955
1956    #[tokio::test]
1957    #[allow(clippy::needless_update)]
1958    async fn snap_account_range_response_encodes_accounts_and_proof() {
1959        let provider = MockEthProvider::default();
1960        let first_hash = B256::repeat_byte(0x01);
1961        let second_hash = B256::repeat_byte(0x02);
1962        let storage_root = B256::repeat_byte(0x11);
1963        let code_hash = B256::repeat_byte(0x22);
1964        let proof = vec![Bytes::from_static(&[0xaa])];
1965        provider.set_snap_account_range(
1966            vec![
1967                (
1968                    first_hash,
1969                    Account {
1970                        nonce: 1,
1971                        balance: U256::from(2),
1972                        bytecode_hash: Some(code_hash),
1973                        ..Default::default()
1974                    },
1975                ),
1976                (second_hash, Account { nonce: 3, balance: U256::from(4), ..Default::default() }),
1977            ],
1978            // A hash-limit stop (not an exhausted trie) so a boundary proof is still expected,
1979            // matching the mocked `proof` below.
1980            RangeEnd::HashLimit,
1981        );
1982        provider.set_snap_storage_root(first_hash, storage_root);
1983        provider.set_snap_storage_root(second_hash, EMPTY_ROOT_HASH);
1984        provider.set_snap_account_proof(Some(proof.clone()));
1985
1986        let mut full_body = vec![0xf8, 0x44, 0x01, 0x02, 0xa0];
1987        full_body.extend_from_slice(storage_root.as_slice());
1988        full_body.push(0xa0);
1989        full_body.extend_from_slice(code_hash.as_slice());
1990        let empty_body = Bytes::from_static(&[0xc4, 0x03, 0x04, 0x80, 0x80]);
1991
1992        let mut handler = snap_handler(provider.clone());
1993        let (response, rx) = oneshot::channel();
1994        handler.on_snap_request(
1995            PeerId::default(),
1996            SnapProtocolMessage::GetAccountRange(GetAccountRangeMessage {
1997                request_id: 1,
1998                root_hash: B256::ZERO,
1999                starting_hash: B256::ZERO,
2000                limit_hash: B256::repeat_byte(0xff),
2001                response_bytes: SOFT_RESPONSE_LIMIT as u64,
2002            }),
2003            response,
2004        );
2005
2006        assert_eq!(
2007            rx.await.unwrap(),
2008            Ok(SnapResponse::AccountRange(AccountRangeMessage {
2009                request_id: 1,
2010                accounts: vec![
2011                    AccountData {
2012                        hash: first_hash,
2013                        body: alloy_rlp::decode_exact(&full_body).unwrap()
2014                    },
2015                    AccountData {
2016                        hash: second_hash,
2017                        body: alloy_rlp::decode_exact(&empty_body).unwrap()
2018                    },
2019                ],
2020                proof,
2021            }))
2022        );
2023        assert_eq!(provider.snap_state_range_resolutions(), 1);
2024    }
2025
2026    #[tokio::test]
2027    async fn snap_account_range_response_skips_proof_for_exhausted_zero_origin_range() {
2028        let provider = MockEthProvider::default();
2029        let hash = B256::repeat_byte(0x01);
2030        provider.set_snap_account_range(
2031            vec![(hash, Account { nonce: 1, balance: U256::from(2), ..Default::default() })],
2032            RangeEnd::Exhausted,
2033        );
2034        provider.set_snap_storage_root(hash, EMPTY_ROOT_HASH);
2035        // A non-empty mocked proof: if the skip-proof optimization regressed to "never skip",
2036        // this wrongly-included proof would surface in the response and fail the assertion below.
2037        provider.set_snap_account_proof(Some(vec![Bytes::from_static(&[0xaa])]));
2038
2039        let mut handler = snap_handler(provider.clone());
2040        let (response, rx) = oneshot::channel();
2041        handler.on_snap_request(
2042            PeerId::default(),
2043            SnapProtocolMessage::GetAccountRange(GetAccountRangeMessage {
2044                request_id: 1,
2045                root_hash: B256::ZERO,
2046                starting_hash: B256::ZERO,
2047                limit_hash: B256::repeat_byte(0xff),
2048                response_bytes: SOFT_RESPONSE_LIMIT as u64,
2049            }),
2050            response,
2051        );
2052
2053        let Ok(SnapResponse::AccountRange(AccountRangeMessage { accounts, proof, .. })) =
2054            rx.await.unwrap()
2055        else {
2056            panic!("expected an account range response");
2057        };
2058        assert_eq!(accounts.len(), 1);
2059        assert!(proof.is_empty(), "a zero-origin, exhausted range must not carry a boundary proof");
2060    }
2061
2062    #[tokio::test]
2063    async fn snap_storage_range_response_encodes_values_and_proof() {
2064        let provider = MockEthProvider::default();
2065        let first_hash = B256::repeat_byte(0x01);
2066        let second_hash = B256::repeat_byte(0x02);
2067        let origin = B256::repeat_byte(0x10);
2068        let proof = vec![Bytes::from_static(&[0xbb])];
2069        provider.push_snap_storage_range(
2070            vec![(first_hash, U256::from(0x0102)), (second_hash, U256::from(0xff))],
2071            RangeEnd::Exhausted,
2072        );
2073        provider.set_snap_storage_proof(Some(proof.clone()));
2074
2075        let mut handler = snap_handler(provider.clone());
2076        let (response, rx) = oneshot::channel();
2077        handler.on_snap_request(
2078            PeerId::default(),
2079            SnapProtocolMessage::GetStorageRanges(GetStorageRangesMessage {
2080                request_id: 2,
2081                root_hash: B256::ZERO,
2082                account_hashes: vec![B256::repeat_byte(0x03)],
2083                starting_hash: origin.into(),
2084                limit_hash: B256::repeat_byte(0xff).into(),
2085                response_bytes: SOFT_RESPONSE_LIMIT as u64,
2086            }),
2087            response,
2088        );
2089
2090        assert_eq!(
2091            rx.await.unwrap(),
2092            Ok(SnapResponse::StorageRanges(StorageRangesMessage {
2093                request_id: 2,
2094                slots: vec![vec![
2095                    StorageData { hash: first_hash, data: Bytes::from_static(&[0x82, 0x01, 0x02]) },
2096                    StorageData { hash: second_hash, data: Bytes::from_static(&[0x81, 0xff]) },
2097                ]],
2098                proof,
2099            }))
2100        );
2101        assert_eq!(provider.snap_storage_range_requests()[0].1, origin);
2102        assert_eq!(provider.snap_state_range_resolutions(), 1);
2103    }
2104
2105    #[tokio::test]
2106    async fn snap_storage_ranges_only_bound_the_first_account() {
2107        let provider = MockEthProvider::default();
2108        provider.push_snap_storage_range(Vec::new(), RangeEnd::Exhausted);
2109        provider.push_snap_storage_range(Vec::new(), RangeEnd::Exhausted);
2110        let first_account = B256::repeat_byte(0x01);
2111        let second_account = B256::repeat_byte(0x02);
2112        let origin = B256::ZERO;
2113        let limit = B256::repeat_byte(0x22);
2114
2115        let mut handler = snap_handler(provider.clone());
2116        let (response, rx) = oneshot::channel();
2117        handler.on_snap_request(
2118            PeerId::default(),
2119            SnapProtocolMessage::GetStorageRanges(GetStorageRangesMessage {
2120                request_id: 3,
2121                root_hash: B256::ZERO,
2122                account_hashes: vec![first_account, second_account],
2123                starting_hash: origin.into(),
2124                limit_hash: limit.into(),
2125                response_bytes: 1_000,
2126            }),
2127            response,
2128        );
2129
2130        assert_eq!(
2131            rx.await.unwrap(),
2132            Ok(SnapResponse::StorageRanges(StorageRangesMessage {
2133                request_id: 3,
2134                slots: vec![Vec::new(), Vec::new()],
2135                proof: Vec::new(),
2136            }))
2137        );
2138        assert_eq!(
2139            provider.snap_storage_range_requests(),
2140            vec![
2141                (first_account, origin, limit, 1_000),
2142                (second_account, B256::ZERO, B256::repeat_byte(0xff), 1_000),
2143            ]
2144        );
2145        assert_eq!(provider.snap_state_range_resolutions(), 1);
2146    }
2147
2148    #[tokio::test]
2149    async fn snap_byte_codes_response_preserves_found_code_order() {
2150        let provider = MockEthProvider::default();
2151        let code = Bytes::from_static(&[0x60, 0x00]);
2152        let code_hash = keccak256(&code);
2153        let later_code = Bytes::from_static(&[0x60, 0x01]);
2154        let later_code_hash = keccak256(&later_code);
2155        provider.add_account(
2156            Address::repeat_byte(0x01),
2157            ExtendedAccount::new(1, U256::ZERO).with_bytecode(code.clone()),
2158        );
2159        provider.add_account(
2160            Address::repeat_byte(0x02),
2161            ExtendedAccount::new(1, U256::ZERO).with_bytecode(later_code),
2162        );
2163
2164        let mut handler = snap_handler(provider);
2165        let (response, rx) = oneshot::channel();
2166        handler.on_snap_request(
2167            PeerId::default(),
2168            SnapProtocolMessage::GetByteCodes(reth_eth_wire::snap::GetByteCodesMessage {
2169                request_id: 3,
2170                hashes: vec![KECCAK_EMPTY, B256::repeat_byte(0xff), code_hash, later_code_hash],
2171                response_bytes: 1,
2172            }),
2173            response,
2174        );
2175
2176        assert_eq!(
2177            rx.await.unwrap(),
2178            Ok(SnapResponse::ByteCodes(ByteCodesMessage {
2179                request_id: 3,
2180                codes: vec![Bytes::new(), code],
2181            }))
2182        );
2183    }
2184
2185    #[tokio::test]
2186    async fn snap_storage_ranges_limit_account_lookups() {
2187        let provider = MockEthProvider::default();
2188        for _ in 0..=MAX_STORAGE_RANGE_ACCOUNTS_SERVE {
2189            provider.push_snap_storage_range(Vec::new(), RangeEnd::Exhausted);
2190        }
2191        let mut handler = snap_handler(provider.clone());
2192        let (response, rx) = oneshot::channel();
2193        handler.on_snap_request(
2194            PeerId::default(),
2195            SnapProtocolMessage::GetStorageRanges(GetStorageRangesMessage {
2196                request_id: 4,
2197                root_hash: B256::ZERO,
2198                account_hashes: vec![B256::ZERO; MAX_STORAGE_RANGE_ACCOUNTS_SERVE + 1],
2199                starting_hash: B256::ZERO.into(),
2200                limit_hash: B256::repeat_byte(0xff).into(),
2201                response_bytes: SOFT_RESPONSE_LIMIT as u64,
2202            }),
2203            response,
2204        );
2205
2206        assert_eq!(
2207            rx.await.unwrap(),
2208            Ok(SnapResponse::StorageRanges(StorageRangesMessage {
2209                request_id: 4,
2210                slots: vec![Vec::new(); MAX_STORAGE_RANGE_ACCOUNTS_SERVE],
2211                proof: Vec::new(),
2212            }))
2213        );
2214        assert_eq!(provider.snap_storage_ranges_remaining(), 1);
2215        assert_eq!(provider.snap_state_range_resolutions(), 1);
2216    }
2217
2218    #[tokio::test]
2219    async fn snap_storage_range_proves_finite_limit_from_zero_origin() {
2220        let provider = MockEthProvider::default();
2221        let hash = B256::repeat_byte(0x01);
2222        let proof = vec![Bytes::from_static(&[0xcc])];
2223        // More entries exist beyond `limit_hash`, so the cursor stopped at the hash limit
2224        // rather than exhausting the trie -- a proof is required even though origin is zero.
2225        provider.push_snap_storage_range(vec![(hash, U256::ONE)], RangeEnd::HashLimit);
2226        provider.set_snap_storage_proof(Some(proof.clone()));
2227
2228        let mut handler = snap_handler(provider.clone());
2229        let (response, rx) = oneshot::channel();
2230        handler.on_snap_request(
2231            PeerId::default(),
2232            SnapProtocolMessage::GetStorageRanges(GetStorageRangesMessage {
2233                request_id: 5,
2234                root_hash: B256::ZERO,
2235                account_hashes: vec![B256::repeat_byte(0x03)],
2236                starting_hash: B256::ZERO.into(),
2237                limit_hash: B256::repeat_byte(0x20).into(),
2238                response_bytes: SOFT_RESPONSE_LIMIT as u64,
2239            }),
2240            response,
2241        );
2242
2243        assert_eq!(
2244            rx.await.unwrap(),
2245            Ok(SnapResponse::StorageRanges(StorageRangesMessage {
2246                request_id: 5,
2247                slots: vec![vec![StorageData { hash, data: Bytes::from_static(&[0x01]) }]],
2248                proof,
2249            }))
2250        );
2251    }
2252
2253    #[tokio::test]
2254    async fn snap_storage_ranges_are_entirely_empty_when_an_account_is_missing() {
2255        let provider = MockEthProvider::default();
2256        provider.push_missing_snap_storage_account();
2257        provider.push_snap_storage_range(
2258            vec![(B256::repeat_byte(0x01), U256::ONE)],
2259            RangeEnd::Exhausted,
2260        );
2261        let missing_account = B256::repeat_byte(0x01);
2262        let valid_account = B256::repeat_byte(0x02);
2263
2264        let mut handler = snap_handler(provider.clone());
2265        let (response, rx) = oneshot::channel();
2266        handler.on_snap_request(
2267            PeerId::default(),
2268            SnapProtocolMessage::GetStorageRanges(GetStorageRangesMessage {
2269                request_id: 6,
2270                root_hash: B256::ZERO,
2271                account_hashes: vec![missing_account, valid_account],
2272                starting_hash: B256::ZERO.into(),
2273                limit_hash: B256::repeat_byte(0xff).into(),
2274                response_bytes: SOFT_RESPONSE_LIMIT as u64,
2275            }),
2276            response,
2277        );
2278
2279        assert_eq!(
2280            rx.await.unwrap(),
2281            Ok(SnapResponse::StorageRanges(StorageRangesMessage {
2282                request_id: 6,
2283                slots: Vec::new(),
2284                proof: Vec::new(),
2285            }))
2286        );
2287        // The valid account's queued range is never consumed: the response bails out at the
2288        // first missing account instead of skipping it and shifting later positions.
2289        assert_eq!(provider.snap_storage_ranges_remaining(), 1);
2290    }
2291
2292    /// Creates a receipt whose single log carries `data_len` bytes of data.
2293    fn receipt_with_data(data_len: usize) -> Receipt {
2294        Receipt {
2295            tx_type: TxType::Legacy,
2296            success: true,
2297            cumulative_gas_used: 21_000,
2298            logs: vec![Log {
2299                address: Address::ZERO,
2300                data: LogData::new_unchecked(Vec::new(), vec![0u8; data_len].into()),
2301            }],
2302        }
2303    }
2304
2305    /// Stores the receipts as block `number` and returns the block hash.
2306    fn insert_receipts_block(
2307        provider: &MockEthProvider,
2308        number: u64,
2309        receipts: Vec<Receipt>,
2310    ) -> B256 {
2311        let hash = B256::with_last_byte(number as u8);
2312        provider.add_header(hash, Header { number, ..Default::default() });
2313        provider.add_receipts(number, receipts);
2314        hash
2315    }
2316
2317    /// Sends a [`GetReceipts70`] request to the handler and returns the response.
2318    async fn get_receipts70(
2319        provider: MockEthProvider,
2320        first_block_receipt_index: u64,
2321        block_hashes: Vec<B256>,
2322    ) -> Receipts70 {
2323        let handler = snap_handler(provider);
2324        let (response, rx) = oneshot::channel();
2325        handler.on_receipts70_request(
2326            PeerId::default(),
2327            GetReceipts70 { first_block_receipt_index, block_hashes },
2328            response,
2329        );
2330        rx.await.unwrap().unwrap()
2331    }
2332
2333    #[tokio::test]
2334    async fn receipts70_serves_block_over_soft_limit_complete() {
2335        let provider = MockEthProvider::default();
2336        // The block crosses the soft limit but fits within the message, so it is served whole.
2337        let small = receipt_with_data(16);
2338        let large = receipt_with_data(SOFT_RESPONSE_LIMIT);
2339        let hash = insert_receipts_block(&provider, 1, vec![small.clone(), large.clone()]);
2340
2341        let resp = get_receipts70(provider, 0, vec![hash]).await;
2342
2343        assert_eq!(
2344            resp,
2345            Receipts70 { last_block_incomplete: false, receipts: vec![vec![small, large]] }
2346        );
2347    }
2348
2349    #[tokio::test]
2350    async fn receipts70_serves_last_block_over_soft_limit_complete() {
2351        let provider = MockEthProvider::default();
2352        let first = vec![receipt_with_data(1024); 160];
2353        let first_hash = insert_receipts_block(&provider, 1, first.clone());
2354        // The second block crosses the soft limit but fits within the message, so it is served
2355        // whole after the first block.
2356        let second = vec![receipt_with_data(SOFT_RESPONSE_LIMIT)];
2357        let second_hash = insert_receipts_block(&provider, 2, second.clone());
2358
2359        let resp = get_receipts70(provider, 0, vec![first_hash, second_hash]).await;
2360
2361        assert_eq!(
2362            resp,
2363            Receipts70 { last_block_incomplete: false, receipts: vec![first, second] }
2364        );
2365    }
2366
2367    #[tokio::test]
2368    async fn receipts70_omits_block_whose_first_receipt_overflows_the_message() {
2369        let provider = MockEthProvider::default();
2370        let first = vec![receipt_with_data(SOFT_RESPONSE_LIMIT - 1024)];
2371        let first_hash = insert_receipts_block(&provider, 1, first.clone());
2372        // The first receipt of the second block fits in the message on its own but not in the
2373        // budget left after the first block, so the response ends after the first block.
2374        let second_hash =
2375            insert_receipts_block(&provider, 2, vec![receipt_with_data(9 * 1024 * 1024)]);
2376
2377        let resp = get_receipts70(provider, 0, vec![first_hash, second_hash]).await;
2378
2379        assert_eq!(resp, Receipts70 { last_block_incomplete: false, receipts: vec![first] });
2380    }
2381
2382    #[tokio::test]
2383    async fn receipts70_serves_partial_block_over_message_limit() {
2384        let provider = MockEthProvider::default();
2385        // Together the receipts overflow the 10 MiB message, so the block is split across
2386        // responses and flagged incomplete.
2387        let receipts = vec![receipt_with_data(1024 * 1024); 12];
2388        let hash = insert_receipts_block(&provider, 1, receipts.clone());
2389
2390        let resp = get_receipts70(provider, 0, vec![hash]).await;
2391
2392        assert!(resp.last_block_incomplete);
2393        assert_eq!(resp.receipts.len(), 1);
2394        let partial = &resp.receipts[0];
2395        assert!(!partial.is_empty() && partial.len() < receipts.len());
2396        assert_eq!(partial.as_slice(), &receipts[..partial.len()]);
2397
2398        let encoded = encode_receipts70_response(resp);
2399        // The split happens at the message limit, not the soft limit.
2400        assert!(encoded.len() > SOFT_RESPONSE_LIMIT);
2401        assert!(encoded.len() <= MAX_MESSAGE_SIZE);
2402    }
2403
2404    #[test_case(0, 0; "first receipt at hard limit")]
2405    #[test_case(1, 0; "continuation receipt at hard limit")]
2406    #[test_case(0, 1; "first receipt framing exceeds hard limit")]
2407    #[test_case(1, 1; "continuation receipt framing exceeds hard limit")]
2408    #[tokio::test]
2409    async fn receipts70_enforces_framed_response_limit(first_receipt_index: u64, excess: usize) {
2410        // Measure the actual wire encoding with the largest request ID. At these sizes, changing
2411        // the log data length does not change the width of any RLP length prefix.
2412        let data_len = MAX_MESSAGE_SIZE - 1024;
2413        let encoded = encode_receipts70_response(Receipts70 {
2414            last_block_incomplete: false,
2415            receipts: vec![vec![receipt_with_data(data_len)]],
2416        });
2417        let receipt = receipt_with_data(data_len + MAX_MESSAGE_SIZE - encoded.len() + excess);
2418        assert!(receipt.length() < MAX_MESSAGE_SIZE);
2419        let expected =
2420            Receipts70 { last_block_incomplete: false, receipts: vec![vec![receipt.clone()]] };
2421        assert_eq!(encode_receipts70_response(expected.clone()).len(), MAX_MESSAGE_SIZE + excess);
2422
2423        let provider = MockEthProvider::default();
2424        let mut receipts = vec![receipt_with_data(16); first_receipt_index as usize];
2425        receipts.push(receipt);
2426        let hash = insert_receipts_block(&provider, 1, receipts);
2427
2428        let resp = get_receipts70(provider, first_receipt_index, vec![hash]).await;
2429
2430        if excess == 0 {
2431            assert_eq!(resp, expected);
2432        } else {
2433            assert_eq!(resp, Receipts70 { last_block_incomplete: false, receipts: Vec::new() });
2434        }
2435        let encoded = encode_receipts70_response(resp);
2436        assert!(encoded.len() <= MAX_MESSAGE_SIZE);
2437        // The requesting side only decodes responses to requests it sent.
2438        let mut requester = EthStreamInner::<EthNetworkPrimitives>::new(EthVersion::Eth70);
2439        requester
2440            .encode_message(EthMessage::GetReceipts70(RequestPair {
2441                request_id: u64::MAX,
2442                message: GetReceipts70 {
2443                    first_block_receipt_index: first_receipt_index,
2444                    block_hashes: vec![hash],
2445                },
2446            }))
2447            .unwrap();
2448        requester.decode_message(encoded.as_ref().into()).unwrap();
2449    }
2450
2451    /// Encodes a receipts response with the largest possible request ID.
2452    fn encode_receipts70_response(response: Receipts70) -> Bytes {
2453        EthStreamInner::<EthNetworkPrimitives>::new(EthVersion::Eth70)
2454            .encode_message(EthMessage::Receipts70(RequestPair {
2455                request_id: u64::MAX,
2456                message: response,
2457            }))
2458            .unwrap()
2459            .into()
2460    }
2461}