1use 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
27type BlockRangeResult<B> =
29 Result<Vec<SealedBlockWithAccessList<B>>, StartNumberMismatch<<B as Block>::Header>>;
30
31pub trait BlockDownloader: Send + Sync {
33 type Block: Block;
35
36 fn on_action(&mut self, action: DownloadAction);
38
39 fn poll(&mut self, cx: &mut Context<'_>) -> Poll<DownloadOutcome<Self::Block>>;
41}
42
43#[derive(Debug)]
45pub enum DownloadAction {
46 Clear,
48 Download(DownloadRequest),
50}
51
52#[derive(Debug)]
54pub enum DownloadOutcome<B: Block> {
55 Blocks(Vec<SealedBlockWithAccessList<B>>),
57 StartNumberMismatch(StartNumberMismatch<B::Header>),
59 NewDownloadStarted {
61 remaining_blocks: u64,
63 target: B256,
65 },
66}
67
68#[expect(missing_debug_implementations)]
70pub struct BasicBlockDownloader<Client, B: Block>
71where
72 Client: BlockClient + BlockAccessListsClient + 'static,
73{
74 full_block_client: FullBlockClient<Client>,
76 inflight_full_block_requests: Vec<FullBlockDownload<Client>>,
78 inflight_block_range_requests: Vec<FullBlockRangeDownload<Client>>,
80 set_buffered_blocks: BinaryHeap<Reverse<OrderedDownloadedBlock<B>>>,
83 metrics: BlockDownloaderMetrics,
85 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 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 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 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 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 fn download_block_range(&mut self, start: BlockNumHash, count: u64, access_lists: bool) {
135 if count == 1 {
136 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 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 fn is_inflight_request(&self, hash: B256) -> bool {
213 self.inflight_full_block_requests.iter().any(|req| *req.hash() == hash)
214 }
215
216 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 fn push_pending_event(&mut self, pending_event: DownloadOutcome<B>) {
225 self.pending_events.push_back(pending_event);
226 }
227
228 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 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 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 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 self.inflight_full_block_requests.push(request);
264 }
265 }
266
267 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 self.inflight_block_range_requests.push(request);
284 }
285 }
286
287 self.update_block_download_metrics();
288
289 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 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 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#[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
342enum FullBlockDownload<Client>
344where
345 Client: BlockClient + BlockAccessListsClient,
346{
347 Block(FetchFullBlockFuture<Client>),
349 WithAccessList(FetchFullBlockWithBalFuture<Client>),
351}
352
353impl<Client> FullBlockDownload<Client>
354where
355 Client: BlockClient + BlockAccessListsClient + 'static,
356{
357 const fn hash(&self) -> &B256 {
359 match self {
360 Self::Block(req) => req.hash(),
361 Self::WithAccessList(req) => req.hash(),
362 }
363 }
364
365 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
374enum FullBlockRangeDownload<Client>
376where
377 Client: BlockClient + BlockAccessListsClient,
378{
379 Blocks(FetchFullBlockRangeFuture<Client>),
381 WithAccessLists(FetchFullBlockRangeWithBalFuture<Client>),
383}
384
385impl<Client> FullBlockRangeDownload<Client>
386where
387 Client: BlockClient + BlockAccessListsClient + 'static,
388{
389 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 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 const fn count(&self) -> u64 {
407 match self {
408 Self::Blocks(req) => req.count(),
409 Self::WithAccessLists(req) => req.count(),
410 }
411 }
412
413 const fn access_lists(&self) -> bool {
415 matches!(self, Self::WithAccessLists(_))
416 }
417
418 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#[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 block_downloader.on_action(DownloadAction::Download(DownloadRequest::block_range(
497 tip.num_hash(),
498 tip.number,
499 )));
500
501 assert_eq!(block_downloader.inflight_block_range_requests.len(), 1);
503
504 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 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 assert_eq!(blocks.len(), TOTAL_BLOCKS);
523
524 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 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 block_downloader.on_action(DownloadAction::Download(DownloadRequest::block_set(
562 B256Set::from_iter([tip.hash(), tip.parent_hash]),
563 )));
564
565 assert_eq!(block_downloader.inflight_full_block_requests.len(), TOTAL_BLOCKS);
567
568 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 assert_eq!(blocks.len(), TOTAL_BLOCKS);
583
584 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 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 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 block_downloader.on_action(DownloadAction::Download(DownloadRequest::block_range(
661 tip.num_hash(),
662 tip.number,
663 )));
664
665 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 assert_eq!(block_downloader.inflight_block_range_requests.len(), 1);
672
673 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 assert_eq!(block_downloader.inflight_full_block_requests.len(), download_set.len());
680
681 block_downloader.on_action(DownloadAction::Clear);
683
684 assert_eq!(block_downloader.inflight_block_range_requests.len(), 0);
686
687 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 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 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 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}