Skip to main content

reth_engine_tree/
download.rs

1//! Handler that can download blocks on demand (e.g. from the network).
2
3use crate::{engine::DownloadRequest, metrics::BlockDownloaderMetrics};
4use alloy_consensus::BlockHeader;
5use alloy_eips::BlockNumHash;
6use alloy_primitives::{map::B256Set, B256};
7use futures::FutureExt;
8use reth_consensus::Consensus;
9use reth_network_p2p::{
10    full_block::{
11        FetchFullBlockFuture, FetchFullBlockRangeFuture, FetchFullBlockRangeWithBalFuture,
12        FetchFullBlockWithBalFuture, FullBlockClient, SealedBlockWithAccessList,
13        StartNumberMismatch,
14    },
15    BlockAccessListsClient, BlockClient,
16};
17use reth_primitives_traits::{Block, SealedBlockWith};
18use std::{
19    cmp::{Ordering, Reverse},
20    collections::{binary_heap::PeekMut, BinaryHeap, VecDeque},
21    fmt::Debug,
22    sync::Arc,
23    task::{Context, Poll},
24};
25use tracing::trace;
26
27// Blocks of a finished range download, or the header that proved its start number wrong.
28type BlockRangeResult<B> =
29    Result<Vec<SealedBlockWithAccessList<B>>, StartNumberMismatch<<B as Block>::Header>>;
30
31/// A trait that can download blocks on demand.
32pub trait BlockDownloader: Send + Sync {
33    /// Type of the block being downloaded.
34    type Block: Block;
35
36    /// Handle an action.
37    fn on_action(&mut self, action: DownloadAction);
38
39    /// Advance in progress requests if any
40    fn poll(&mut self, cx: &mut Context<'_>) -> Poll<DownloadOutcome<Self::Block>>;
41}
42
43/// Actions that can be performed by the block downloader.
44#[derive(Debug)]
45pub enum DownloadAction {
46    /// Stop downloading blocks.
47    Clear,
48    /// Download given blocks
49    Download(DownloadRequest),
50}
51
52/// Outcome of downloaded blocks.
53#[derive(Debug)]
54pub enum DownloadOutcome<B: Block> {
55    /// Downloaded blocks with optional block access list data.
56    Blocks(Vec<SealedBlockWithAccessList<B>>),
57    /// A range download ended because its start header is not at the requested block number.
58    StartNumberMismatch(StartNumberMismatch<B::Header>),
59    /// New download started.
60    NewDownloadStarted {
61        /// How many blocks are pending in this download.
62        remaining_blocks: u64,
63        /// The hash of the highest block of this download.
64        target: B256,
65    },
66}
67
68/// Basic [`BlockDownloader`].
69#[expect(missing_debug_implementations)]
70pub struct BasicBlockDownloader<Client, B: Block>
71where
72    Client: BlockClient + BlockAccessListsClient + 'static,
73{
74    /// A downloader that can download full blocks from the network.
75    full_block_client: FullBlockClient<Client>,
76    /// In-flight full block requests in progress.
77    inflight_full_block_requests: Vec<FullBlockDownload<Client>>,
78    /// In-flight full block _range_ requests in progress.
79    inflight_block_range_requests: Vec<FullBlockRangeDownload<Client>>,
80    /// Buffered blocks from downloads - this is a min-heap of blocks, using the block number for
81    /// ordering. This means the blocks will be popped from the heap with ascending block numbers.
82    set_buffered_blocks: BinaryHeap<Reverse<OrderedDownloadedBlock<B>>>,
83    /// Engine download metrics.
84    metrics: BlockDownloaderMetrics,
85    /// Pending events to be emitted.
86    pending_events: VecDeque<DownloadOutcome<B>>,
87}
88
89impl<Client, B> BasicBlockDownloader<Client, B>
90where
91    Client: BlockClient<Block = B> + BlockAccessListsClient + 'static,
92    B: Block,
93{
94    /// Create a new instance
95    pub fn new(client: Client, consensus: Arc<dyn Consensus<B>>) -> Self {
96        Self {
97            full_block_client: FullBlockClient::new(client, consensus),
98            inflight_full_block_requests: Vec::new(),
99            inflight_block_range_requests: Vec::new(),
100            set_buffered_blocks: BinaryHeap::new(),
101            metrics: BlockDownloaderMetrics::default(),
102            pending_events: Default::default(),
103        }
104    }
105
106    /// Clears the stored inflight requests.
107    fn clear(&mut self) {
108        self.inflight_full_block_requests.clear();
109        self.inflight_block_range_requests.clear();
110        self.set_buffered_blocks.clear();
111        self.update_block_download_metrics();
112    }
113
114    /// Processes a download request.
115    fn download(&mut self, request: DownloadRequest) {
116        match request {
117            DownloadRequest::BlockSet { hashes, access_lists } => {
118                self.download_block_set(hashes, access_lists)
119            }
120            DownloadRequest::BlockRange { start, count, access_lists } => {
121                self.download_block_range(start, count, access_lists)
122            }
123        }
124    }
125
126    /// Processes a block set download request.
127    fn download_block_set(&mut self, hashes: B256Set, access_lists: bool) {
128        for hash in hashes {
129            self.download_full_block(hash, access_lists);
130        }
131    }
132
133    /// Processes a block range download request.
134    fn download_block_range(&mut self, start: BlockNumHash, count: u64, access_lists: bool) {
135        if count == 1 {
136            // A single block is fetched by hash alone, so its number is left to the tree, which
137            // validates the buffered child against the downloaded block.
138            self.download_full_block(start.hash, access_lists);
139        } else {
140            if self.inflight_block_range_requests.iter().any(|request| {
141                request.start_hash() == start.hash &&
142                    request.start_number() == start.number &&
143                    request.count() == count &&
144                    request.access_lists() == access_lists
145            }) {
146                return
147            }
148
149            trace!(
150                target: "engine::download",
151                ?start,
152                ?count,
153                access_lists,
154                "start downloading full block range."
155            );
156
157            let request = if access_lists {
158                FullBlockRangeDownload::WithAccessLists(
159                    self.full_block_client
160                        .get_full_block_range_with_optional_access_lists(start, count),
161                )
162            } else {
163                FullBlockRangeDownload::Blocks(
164                    self.full_block_client.get_full_block_range(start, count),
165                )
166            };
167            self.push_pending_event(DownloadOutcome::NewDownloadStarted {
168                remaining_blocks: request.count(),
169                target: request.start_hash(),
170            });
171            self.inflight_block_range_requests.push(request);
172
173            self.update_block_download_metrics();
174        }
175    }
176
177    /// Starts requesting a full block from the network.
178    ///
179    /// Returns `true` if the request was started, `false` if there's already a request for the
180    /// given hash.
181    fn download_full_block(&mut self, hash: B256, access_lists: bool) -> bool {
182        if self.is_inflight_request(hash) {
183            return false
184        }
185        self.push_pending_event(DownloadOutcome::NewDownloadStarted {
186            remaining_blocks: 1,
187            target: hash,
188        });
189
190        trace!(
191            target: "engine::download",
192            ?hash,
193            access_lists,
194            "Start downloading full block"
195        );
196
197        let request = if access_lists {
198            FullBlockDownload::WithAccessList(
199                self.full_block_client.get_full_block_with_access_lists(hash),
200            )
201        } else {
202            FullBlockDownload::Block(self.full_block_client.get_full_block(hash))
203        };
204        self.inflight_full_block_requests.push(request);
205
206        self.update_block_download_metrics();
207
208        true
209    }
210
211    /// Returns true if there's already a request for the given hash.
212    fn is_inflight_request(&self, hash: B256) -> bool {
213        self.inflight_full_block_requests.iter().any(|req| *req.hash() == hash)
214    }
215
216    /// Sets the metrics for the active downloads
217    fn update_block_download_metrics(&self) {
218        let blocks = self.inflight_full_block_requests.len() +
219            self.inflight_block_range_requests.iter().map(|r| r.count() as usize).sum::<usize>();
220        self.metrics.active_block_downloads.set(blocks as f64);
221    }
222
223    /// Adds a pending event to the FIFO queue.
224    fn push_pending_event(&mut self, pending_event: DownloadOutcome<B>) {
225        self.pending_events.push_back(pending_event);
226    }
227
228    /// Removes a pending event from the FIFO queue.
229    fn pop_pending_event(&mut self) -> Option<DownloadOutcome<B>> {
230        self.pending_events.pop_front()
231    }
232}
233
234impl<Client, B> BlockDownloader for BasicBlockDownloader<Client, B>
235where
236    Client: BlockClient<Block = B> + BlockAccessListsClient,
237    B: Block,
238{
239    type Block = B;
240
241    /// Handles incoming download actions.
242    fn on_action(&mut self, action: DownloadAction) {
243        match action {
244            DownloadAction::Clear => self.clear(),
245            DownloadAction::Download(request) => self.download(request),
246        }
247    }
248
249    /// Advances the download process.
250    fn poll(&mut self, cx: &mut Context<'_>) -> Poll<DownloadOutcome<B>> {
251        if let Some(pending_event) = self.pop_pending_event() {
252            return Poll::Ready(pending_event);
253        }
254
255        // advance all full block requests
256        for idx in (0..self.inflight_full_block_requests.len()).rev() {
257            let mut request = self.inflight_full_block_requests.swap_remove(idx);
258            if let Poll::Ready(block) = request.poll(cx) {
259                trace!(target: "engine::download", block=?block.num_hash(), "Received single full block, buffering");
260                self.set_buffered_blocks.push(Reverse(block.into()));
261            } else {
262                // still pending
263                self.inflight_full_block_requests.push(request);
264            }
265        }
266
267        // advance all full block range requests
268        for idx in (0..self.inflight_block_range_requests.len()).rev() {
269            let mut request = self.inflight_block_range_requests.swap_remove(idx);
270            if let Poll::Ready(result) = request.poll(cx) {
271                match result {
272                    Ok(blocks) => {
273                        trace!(target: "engine::download", len=?blocks.len(), first=?blocks.first().map(|b| b.num_hash()), last=?blocks.last().map(|b| b.num_hash()), "Received full block range, buffering");
274                        self.set_buffered_blocks
275                            .extend(blocks.into_iter().map(OrderedDownloadedBlock).map(Reverse));
276                    }
277                    Err(mismatch) => {
278                        self.push_pending_event(DownloadOutcome::StartNumberMismatch(mismatch))
279                    }
280                }
281            } else {
282                // still pending
283                self.inflight_block_range_requests.push(request);
284            }
285        }
286
287        self.update_block_download_metrics();
288
289        // Buffered blocks stay for the next poll, which the caller makes after any outcome.
290        if let Some(pending_event) = self.pop_pending_event() {
291            return Poll::Ready(pending_event);
292        }
293
294        if self.set_buffered_blocks.is_empty() {
295            return Poll::Pending;
296        }
297
298        // drain all unique element of the block buffer if there are any
299        let mut downloaded_blocks = Vec::with_capacity(self.set_buffered_blocks.len());
300        while let Some(block) = self.set_buffered_blocks.pop() {
301            let mut block = block.0 .0;
302            // peek ahead and pop duplicates, keeping the copy that includes access list data
303            while let Some(peek) = self.set_buffered_blocks.peek_mut() {
304                if peek.0 .0.hash() == block.hash() {
305                    let duplicate = PeekMut::pop(peek).0 .0;
306                    if block.data().is_none() && duplicate.data().is_some() {
307                        block = duplicate;
308                    }
309                } else {
310                    break
311                }
312            }
313            downloaded_blocks.push(block);
314        }
315        Poll::Ready(DownloadOutcome::Blocks(downloaded_blocks))
316    }
317}
318
319/// A wrapper type around [`SealedBlockWithAccessList`] that implements the [Ord]
320/// trait by block number.
321#[derive(Debug, Clone, PartialEq, Eq)]
322struct OrderedDownloadedBlock<B: Block>(SealedBlockWithAccessList<B>);
323
324impl<B: Block> PartialOrd for OrderedDownloadedBlock<B> {
325    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
326        Some(self.cmp(other))
327    }
328}
329
330impl<B: Block> Ord for OrderedDownloadedBlock<B> {
331    fn cmp(&self, other: &Self) -> Ordering {
332        self.0.number().cmp(&other.0.number())
333    }
334}
335
336impl<B: Block> From<SealedBlockWithAccessList<B>> for OrderedDownloadedBlock<B> {
337    fn from(block: SealedBlockWithAccessList<B>) -> Self {
338        Self(block)
339    }
340}
341
342/// An in-flight full block request that optionally also fetches the block's access list.
343enum FullBlockDownload<Client>
344where
345    Client: BlockClient + BlockAccessListsClient,
346{
347    /// Fetches the block only.
348    Block(FetchFullBlockFuture<Client>),
349    /// Fetches the block and attempts to fetch its access list.
350    WithAccessList(FetchFullBlockWithBalFuture<Client>),
351}
352
353impl<Client> FullBlockDownload<Client>
354where
355    Client: BlockClient + BlockAccessListsClient + 'static,
356{
357    /// Returns the hash of the block being requested.
358    const fn hash(&self) -> &B256 {
359        match self {
360            Self::Block(req) => req.hash(),
361            Self::WithAccessList(req) => req.hash(),
362        }
363    }
364
365    /// Advances the download.
366    fn poll(&mut self, cx: &mut Context<'_>) -> Poll<SealedBlockWithAccessList<Client::Block>> {
367        match self {
368            Self::Block(req) => req.poll_unpin(cx).map(SealedBlockWith::from_block),
369            Self::WithAccessList(req) => req.poll_unpin(cx),
370        }
371    }
372}
373
374/// An in-flight full block range request that optionally also fetches the blocks' access lists.
375enum FullBlockRangeDownload<Client>
376where
377    Client: BlockClient + BlockAccessListsClient,
378{
379    /// Fetches the block range only.
380    Blocks(FetchFullBlockRangeFuture<Client>),
381    /// Fetches the block range and attempts to fetch the blocks' access lists.
382    WithAccessLists(FetchFullBlockRangeWithBalFuture<Client>),
383}
384
385impl<Client> FullBlockRangeDownload<Client>
386where
387    Client: BlockClient + BlockAccessListsClient + 'static,
388{
389    /// Returns the block hash the requested range starts at (inclusive).
390    const fn start_hash(&self) -> B256 {
391        match self {
392            Self::Blocks(req) => req.start_hash(),
393            Self::WithAccessLists(req) => req.start_hash(),
394        }
395    }
396
397    // Block number the start header must have.
398    const fn start_number(&self) -> u64 {
399        match self {
400            Self::Blocks(req) => req.start_number(),
401            Self::WithAccessLists(req) => req.start_number(),
402        }
403    }
404
405    /// Returns the number of requested blocks.
406    const fn count(&self) -> u64 {
407        match self {
408            Self::Blocks(req) => req.count(),
409            Self::WithAccessLists(req) => req.count(),
410        }
411    }
412
413    /// Returns whether the request also fetches block access lists.
414    const fn access_lists(&self) -> bool {
415        matches!(self, Self::WithAccessLists(_))
416    }
417
418    /// Advances the download.
419    fn poll(&mut self, cx: &mut Context<'_>) -> Poll<BlockRangeResult<Client::Block>> {
420        match self {
421            Self::Blocks(req) => req
422                .poll_unpin(cx)
423                .map_ok(|blocks| blocks.into_iter().map(SealedBlockWith::from_block).collect()),
424            Self::WithAccessLists(req) => req.poll_unpin(cx),
425        }
426    }
427}
428
429/// A [`BlockDownloader`] that does nothing.
430#[derive(Debug, Clone, Default)]
431#[non_exhaustive]
432pub struct NoopBlockDownloader<B>(core::marker::PhantomData<B>);
433
434impl<B: Block> BlockDownloader for NoopBlockDownloader<B> {
435    type Block = B;
436
437    fn on_action(&mut self, _event: DownloadAction) {}
438
439    fn poll(&mut self, _cx: &mut Context<'_>) -> Poll<DownloadOutcome<B>> {
440        Poll::Pending
441    }
442}
443
444#[cfg(test)]
445mod tests {
446    use super::*;
447    use crate::test_utils::insert_headers_into_client;
448    use alloy_consensus::Header;
449    use alloy_eips::eip1559::ETHEREUM_BLOCK_GAS_LIMIT_30M;
450    use assert_matches::assert_matches;
451    use reth_chainspec::{ChainSpecBuilder, MAINNET};
452    use reth_ethereum_consensus::EthBeaconConsensus;
453    use reth_network_p2p::test_utils::TestFullBlockClient;
454    use reth_primitives_traits::SealedHeader;
455    use std::{future::poll_fn, sync::Arc};
456
457    struct TestHarness {
458        block_downloader:
459            BasicBlockDownloader<TestFullBlockClient, reth_ethereum_primitives::Block>,
460        client: TestFullBlockClient,
461    }
462
463    impl TestHarness {
464        fn new(total_blocks: usize) -> Self {
465            let chain_spec = Arc::new(
466                ChainSpecBuilder::default()
467                    .chain(MAINNET.chain)
468                    .genesis(MAINNET.genesis.clone())
469                    .paris_activated()
470                    .build(),
471            );
472
473            let client = TestFullBlockClient::default();
474            let header = Header {
475                base_fee_per_gas: Some(7),
476                gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M,
477                ..Default::default()
478            };
479            let header = SealedHeader::seal_slow(header);
480
481            insert_headers_into_client(&client, header, 0..total_blocks);
482            let consensus = Arc::new(EthBeaconConsensus::new(chain_spec));
483
484            let block_downloader = BasicBlockDownloader::new(client.clone(), consensus);
485            Self { block_downloader, client }
486        }
487    }
488
489    #[tokio::test]
490    async fn block_downloader_range_request() {
491        const TOTAL_BLOCKS: usize = 10;
492        let TestHarness { mut block_downloader, client } = TestHarness::new(TOTAL_BLOCKS);
493        let tip = client.highest_block().expect("there should be blocks here");
494
495        // send block range download request
496        block_downloader.on_action(DownloadAction::Download(DownloadRequest::block_range(
497            tip.num_hash(),
498            tip.number,
499        )));
500
501        // ensure we have one in flight range request
502        assert_eq!(block_downloader.inflight_block_range_requests.len(), 1);
503
504        // ensure the range request is made correctly
505        let first_req = block_downloader.inflight_block_range_requests.first().unwrap();
506        assert_eq!(first_req.start_hash(), tip.hash());
507        assert_eq!(first_req.count(), tip.number);
508
509        // poll downloader
510        let sync_future = poll_fn(|cx| block_downloader.poll(cx));
511        let next_ready = sync_future.await;
512
513        assert_matches!(next_ready, DownloadOutcome::NewDownloadStarted { remaining_blocks, .. } => {
514            assert_eq!(remaining_blocks, TOTAL_BLOCKS as u64);
515        });
516
517        let sync_future = poll_fn(|cx| block_downloader.poll(cx));
518        let next_ready = sync_future.await;
519
520        assert_matches!(next_ready, DownloadOutcome::Blocks(blocks) => {
521            // ensure all blocks were obtained
522            assert_eq!(blocks.len(), TOTAL_BLOCKS);
523
524            // ensure they are in ascending order
525            for num in 1..=TOTAL_BLOCKS {
526                assert_eq!(blocks[num - 1].number(), num as u64);
527            }
528        });
529    }
530
531    #[tokio::test]
532    async fn block_downloader_deduplicates_range_requests() {
533        let TestHarness { mut block_downloader, client } = TestHarness::new(3);
534        let start = client.highest_block().unwrap().num_hash();
535        let request = || DownloadRequest::block_range(start, 2);
536
537        block_downloader.on_action(DownloadAction::Download(request()));
538        block_downloader.on_action(DownloadAction::Download(request()));
539        assert_eq!(block_downloader.inflight_block_range_requests.len(), 1);
540
541        block_downloader
542            .on_action(DownloadAction::Download(DownloadRequest::block_range(start, 3)));
543        block_downloader.on_action(DownloadAction::Download(request().with_access_lists(true)));
544        assert_eq!(block_downloader.inflight_block_range_requests.len(), 3);
545
546        // a different start number can resolve differently, so it is not a duplicate.
547        let wrong_start = BlockNumHash::new(start.number + 1, start.hash);
548        block_downloader
549            .on_action(DownloadAction::Download(DownloadRequest::block_range(wrong_start, 2)));
550        assert_eq!(block_downloader.inflight_block_range_requests.len(), 4);
551    }
552
553    #[tokio::test]
554    async fn block_downloader_set_request() {
555        const TOTAL_BLOCKS: usize = 2;
556        let TestHarness { mut block_downloader, client } = TestHarness::new(TOTAL_BLOCKS);
557
558        let tip = client.highest_block().expect("there should be blocks here");
559
560        // send block set download request
561        block_downloader.on_action(DownloadAction::Download(DownloadRequest::block_set(
562            B256Set::from_iter([tip.hash(), tip.parent_hash]),
563        )));
564
565        // ensure we have TOTAL_BLOCKS in flight full block request
566        assert_eq!(block_downloader.inflight_full_block_requests.len(), TOTAL_BLOCKS);
567
568        // poll downloader
569        for _ in 0..TOTAL_BLOCKS {
570            let sync_future = poll_fn(|cx| block_downloader.poll(cx));
571            let next_ready = sync_future.await;
572
573            assert_matches!(next_ready, DownloadOutcome::NewDownloadStarted { remaining_blocks, .. } => {
574                assert_eq!(remaining_blocks, 1);
575            });
576        }
577
578        let sync_future = poll_fn(|cx| block_downloader.poll(cx));
579        let next_ready = sync_future.await;
580        assert_matches!(next_ready, DownloadOutcome::Blocks(blocks) => {
581            // ensure all blocks were obtained
582            assert_eq!(blocks.len(), TOTAL_BLOCKS);
583
584            // ensure they are in ascending order
585            for num in 1..=TOTAL_BLOCKS {
586                assert_eq!(blocks[num - 1].number(), num as u64);
587            }
588        });
589    }
590
591    #[tokio::test]
592    async fn block_downloader_range_request_with_access_lists() {
593        const TOTAL_BLOCKS: usize = 4;
594        let chain_spec = Arc::new(
595            ChainSpecBuilder::default()
596                .chain(MAINNET.chain)
597                .genesis(MAINNET.genesis.clone())
598                .paris_activated()
599                .build(),
600        );
601
602        let client = TestFullBlockClient::default();
603        // empty RLP list
604        let access_list = alloy_primitives::Bytes::from_static(&[0xc0]);
605        let header = Header {
606            base_fee_per_gas: Some(7),
607            gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M,
608            block_access_list_hash: Some(alloy_primitives::keccak256(access_list.as_ref())),
609            ..Default::default()
610        };
611        let mut sealed_header = SealedHeader::seal_slow(header);
612        let body = reth_ethereum_primitives::BlockBody::default();
613        for _ in 0..TOTAL_BLOCKS {
614            let (mut header, hash) = sealed_header.split();
615            header.parent_hash = hash;
616            header.number += 1;
617            header.timestamp += 1;
618            sealed_header = SealedHeader::seal_slow(header);
619            client.insert(sealed_header.clone(), body.clone());
620            client.insert_access_list(sealed_header.hash(), access_list.clone());
621        }
622
623        let consensus = Arc::new(EthBeaconConsensus::new(chain_spec).with_allow_bal_hashes(true));
624        let mut block_downloader = BasicBlockDownloader::new(client.clone(), consensus);
625
626        let tip = client.highest_block().expect("there should be blocks here");
627
628        block_downloader.on_action(DownloadAction::Download(
629            DownloadRequest::block_range(tip.num_hash(), tip.number).with_access_lists(true),
630        ));
631
632        let sync_future = poll_fn(|cx| block_downloader.poll(cx));
633        let next_ready = sync_future.await;
634
635        assert_matches!(next_ready, DownloadOutcome::NewDownloadStarted { remaining_blocks, .. } => {
636            assert_eq!(remaining_blocks, TOTAL_BLOCKS as u64);
637        });
638
639        let sync_future = poll_fn(|cx| block_downloader.poll(cx));
640        let next_ready = sync_future.await;
641
642        assert_matches!(next_ready, DownloadOutcome::Blocks(blocks) => {
643            assert_eq!(blocks.len(), TOTAL_BLOCKS);
644
645            // every block carries its validated access list data
646            for block in &blocks {
647                assert!(block.data().is_some());
648            }
649        });
650    }
651
652    #[tokio::test]
653    async fn block_downloader_clear_request() {
654        const TOTAL_BLOCKS: usize = 10;
655        let TestHarness { mut block_downloader, client } = TestHarness::new(TOTAL_BLOCKS);
656
657        let tip = client.highest_block().expect("there should be blocks here");
658
659        // send block range download request
660        block_downloader.on_action(DownloadAction::Download(DownloadRequest::block_range(
661            tip.num_hash(),
662            tip.number,
663        )));
664
665        // send block set download request
666        let download_set = B256Set::from_iter([tip.hash(), tip.parent_hash]);
667        block_downloader
668            .on_action(DownloadAction::Download(DownloadRequest::block_set(download_set.clone())));
669
670        // ensure we have one in flight range request
671        assert_eq!(block_downloader.inflight_block_range_requests.len(), 1);
672
673        // ensure the range request is made correctly
674        let first_req = block_downloader.inflight_block_range_requests.first().unwrap();
675        assert_eq!(first_req.start_hash(), tip.hash());
676        assert_eq!(first_req.count(), tip.number);
677
678        // ensure we have download_set.len() in flight full block request
679        assert_eq!(block_downloader.inflight_full_block_requests.len(), download_set.len());
680
681        // send clear request
682        block_downloader.on_action(DownloadAction::Clear);
683
684        // ensure we have no in flight range request
685        assert_eq!(block_downloader.inflight_block_range_requests.len(), 0);
686
687        // ensure we have no in flight full block request
688        assert_eq!(block_downloader.inflight_full_block_requests.len(), 0);
689    }
690
691    #[tokio::test]
692    async fn block_downloader_range_request_start_number_mismatch() {
693        let TestHarness { mut block_downloader, client } = TestHarness::new(3);
694        let tip = client.highest_block().expect("there should be blocks here");
695
696        // a buffered child claiming a higher number requests the range one block below it.
697        let start = BlockNumHash::new(tip.number + 5, tip.hash());
698        block_downloader
699            .on_action(DownloadAction::Download(DownloadRequest::block_range(start, start.number)));
700
701        let next_ready = poll_fn(|cx| block_downloader.poll(cx)).await;
702        assert_matches!(next_ready, DownloadOutcome::NewDownloadStarted { .. });
703
704        // the poll that resolves the range reports the mismatch immediately.
705        let next_ready = poll_fn(|cx| block_downloader.poll(cx))
706            .now_or_never()
707            .expect("mismatch should be reported");
708        assert_matches!(next_ready, DownloadOutcome::StartNumberMismatch(mismatch) => {
709            assert_eq!(&mismatch.header, tip.sealed_header());
710        });
711        assert!(block_downloader.inflight_block_range_requests.is_empty());
712    }
713
714    #[tokio::test]
715    async fn block_downloader_single_block_range_request() {
716        let TestHarness { mut block_downloader, client } = TestHarness::new(3);
717        let tip = client.highest_block().expect("there should be blocks here");
718
719        // a single block is fetched by hash, whatever number its buffered child claims.
720        let start = BlockNumHash::new(tip.number + 5, tip.hash());
721        block_downloader
722            .on_action(DownloadAction::Download(DownloadRequest::block_range(start, 1)));
723        assert_eq!(block_downloader.inflight_full_block_requests.len(), 1);
724        assert!(block_downloader.inflight_block_range_requests.is_empty());
725
726        let next_ready = poll_fn(|cx| block_downloader.poll(cx)).await;
727        assert_matches!(next_ready, DownloadOutcome::NewDownloadStarted { remaining_blocks, .. } => {
728            assert_eq!(remaining_blocks, 1);
729        });
730
731        let next_ready = poll_fn(|cx| block_downloader.poll(cx)).await;
732        assert_matches!(next_ready, DownloadOutcome::Blocks(blocks) => {
733            assert_eq!(blocks.len(), 1);
734            assert_eq!(blocks[0].number(), tip.number);
735        });
736    }
737}