1use super::headers::client::HeadersRequest;
2use crate::{
3 block_access_lists::client::{BalRequirement, BlockAccessListsClient},
4 bodies::client::{BodiesClient, SingleBodyRequest},
5 download::DownloadClient,
6 error::PeerRequestResult,
7 headers::client::{HeadersClient, SingleHeaderRequest},
8 priority::Priority,
9 BlockClient,
10};
11use alloy_consensus::BlockHeader;
12use alloy_eip7928::bal::RawBal;
13use alloy_eips::BlockNumHash;
14use alloy_primitives::{Bytes, Sealable, B256};
15use core::marker::PhantomData;
16use futures::FutureExt;
17use reth_consensus::Consensus;
18use reth_eth_wire_types::{BlockAccessLists, EthNetworkPrimitives, NetworkPrimitives};
19use reth_network_peers::{PeerId, WithPeerId};
20use reth_primitives_traits::{Block, SealedBlock, SealedBlockWith, SealedHeader};
21use std::{
22 cmp::Reverse,
23 collections::{HashMap, VecDeque},
24 fmt::Debug,
25 hash::Hash,
26 ops::RangeInclusive,
27 pin::Pin,
28 sync::Arc,
29 task::{ready, Context, Poll},
30};
31use tracing::{debug, trace};
32
33pub type SealedBlockWithAccessList<B> = SealedBlockWith<B, Option<RawBal>>;
35
36#[derive(Debug, Clone)]
38pub struct FullBlockClient<Client>
39where
40 Client: BlockClient,
41{
42 client: Client,
43 consensus: Arc<dyn Consensus<Client::Block>>,
44}
45
46impl<Client> FullBlockClient<Client>
47where
48 Client: BlockClient,
49{
50 pub fn new(client: Client, consensus: Arc<dyn Consensus<Client::Block>>) -> Self {
52 Self { client, consensus }
53 }
54
55 #[cfg(any(test, feature = "test-utils"))]
57 pub fn test_client(client: Client) -> Self {
58 Self::new(client, Arc::new(reth_consensus::test_utils::TestConsensus::default()))
59 }
60}
61
62impl<Client> FullBlockClient<Client>
63where
64 Client: BlockClient,
65{
66 pub fn get_full_block(&self, hash: B256) -> FetchFullBlockFuture<Client> {
73 FetchFullBlockFuture::new(self.client.clone(), self.consensus.clone(), hash)
74 }
75
76 pub fn get_full_block_range(
87 &self,
88 start: BlockNumHash,
89 count: u64,
90 ) -> FetchFullBlockRangeFuture<Client> {
91 let client = self.client.clone();
92 FetchFullBlockRangeFuture {
93 start_hash: start.hash,
94 start_number: start.number,
95 count,
96 request: FullBlockRangeRequest {
97 headers: Some(
98 client.get_headers(HeadersRequest::falling(start.hash.into(), count)),
99 ),
100 bodies: None,
101 },
102 client,
103 headers: Vec::new(),
104 pending_headers: VecDeque::new(),
105 bodies: HashMap::default(),
106 consensus: Arc::clone(&self.consensus),
107 }
108 }
109}
110
111impl<Client> FullBlockClient<Client>
112where
113 Client: BlockClient + BlockAccessListsClient,
114{
115 pub fn get_full_block_with_access_lists(
123 &self,
124 hash: B256,
125 ) -> FetchFullBlockWithBalFuture<Client> {
126 self.get_full_block_with_access_lists_with_requirement(hash, BalRequirement::default())
127 }
128
129 pub fn get_full_block_with_access_lists_with_requirement(
137 &self,
138 hash: B256,
139 requirement: BalRequirement,
140 ) -> FetchFullBlockWithBalFuture<Client> {
141 let client = self.client.clone();
142 FetchFullBlockWithBalFuture {
143 block: FetchFullBlockFuture::new(client.clone(), self.consensus.clone(), hash),
144 block_result: None,
145 bal_request_state: BalRequestState::Pending(
146 client.get_block_access_lists_with_requirement(vec![hash], requirement),
147 ),
148 }
149 }
150
151 pub fn get_full_block_range_with_optional_access_lists(
158 &self,
159 start: BlockNumHash,
160 count: u64,
161 ) -> FetchFullBlockRangeWithBalFuture<Client> {
162 self.get_full_block_range_with_optional_access_lists_with_requirement(
163 start,
164 count,
165 BalRequirement::default(),
166 )
167 }
168
169 pub fn get_full_block_range_with_optional_access_lists_with_requirement(
176 &self,
177 start: BlockNumHash,
178 count: u64,
179 requirement: BalRequirement,
180 ) -> FetchFullBlockRangeWithBalFuture<Client> {
181 let client = self.client.clone();
182 FetchFullBlockRangeWithBalFuture {
183 blocks: self.get_full_block_range(start, count),
184 client,
185 block_result: None,
186 access_lists: OptionalBlockAccessListsState::WaitingForBlocks { requirement },
187 }
188 }
189}
190
191#[must_use = "futures do nothing unless polled"]
196pub struct FetchFullBlockFuture<Client>
197where
198 Client: BlockClient,
199{
200 client: Client,
201 consensus: Arc<dyn Consensus<Client::Block>>,
202 hash: B256,
203 request: FullBlockRequest<Client>,
204 header: Option<SealedHeader<Client::Header>>,
205 body: Option<BodyResponse<Client::Body>>,
206}
207
208impl<Client> FetchFullBlockFuture<Client>
209where
210 Client: BlockClient,
211{
212 fn new(client: Client, consensus: Arc<dyn Consensus<Client::Block>>, hash: B256) -> Self {
213 Self {
214 hash,
215 consensus,
216 request: FullBlockRequest {
217 header: Some(client.get_header(hash.into())),
218 body: Some(client.get_block_body(hash)),
219 },
220 client,
221 header: None,
222 body: None,
223 }
224 }
225
226 pub const fn hash(&self) -> &B256 {
228 &self.hash
229 }
230
231 pub fn block_number(&self) -> Option<u64> {
233 self.header.as_ref().map(|h| h.number())
234 }
235
236 fn take_block(&mut self) -> Option<SealedBlock<Client::Block>> {
238 if self.header.is_none() || self.body.is_none() {
239 return None
240 }
241
242 let header = self.header.take().unwrap();
243 let resp = self.body.take().unwrap();
244 match resp {
245 BodyResponse::Validated(body) => Some(SealedBlock::from_sealed_parts(header, body)),
246 BodyResponse::PendingValidation(resp) => {
247 if let Err(err) = self.consensus.validate_body_against_header(resp.data(), &header)
249 {
250 debug!(target: "downloaders", %err, hash=?header.hash(), "Received wrong body");
251 self.client.report_bad_message(resp.peer_id());
252 self.header = Some(header);
253 self.request.body = Some(self.client.get_block_body(self.hash));
254 return None
255 }
256 Some(SealedBlock::from_sealed_parts(header, resp.into_data()))
257 }
258 }
259 }
260
261 fn on_block_response(&mut self, resp: WithPeerId<Client::Body>) {
262 if let Some(ref header) = self.header {
263 if let Err(err) = self.consensus.validate_body_against_header(resp.data(), header) {
264 debug!(target: "downloaders", %err, hash=?header.hash(), "Received wrong body");
265 self.client.report_bad_message(resp.peer_id());
266 return
267 }
268 self.body = Some(BodyResponse::Validated(resp.into_data()));
269 return
270 }
271 self.body = Some(BodyResponse::PendingValidation(resp));
272 }
273}
274
275impl<Client> Future for FetchFullBlockFuture<Client>
276where
277 Client: BlockClient<Header: BlockHeader + Sealable> + 'static,
278{
279 type Output = SealedBlock<Client::Block>;
280
281 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
282 let this = self.get_mut();
283
284 let mut budget = 4;
286
287 loop {
288 match ready!(this.request.poll(cx)) {
289 ResponseResult::Header(res) => {
290 match res {
291 Ok(maybe_header) => {
292 let (peer, maybe_header) =
293 maybe_header.map(|h| h.map(SealedHeader::seal_slow)).split();
294 if let Some(header) = maybe_header {
295 if header.hash() == this.hash {
296 this.header = Some(header);
297 } else {
298 debug!(target: "downloaders", expected=?this.hash, received=?header.hash(), "Received wrong header");
299 this.client.report_bad_message(peer)
301 }
302 }
303 }
304 Err(err) => {
305 debug!(target: "downloaders", %err, ?this.hash, "Header download failed");
306 }
307 }
308
309 if this.header.is_none() {
310 this.request.header = Some(this.client.get_header(this.hash.into()));
312 }
313 }
314 ResponseResult::Body(res) => {
315 match res {
316 Ok(maybe_body) => {
317 if let Some(body) = maybe_body.transpose() {
318 this.on_block_response(body);
319 }
320 }
321 Err(err) => {
322 debug!(target: "downloaders", %err, ?this.hash, "Body download failed");
323 }
324 }
325 if this.body.is_none() {
326 this.request.body = Some(this.client.get_block_body(this.hash));
328 }
329 }
330 }
331
332 if let Some(res) = this.take_block() {
333 return Poll::Ready(res)
334 }
335
336 budget -= 1;
338 if budget == 0 {
339 cx.waker().wake_by_ref();
341 return Poll::Pending
342 }
343 }
344 }
345}
346
347#[must_use = "futures do nothing unless polled"]
352pub struct FetchFullBlockWithBalFuture<Client>
353where
354 Client: BlockClient + BlockAccessListsClient,
355{
356 block: FetchFullBlockFuture<Client>,
357 block_result: Option<SealedBlock<Client::Block>>,
358 bal_request_state: BalRequestState<<Client as BlockAccessListsClient>::Output>,
359}
360
361impl<Client> FetchFullBlockWithBalFuture<Client>
362where
363 Client: BlockClient<Header: BlockHeader> + BlockAccessListsClient,
364{
365 pub const fn hash(&self) -> &B256 {
367 self.block.hash()
368 }
369}
370
371impl<Client> FetchFullBlockWithBalFuture<Client>
372where
373 Client: BlockClient<Header: BlockHeader + Sealable> + BlockAccessListsClient + 'static,
374{
375 pub fn block_number(&self) -> Option<u64> {
377 self.block_result.as_ref().map(|block| block.number()).or_else(|| self.block.block_number())
378 }
379
380 fn poll_bal_request(&mut self, cx: &mut Context<'_>) -> Poll<()> {
386 let res = match &mut self.bal_request_state {
387 BalRequestState::Pending(fut) => ready!(fut.poll_unpin(cx)),
388 BalRequestState::Ready(_) => return Poll::Ready(()),
389 };
390
391 match res {
392 Ok(bal) => {
393 let (peer, access_lists) = bal.split();
394 match access_lists.0.len() {
395 0 => self.bal_request_state = BalRequestState::Ready(None),
396 1 => {
397 let bal = access_lists.0.into_iter().next().expect("len checked");
398 self.bal_request_state =
399 BalRequestState::Ready(Some(WithPeerId::new(peer, bal)));
400 }
401 received => {
402 debug!(
403 target: "downloaders",
404 hash = ?self.block.hash(),
405 expected = 1,
406 received,
407 "Received wrong access list response",
408 );
409 self.block.client.report_bad_message(peer);
410 self.bal_request_state = BalRequestState::Ready(None);
411 }
412 }
413 }
414 Err(err) => {
415 debug!(
416 target: "downloaders",
417 %err,
418 hash = ?self.block.hash(),
419 "Access list download failed",
420 );
421 self.bal_request_state = BalRequestState::Ready(None);
422 }
423 }
424
425 Poll::Ready(())
426 }
427
428 fn take_block_and_access_lists(&mut self) -> Option<SealedBlockWithAccessList<Client::Block>> {
434 let BalRequestState::Ready(bal) = &mut self.bal_request_state else { return None };
435 let block = self.block_result.take()?;
436 let raw_bal =
437 bal.take().and_then(|bal| match seal_block_access_list_for_block(&block, bal) {
438 Ok(raw_bal) => raw_bal,
439 Err(peer) => {
440 self.block.client.report_bad_message(peer);
441 None
442 }
443 });
444 Some(SealedBlockWith::new(block, raw_bal))
445 }
446}
447
448impl<Client> Future for FetchFullBlockWithBalFuture<Client>
449where
450 Client: BlockClient<Header: BlockHeader + Sealable> + BlockAccessListsClient + 'static,
451{
452 type Output = SealedBlockWithAccessList<Client::Block>;
453
454 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
455 let this = self.get_mut();
456
457 if this.block_result.is_none() &&
458 let Poll::Ready(block) = this.block.poll_unpin(cx)
459 {
460 this.block_result = Some(block);
461 }
462
463 ready!(this.poll_bal_request(cx));
464
465 if let Some(res) = this.take_block_and_access_lists() {
466 return Poll::Ready(res)
467 }
468
469 Poll::Pending
470 }
471}
472
473impl<Client> Debug for FetchFullBlockWithBalFuture<Client>
474where
475 Client: BlockClient<Header: BlockHeader> + BlockAccessListsClient,
476{
477 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
478 f.debug_struct("FetchFullBlockWithBalFuture")
479 .field("hash", &self.block.hash())
480 .field("block_ready", &self.block_result.is_some())
481 .field("bal_request_ready", &self.bal_request_state.is_ready())
482 .finish()
483 }
484}
485
486enum BalRequestState<Req> {
488 Pending(Req),
489 Ready(Option<WithPeerId<Option<Bytes>>>),
490}
491
492impl<Req> BalRequestState<Req> {
493 const fn is_ready(&self) -> bool {
494 matches!(self, Self::Ready(_))
495 }
496}
497
498#[must_use = "futures do nothing unless polled"]
505#[expect(missing_debug_implementations)]
506pub struct FetchFullBlockRangeWithBalFuture<Client>
507where
508 Client: BlockClient + BlockAccessListsClient,
509{
510 blocks: FetchFullBlockRangeFuture<Client>,
511 client: Client,
512 block_result: Option<Vec<SealedBlock<Client::Block>>>,
513 access_lists: OptionalBlockAccessListsState<<Client as BlockAccessListsClient>::Output>,
514}
515
516impl<Client> FetchFullBlockRangeWithBalFuture<Client>
517where
518 Client: BlockClient<Header: Debug + BlockHeader + Sealable + Clone + Hash + Eq>
519 + BlockAccessListsClient,
520{
521 pub const fn start_hash(&self) -> B256 {
523 self.blocks.start_hash()
524 }
525
526 pub const fn start_number(&self) -> u64 {
528 self.blocks.start_number()
529 }
530
531 pub const fn count(&self) -> u64 {
533 self.blocks.count()
534 }
535
536 fn start_access_lists_request_if_possible(&mut self) {
537 let requirement = match &self.access_lists {
538 OptionalBlockAccessListsState::WaitingForBlocks { requirement } => *requirement,
539 OptionalBlockAccessListsState::Pending(_) | OptionalBlockAccessListsState::Ready(_) => {
540 return
541 }
542 };
543
544 let Some(blocks) = self.block_result.as_ref() else { return };
546 let hashes = blocks.iter().map(|block| block.hash()).collect::<Vec<_>>();
547 self.access_lists = OptionalBlockAccessListsState::Pending(
548 self.client.get_block_access_lists_with_requirement(hashes, requirement),
549 );
550 }
551
552 fn poll_access_lists(&mut self, cx: &mut Context<'_>) {
554 self.start_access_lists_request_if_possible();
555
556 let poll = match &mut self.access_lists {
557 OptionalBlockAccessListsState::Pending(fut) => fut.poll_unpin(cx),
558 OptionalBlockAccessListsState::WaitingForBlocks { .. } |
559 OptionalBlockAccessListsState::Ready(_) => return,
560 };
561
562 match poll {
563 Poll::Pending => {}
564 Poll::Ready(Ok(access_lists)) => {
565 self.access_lists = OptionalBlockAccessListsState::Ready(Some(access_lists));
566 }
567 Poll::Ready(Err(err)) => {
568 debug!(
569 target: "downloaders",
570 %err,
571 start_hash = ?self.blocks.start_hash(),
572 "Access list range download failed",
573 );
574
575 self.access_lists = OptionalBlockAccessListsState::Ready(None);
578 }
579 }
580 }
581
582 fn take_response(&mut self) -> Option<Vec<SealedBlockWithAccessList<Client::Block>>> {
584 let OptionalBlockAccessListsState::Ready(access_lists) = &mut self.access_lists else {
585 return None
586 };
587
588 let blocks = self.block_result.take()?;
589
590 Some(seal_blocks_with_access_lists(&self.client, blocks, access_lists.take()))
591 }
592}
593
594impl<Client> Future for FetchFullBlockRangeWithBalFuture<Client>
595where
596 Client: BlockClient<Header: Debug + BlockHeader + Sealable + Clone + Hash + Eq>
597 + BlockAccessListsClient
598 + 'static,
599{
600 type Output =
601 Result<Vec<SealedBlockWithAccessList<Client::Block>>, StartNumberMismatch<Client::Header>>;
602
603 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
604 let this = self.get_mut();
605
606 if this.block_result.is_none() &&
608 let Poll::Ready(blocks) = this.blocks.poll_unpin(cx)
609 {
610 this.block_result = Some(blocks?);
611 }
612
613 this.poll_access_lists(cx);
614
615 if let Some(response) = this.take_response() {
616 return Poll::Ready(Ok(response))
617 }
618
619 Poll::Pending
620 }
621}
622
623enum OptionalBlockAccessListsState<Req> {
625 WaitingForBlocks {
627 requirement: BalRequirement,
629 },
630 Pending(Req),
632 Ready(Option<WithPeerId<BlockAccessLists>>),
634}
635
636impl<Client> Debug for FetchFullBlockFuture<Client>
637where
638 Client: BlockClient<Header: Debug, Body: Debug>,
639{
640 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
641 f.debug_struct("FetchFullBlockFuture")
642 .field("hash", &self.hash)
643 .field("header", &self.header)
644 .field("body", &self.body)
645 .finish()
646 }
647}
648
649struct FullBlockRequest<Client>
650where
651 Client: BlockClient,
652{
653 header: Option<SingleHeaderRequest<<Client as HeadersClient>::Output>>,
654 body: Option<SingleBodyRequest<<Client as BodiesClient>::Output>>,
655}
656
657impl<Client> FullBlockRequest<Client>
658where
659 Client: BlockClient,
660{
661 fn poll(&mut self, cx: &mut Context<'_>) -> Poll<ResponseResult<Client::Header, Client::Body>> {
662 if let Some(fut) = Pin::new(&mut self.header).as_pin_mut() &&
663 let Poll::Ready(res) = fut.poll(cx)
664 {
665 self.header = None;
666 return Poll::Ready(ResponseResult::Header(res))
667 }
668
669 if let Some(fut) = Pin::new(&mut self.body).as_pin_mut() &&
670 let Poll::Ready(res) = fut.poll(cx)
671 {
672 self.body = None;
673 return Poll::Ready(ResponseResult::Body(res))
674 }
675
676 Poll::Pending
677 }
678}
679
680enum ResponseResult<H, B> {
683 Header(PeerRequestResult<Option<H>>),
684 Body(PeerRequestResult<Option<B>>),
685}
686
687#[derive(Debug)]
689enum BodyResponse<B> {
690 Validated(B),
692 PendingValidation(WithPeerId<B>),
694}
695#[must_use = "futures do nothing unless polled"]
708#[expect(missing_debug_implementations)]
709pub struct FetchFullBlockRangeFuture<Client>
710where
711 Client: BlockClient,
712{
713 client: Client,
715 consensus: Arc<dyn Consensus<Client::Block>>,
717 start_hash: B256,
719 start_number: u64,
721 count: u64,
723 request: FullBlockRangeRequest<Client>,
725 headers: Vec<SealedHeader<Client::Header>>,
728 pending_headers: VecDeque<SealedHeader<Client::Header>>,
730 bodies: HashMap<SealedHeader<Client::Header>, BodyResponse<Client::Body>>,
732}
733
734impl<Client> FetchFullBlockRangeFuture<Client>
735where
736 Client: BlockClient<Header: Debug + BlockHeader + Sealable + Clone + Hash + Eq>,
737{
738 fn is_bodies_complete(&self) -> bool {
740 self.bodies.len() == self.count as usize
741 }
742
743 fn insert_body(&mut self, body_response: BodyResponse<Client::Body>) {
747 if let Some(header) = self.pending_headers.pop_front() {
748 self.bodies.insert(header, body_response);
749 }
750 }
751
752 fn insert_bodies(&mut self, bodies: impl IntoIterator<Item = BodyResponse<Client::Body>>) {
754 for body in bodies {
755 self.insert_body(body);
756 }
757 }
758
759 fn remaining_bodies_hashes(&self) -> Vec<B256> {
762 self.pending_headers.iter().map(|h| h.hash()).collect()
763 }
764
765 fn take_blocks(&mut self) -> Option<Vec<SealedBlock<Client::Block>>> {
773 if !self.is_bodies_complete() {
774 return None
776 }
777
778 let headers = core::mem::take(&mut self.headers);
779 let mut needs_retry = false;
780 let mut valid_responses = Vec::new();
781
782 for header in &headers {
783 if let Some(body_resp) = self.bodies.remove(header) {
784 let body = match body_resp {
786 BodyResponse::Validated(body) => body,
787 BodyResponse::PendingValidation(resp) => {
788 if let Err(err) =
790 self.consensus.validate_body_against_header(resp.data(), header)
791 {
792 debug!(target: "downloaders", %err, hash=?header.hash(), "Received wrong body in range response");
793 self.client.report_bad_message(resp.peer_id());
794
795 self.pending_headers.push_back(header.clone());
797 needs_retry = true;
798 continue
799 }
800
801 resp.into_data()
802 }
803 };
804
805 valid_responses
806 .push(SealedBlock::<Client::Block>::from_sealed_parts(header.clone(), body));
807 }
808 }
809
810 if needs_retry {
811 for block in valid_responses {
814 let (header, body) = block.split_sealed_header_body();
815 self.bodies.insert(header, BodyResponse::Validated(body));
816 }
817
818 self.headers = headers;
820
821 let hashes = self.remaining_bodies_hashes();
823 self.request.bodies = Some(self.client.get_block_bodies(hashes));
824 return None
825 }
826
827 Some(valid_responses)
828 }
829
830 fn on_headers_response(
831 &mut self,
832 headers: WithPeerId<Vec<Client::Header>>,
833 ) -> Result<(), StartNumberMismatch<Client::Header>> {
834 let (peer, mut headers_falling) =
835 headers.map(|h| h.into_iter().map(SealedHeader::seal_slow).collect::<Vec<_>>()).split();
836
837 let remaining = self.count as usize - self.headers.len();
839 if headers_falling.is_empty() || headers_falling.len() > remaining {
840 return Ok(())
841 }
842
843 headers_falling.sort_unstable_by_key(|h| Reverse(h.number()));
845
846 if headers_falling[0].hash() != self.next_header_hash() {
848 self.client.report_bad_message(peer);
850 return Ok(())
851 }
852
853 if self.headers.is_empty() && headers_falling[0].number() != self.start_number {
856 debug!(
857 target: "downloaders",
858 start_hash = ?self.start_hash,
859 expected = self.start_number,
860 actual = headers_falling[0].number(),
861 "Header range starts at an unexpected block number",
862 );
863 return Err(StartNumberMismatch { header: headers_falling.swap_remove(0) })
864 }
865
866 let headers_rising = headers_falling.iter().rev().cloned().collect::<Vec<_>>();
867 if let Err(err) = self.consensus.validate_header_range(&headers_rising) {
868 debug!(target: "downloaders", %err, ?self.start_hash, "Received bad header response");
869 self.client.report_bad_message(peer);
870 return Ok(())
871 }
872
873 if let Some(child) = self.headers.last() &&
876 let Err(err) =
877 self.consensus.validate_header_against_parent(child, &headers_falling[0])
878 {
879 debug!(target: "downloaders", %err, ?self.start_hash, "Requested header range is invalid");
880 return Ok(())
881 }
882
883 self.headers.extend(headers_falling);
884 if self.headers.len() < self.count as usize {
885 return Ok(())
886 }
887
888 let hashes = self.headers.iter().map(|h| h.hash()).collect::<Vec<_>>();
890
891 self.pending_headers = self.headers.clone().into();
893
894 if !self.has_bodies_request_started() {
896 self.request.bodies = Some(self.client.get_block_bodies(hashes));
898 }
899
900 Ok(())
901 }
902
903 fn next_header_hash(&self) -> B256 {
906 self.headers.last().map_or(self.start_hash, |h| h.parent_hash())
907 }
908
909 const fn has_bodies_request_started(&self) -> bool {
912 self.request.bodies.is_some()
913 }
914
915 pub const fn start_hash(&self) -> B256 {
917 self.start_hash
918 }
919
920 pub const fn start_number(&self) -> u64 {
922 self.start_number
923 }
924
925 pub const fn count(&self) -> u64 {
927 self.count
928 }
929}
930
931impl<Client> Future for FetchFullBlockRangeFuture<Client>
932where
933 Client: BlockClient<Header: Debug + BlockHeader + Sealable + Clone + Hash + Eq> + 'static,
934{
935 type Output = Result<Vec<SealedBlock<Client::Block>>, StartNumberMismatch<Client::Header>>;
936
937 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
938 let this = self.get_mut();
939
940 loop {
941 match ready!(this.request.poll(cx)) {
942 RangeResponseResult::Header(res) => {
953 match res {
954 Ok(headers) => {
955 this.on_headers_response(headers)?;
956 }
957 Err(err) => {
958 debug!(target: "downloaders", %err, ?this.start_hash, "Header range download failed");
959 }
960 }
961
962 if this.headers.len() < this.count as usize {
963 this.request.headers =
965 Some(this.client.get_headers(HeadersRequest::falling(
966 this.next_header_hash().into(),
967 this.count - this.headers.len() as u64,
968 )));
969 }
970 }
971 RangeResponseResult::Body(res) => {
977 match res {
978 Ok(bodies_resp) => {
979 let (peer, new_bodies) = bodies_resp.split();
980
981 this.insert_bodies(
983 new_bodies
984 .into_iter()
985 .map(|resp| WithPeerId::new(peer, resp))
986 .map(BodyResponse::PendingValidation),
987 );
988
989 if !this.is_bodies_complete() {
990 let req_hashes = this.remaining_bodies_hashes();
992
993 this.request.bodies = Some(this.client.get_block_bodies(req_hashes))
995 }
996 }
997 Err(err) => {
998 debug!(target: "downloaders", %err, ?this.start_hash, "Body range download failed");
999 }
1000 }
1001 if this.request.bodies.is_none() && !this.is_bodies_complete() {
1002 let hashes = this.remaining_bodies_hashes();
1015 if !hashes.is_empty() {
1016 this.request.bodies = Some(this.client.get_block_bodies(hashes));
1017 }
1018 }
1019 }
1020 }
1021
1022 if let Some(res) = this.take_blocks() {
1023 return Poll::Ready(Ok(res))
1024 }
1025 }
1026 }
1027}
1028
1029#[derive(Debug)]
1033pub struct StartNumberMismatch<H> {
1034 pub header: SealedHeader<H>,
1036}
1037
1038struct FullBlockRangeRequest<Client>
1042where
1043 Client: BlockClient,
1044{
1045 headers: Option<<Client as HeadersClient>::Output>,
1046 bodies: Option<<Client as BodiesClient>::Output>,
1047}
1048
1049impl<Client> FullBlockRangeRequest<Client>
1050where
1051 Client: BlockClient,
1052{
1053 fn poll(
1054 &mut self,
1055 cx: &mut Context<'_>,
1056 ) -> Poll<RangeResponseResult<Client::Header, Client::Body>> {
1057 if let Some(fut) = Pin::new(&mut self.headers).as_pin_mut() &&
1058 let Poll::Ready(res) = fut.poll(cx)
1059 {
1060 self.headers = None;
1061 return Poll::Ready(RangeResponseResult::Header(res))
1062 }
1063
1064 if let Some(fut) = Pin::new(&mut self.bodies).as_pin_mut() &&
1065 let Poll::Ready(res) = fut.poll(cx)
1066 {
1067 self.bodies = None;
1068 return Poll::Ready(RangeResponseResult::Body(res))
1069 }
1070
1071 Poll::Pending
1072 }
1073}
1074
1075enum RangeResponseResult<H, B> {
1078 Header(PeerRequestResult<Vec<H>>),
1079 Body(PeerRequestResult<Vec<B>>),
1080}
1081
1082#[derive(Debug, Clone)]
1084#[non_exhaustive]
1085pub struct NoopFullBlockClient<Net = EthNetworkPrimitives>(PhantomData<Net>);
1086
1087impl<Net> DownloadClient for NoopFullBlockClient<Net>
1089where
1090 Net: Debug + Send + Sync,
1091{
1092 fn report_bad_message(&self, _peer_id: PeerId) {}
1099
1100 fn num_connected_peers(&self) -> usize {
1106 0
1107 }
1108}
1109
1110impl<Net> BodiesClient for NoopFullBlockClient<Net>
1112where
1113 Net: NetworkPrimitives,
1114{
1115 type Body = Net::BlockBody;
1116 type Output = futures::future::Ready<PeerRequestResult<Vec<Self::Body>>>;
1118
1119 fn get_block_bodies_with_priority_and_range_hint(
1130 &self,
1131 _hashes: Vec<B256>,
1132 _priority: Priority,
1133 _range_hint: Option<RangeInclusive<u64>>,
1134 ) -> Self::Output {
1135 futures::future::ready(Ok(WithPeerId::new(PeerId::random(), vec![])))
1138 }
1139}
1140
1141impl<Net> HeadersClient for NoopFullBlockClient<Net>
1142where
1143 Net: NetworkPrimitives,
1144{
1145 type Header = Net::BlockHeader;
1146 type Output = futures::future::Ready<PeerRequestResult<Vec<Self::Header>>>;
1149
1150 fn get_headers_with_priority(
1164 &self,
1165 _request: HeadersRequest,
1166 _priority: Priority,
1167 ) -> Self::Output {
1168 futures::future::ready(Ok(WithPeerId::new(PeerId::random(), vec![])))
1169 }
1170}
1171
1172impl<Net> BlockClient for NoopFullBlockClient<Net>
1173where
1174 Net: NetworkPrimitives,
1175{
1176 type Block = Net::Block;
1177}
1178
1179impl<Net> BlockAccessListsClient for NoopFullBlockClient<Net>
1180where
1181 Net: NetworkPrimitives,
1182{
1183 type Output = futures::future::Ready<PeerRequestResult<BlockAccessLists>>;
1184
1185 fn get_block_access_lists_with_priority_and_requirement(
1186 &self,
1187 _hashes: Vec<B256>,
1188 _priority: Priority,
1189 _requirement: BalRequirement,
1190 ) -> Self::Output {
1191 futures::future::ready(Ok(WithPeerId::new(PeerId::random(), BlockAccessLists::default())))
1192 }
1193}
1194
1195impl<Net> Default for NoopFullBlockClient<Net> {
1196 fn default() -> Self {
1197 Self(PhantomData::<Net>)
1198 }
1199}
1200
1201fn seal_block_access_list_for_block<B: Block>(
1207 block: &SealedBlock<B>,
1208 bal: WithPeerId<Option<Bytes>>,
1209) -> Result<Option<RawBal>, PeerId> {
1210 let Some(expected) = block.header().block_access_list_hash() else { return Ok(None) };
1211
1212 let (peer, bal) = bal.split();
1213 let Some(bal) = bal else { return Ok(None) };
1214 let raw_bal = RawBal::new(bal);
1215 raw_bal.ensure_hash(expected).map_err(|error| {
1216 debug!(
1217 target: "downloaders",
1218 block_hash = ?block.hash(),
1219 computed = ?error.computed,
1220 expected = ?error.expected,
1221 "Received block access list with wrong hash",
1222 );
1223 peer
1224 })?;
1225 Ok(Some(raw_bal))
1226}
1227
1228fn seal_blocks_with_access_lists<Client>(
1235 client: &Client,
1236 blocks: Vec<SealedBlock<Client::Block>>,
1237 access_lists: Option<WithPeerId<BlockAccessLists>>,
1238) -> Vec<SealedBlockWithAccessList<Client::Block>>
1239where
1240 Client: BlockClient,
1241{
1242 let Some(access_lists) = access_lists else {
1243 return blocks.into_iter().map(SealedBlockWith::from_block).collect()
1244 };
1245
1246 let (peer, access_lists) = access_lists.split();
1247 let expected = blocks.len();
1248 let received = access_lists.0.len();
1249
1250 if received > expected {
1251 trace!(
1252 target: "downloaders",
1253 expected,
1254 received,
1255 "Ignoring overlong access list range response",
1256 );
1257 return blocks.into_iter().map(SealedBlockWith::from_block).collect()
1258 }
1259
1260 let mut access_lists = access_lists.0.into_iter();
1261 let mut blocks = blocks.into_iter();
1262 let mut response = Vec::with_capacity(expected);
1263
1264 for block in blocks.by_ref() {
1265 let Some(bal) = access_lists.next() else {
1266 response.push(SealedBlockWith::from_block(block));
1269 break
1270 };
1271
1272 match seal_block_access_list_for_block(&block, WithPeerId::new(peer, bal)) {
1273 Ok(raw_bal) => response.push(SealedBlockWith::new(block, raw_bal)),
1274 Err(peer) => {
1275 client.report_bad_message(peer);
1278 response.push(SealedBlockWith::from_block(block));
1279 break
1280 }
1281 }
1282 }
1283
1284 response.extend(blocks.map(SealedBlockWith::from_block));
1285 response
1286}
1287
1288#[cfg(test)]
1289mod tests {
1290 use reth_ethereum_primitives::BlockBody;
1291
1292 use super::*;
1293 use crate::{error::RequestError, test_utils::TestFullBlockClient};
1294 use alloy_consensus::Header;
1295 use alloy_primitives::{keccak256, map::B256Map, Bytes};
1296 use parking_lot::Mutex;
1297 use std::{
1298 ops::Range,
1299 sync::{
1300 atomic::{AtomicBool, AtomicUsize, Ordering},
1301 Arc,
1302 },
1303 };
1304
1305 const EMPTY_LIST_CODE: u8 = 0xc0;
1306 use tokio::time::{timeout, Duration};
1307
1308 fn sealed_header_with_access_list_hash(bal: &Bytes) -> SealedHeader {
1309 let header =
1310 Header { block_access_list_hash: Some(keccak256(bal.as_ref())), ..Default::default() };
1311 SealedHeader::seal_slow(header)
1312 }
1313
1314 fn range_access_lists<B: Block>(
1315 blocks: &[SealedBlockWithAccessList<B>],
1316 ) -> Vec<Option<RawBal>> {
1317 blocks.iter().map(|block| block.data().clone()).collect()
1318 }
1319
1320 #[tokio::test]
1321 async fn download_single_full_block() {
1322 let client = TestFullBlockClient::default();
1323 let header: SealedHeader = SealedHeader::default();
1324 let body = BlockBody::default();
1325 client.insert(header.clone(), body.clone());
1326 let client = FullBlockClient::test_client(client);
1327
1328 let received = client.get_full_block(header.hash()).await;
1329 assert_eq!(received, SealedBlock::from_sealed_parts(header, body));
1330 }
1331
1332 #[tokio::test]
1333 async fn download_single_full_block_range() {
1334 let client = TestFullBlockClient::default();
1335 let header: SealedHeader = SealedHeader::default();
1336 let body = BlockBody::default();
1337 client.insert(header.clone(), body.clone());
1338 let client = FullBlockClient::test_client(client);
1339
1340 let received = client.get_full_block_range(header.num_hash(), 1).await.unwrap();
1341 let received = received.first().expect("response should include a block");
1342 assert_eq!(*received, SealedBlock::from_sealed_parts(header, body));
1343 }
1344
1345 #[tokio::test]
1346 async fn download_single_full_block_with_access_lists() {
1347 let client = FullBlockWithAccessListsClient::default();
1348 let body = BlockBody::default();
1349 let bal = Bytes::from_static(&[EMPTY_LIST_CODE]);
1350 let header = sealed_header_with_access_list_hash(&bal);
1351 client.insert(header.clone(), body.clone(), bal.clone());
1352
1353 let request_count = Arc::clone(&client.access_list_requests);
1354 let client = FullBlockClient::test_client(client);
1355
1356 let received = client.get_full_block_with_access_lists(header.hash()).await;
1357 let expected_raw_bal = RawBal::from(bal);
1358
1359 assert_eq!(received.block(), &SealedBlock::from_sealed_parts(header, body));
1360 assert_eq!(received.data().as_ref(), Some(&expected_raw_bal));
1361 assert_eq!(request_count.load(Ordering::SeqCst), 1);
1362 }
1363
1364 #[tokio::test]
1365 async fn download_single_full_block_with_access_lists_uses_requested_requirement() {
1366 let client = FullBlockWithAccessListsClient::default();
1367 let body = BlockBody::default();
1368 let bal = Bytes::from_static(&[EMPTY_LIST_CODE]);
1369 let header = sealed_header_with_access_list_hash(&bal);
1370 client.insert(header.clone(), body.clone(), bal.clone());
1371
1372 let requirement = Arc::clone(&client.last_access_list_requirement);
1373 let client = FullBlockClient::test_client(client);
1374
1375 let received = client
1376 .get_full_block_with_access_lists_with_requirement(
1377 header.hash(),
1378 BalRequirement::Mandatory,
1379 )
1380 .await;
1381
1382 let expected_raw_bal = RawBal::from(bal);
1383 assert_eq!(received.block(), &SealedBlock::from_sealed_parts(header, body));
1384 assert_eq!(received.data().as_ref(), Some(&expected_raw_bal));
1385 assert_eq!(*requirement.lock(), Some(BalRequirement::Mandatory));
1386 }
1387
1388 #[tokio::test]
1389 async fn download_single_full_block_with_access_lists_waits_for_pending_access_lists() {
1390 let client = FullBlockWithAccessListsClient::default();
1391 client.set_access_list_pending_polls(1);
1392
1393 let body = BlockBody::default();
1394 let bal = Bytes::from_static(&[EMPTY_LIST_CODE]);
1395 let header = sealed_header_with_access_list_hash(&bal);
1396 client.insert(header.clone(), body.clone(), bal.clone());
1397
1398 let request_count = Arc::clone(&client.access_list_requests);
1399 let client = FullBlockClient::test_client(client);
1400
1401 let received =
1402 timeout(Duration::from_secs(1), client.get_full_block_with_access_lists(header.hash()))
1403 .await
1404 .expect("access list request should complete");
1405
1406 let expected_raw_bal = RawBal::from(bal);
1407 assert_eq!(received.block(), &SealedBlock::from_sealed_parts(header, body));
1408 assert_eq!(received.data().as_ref(), Some(&expected_raw_bal));
1409 assert_eq!(request_count.load(Ordering::SeqCst), 1);
1410 }
1411
1412 #[tokio::test]
1413 async fn download_single_full_block_with_access_lists_rejects_wrong_hash() {
1414 let client = FullBlockWithAccessListsClient::default();
1415 let body = BlockBody::default();
1416 let expected_bal = Bytes::from_static(&[EMPTY_LIST_CODE]);
1417 let wrong_bal = Bytes::from_static(&[0xc1, 0x01]);
1418 let header = sealed_header_with_access_list_hash(&expected_bal);
1419 client.insert(header.clone(), body.clone(), wrong_bal);
1420
1421 let bad_messages = Arc::clone(&client.bad_messages);
1422 let client = FullBlockClient::test_client(client);
1423
1424 let received =
1425 timeout(Duration::from_secs(1), client.get_full_block_with_access_lists(header.hash()))
1426 .await
1427 .expect("block request should complete without access lists");
1428
1429 assert_eq!(received.block(), &SealedBlock::from_sealed_parts(header, body));
1430 assert!(received.data().is_none());
1431 assert_eq!(bad_messages.load(Ordering::SeqCst), 1);
1432 }
1433
1434 #[tokio::test]
1435 async fn download_single_full_block_with_access_lists_treats_none_as_unavailable() {
1436 let client = FullBlockWithAccessListsClient::default();
1437 let body = BlockBody::default();
1438 let expected_bal = Bytes::from_static(&[0xc1, 0x01]);
1439 let header = sealed_header_with_access_list_hash(&expected_bal);
1440 client.inner.insert(header.clone(), body.clone());
1441
1442 let bad_messages = Arc::clone(&client.bad_messages);
1443 let client = FullBlockClient::test_client(client);
1444
1445 let received =
1446 timeout(Duration::from_secs(1), client.get_full_block_with_access_lists(header.hash()))
1447 .await
1448 .expect("block request should complete without access lists");
1449
1450 assert_eq!(received.block(), &SealedBlock::from_sealed_parts(header, body));
1451 assert!(received.data().is_none());
1452 assert_eq!(bad_messages.load(Ordering::SeqCst), 0);
1453 }
1454
1455 #[tokio::test]
1456 async fn download_single_full_block_with_access_lists_rejects_wrong_empty_list() {
1457 let client = FullBlockWithAccessListsClient::default();
1458 let body = BlockBody::default();
1459 let expected_bal = Bytes::from_static(&[0xc1, 0x01]);
1460 let wrong_empty_bal = Bytes::from_static(&[EMPTY_LIST_CODE]);
1461 let header = sealed_header_with_access_list_hash(&expected_bal);
1462 client.insert(header.clone(), body.clone(), wrong_empty_bal);
1463
1464 let bad_messages = Arc::clone(&client.bad_messages);
1465 let client = FullBlockClient::test_client(client);
1466
1467 let received =
1468 timeout(Duration::from_secs(1), client.get_full_block_with_access_lists(header.hash()))
1469 .await
1470 .expect("block request should complete without access lists");
1471
1472 assert_eq!(received.block(), &SealedBlock::from_sealed_parts(header, body));
1473 assert!(received.data().is_none());
1474 assert_eq!(bad_messages.load(Ordering::SeqCst), 1);
1475 }
1476
1477 #[tokio::test]
1478 async fn download_single_full_block_with_access_lists_returns_none_after_empty_response() {
1479 let client = FullBlockWithAccessListsClient::default();
1480 client.empty_first_response.store(true, Ordering::SeqCst);
1481
1482 let body = BlockBody::default();
1483 let bal = Bytes::from_static(&[EMPTY_LIST_CODE]);
1484 let header = sealed_header_with_access_list_hash(&bal);
1485 client.insert(header.clone(), body.clone(), bal.clone());
1486
1487 let request_count = Arc::clone(&client.access_list_requests);
1488 let bad_messages = Arc::clone(&client.bad_messages);
1489 let client = FullBlockClient::test_client(client);
1490
1491 let received =
1492 timeout(Duration::from_secs(1), client.get_full_block_with_access_lists(header.hash()))
1493 .await
1494 .expect("block request should complete without access lists");
1495
1496 assert_eq!(received.block(), &SealedBlock::from_sealed_parts(header, body));
1497 assert!(received.data().is_none());
1498 assert_eq!(request_count.load(Ordering::SeqCst), 1);
1499 assert_eq!(bad_messages.load(Ordering::SeqCst), 0);
1500 }
1501
1502 #[tokio::test]
1503 async fn download_single_full_block_with_access_lists_returns_block_when_unavailable() {
1504 let client = FullBlockWithAccessListsClient::default();
1505 client.set_access_lists_unsupported(true);
1506
1507 let body = BlockBody::default();
1508 let bal = Bytes::from_static(&[EMPTY_LIST_CODE]);
1509 let header = sealed_header_with_access_list_hash(&bal);
1510 client.insert(header.clone(), body.clone(), bal);
1511
1512 let request_count = Arc::clone(&client.access_list_requests);
1513 let requirement = Arc::clone(&client.last_access_list_requirement);
1514 let client = FullBlockClient::test_client(client);
1515
1516 let received =
1517 timeout(Duration::from_secs(1), client.get_full_block_with_access_lists(header.hash()))
1518 .await
1519 .expect("block request should complete without access lists");
1520
1521 assert_eq!(received.block(), &SealedBlock::from_sealed_parts(header, body));
1522 assert!(received.data().is_none());
1523 assert_eq!(request_count.load(Ordering::SeqCst), 1);
1524 assert_eq!(
1525 *requirement.lock(),
1526 Some(BalRequirement::Optional),
1527 "single block BAL lookup should be best-effort"
1528 );
1529 }
1530
1531 fn insert_headers_into_client(
1533 client: &TestFullBlockClient,
1534 range: Range<usize>,
1535 ) -> (SealedHeader, BlockBody) {
1536 let mut sealed_header: SealedHeader = SealedHeader::default();
1537 let body = BlockBody::default();
1538 for _ in range {
1539 let (mut header, hash) = sealed_header.split();
1540 header.parent_hash = hash;
1542 header.number += 1;
1543
1544 sealed_header = SealedHeader::seal_slow(header);
1545
1546 client.insert(sealed_header.clone(), body.clone());
1547 }
1548
1549 (sealed_header, body)
1550 }
1551
1552 #[derive(Clone, Debug)]
1553 struct FullBlockWithAccessListsClient {
1554 inner: TestFullBlockClient,
1555 access_lists: Arc<Mutex<B256Map<Bytes>>>,
1556 access_list_requests: Arc<AtomicUsize>,
1557 access_list_soft_limit: Arc<AtomicUsize>,
1558 access_list_pending_polls: Arc<AtomicUsize>,
1559 extra_access_list_entries: Arc<AtomicUsize>,
1560 unsupported_access_lists: Arc<AtomicBool>,
1561 last_access_list_requirement: Arc<Mutex<Option<BalRequirement>>>,
1562 bad_messages: Arc<AtomicUsize>,
1563 empty_first_response: Arc<AtomicBool>,
1564 }
1565
1566 impl Default for FullBlockWithAccessListsClient {
1567 fn default() -> Self {
1568 Self {
1569 inner: TestFullBlockClient::default(),
1570 access_lists: Arc::new(Mutex::new(B256Map::default())),
1571 access_list_requests: Arc::new(AtomicUsize::new(0)),
1572 access_list_soft_limit: Arc::new(AtomicUsize::new(usize::MAX)),
1573 access_list_pending_polls: Arc::new(AtomicUsize::new(0)),
1574 extra_access_list_entries: Arc::new(AtomicUsize::new(0)),
1575 unsupported_access_lists: Arc::new(AtomicBool::new(false)),
1576 last_access_list_requirement: Arc::new(Mutex::new(None)),
1577 bad_messages: Arc::new(AtomicUsize::new(0)),
1578 empty_first_response: Arc::new(AtomicBool::new(false)),
1579 }
1580 }
1581 }
1582
1583 impl FullBlockWithAccessListsClient {
1584 fn insert(&self, header: SealedHeader, body: BlockBody, bal: Bytes) {
1585 self.inner.insert(header.clone(), body);
1586 self.access_lists.lock().insert(header.hash(), bal);
1587 }
1588
1589 fn set_access_list_soft_limit(&self, limit: usize) {
1590 self.access_list_soft_limit.store(limit, Ordering::SeqCst);
1591 }
1592
1593 fn set_access_list_pending_polls(&self, polls: usize) {
1594 self.access_list_pending_polls.store(polls, Ordering::SeqCst);
1595 }
1596
1597 fn set_extra_access_list_entries(&self, count: usize) {
1598 self.extra_access_list_entries.store(count, Ordering::SeqCst);
1599 }
1600
1601 fn set_access_lists_unsupported(&self, unsupported: bool) {
1602 self.unsupported_access_lists.store(unsupported, Ordering::SeqCst);
1603 }
1604 }
1605
1606 fn insert_headers_with_access_lists_into_client(
1608 client: &FullBlockWithAccessListsClient,
1609 range: Range<usize>,
1610 ) -> (SealedHeader, BlockBody) {
1611 let mut sealed_header: SealedHeader = SealedHeader::default();
1612 let body = BlockBody::default();
1613 for block_idx in range {
1614 let (mut header, hash) = sealed_header.split();
1615 header.parent_hash = hash;
1616 header.number += 1;
1617 let bal = Bytes::from(vec![0xc1, block_idx as u8]);
1618 header.block_access_list_hash = Some(keccak256(bal.as_ref()));
1619
1620 sealed_header = SealedHeader::seal_slow(header);
1621
1622 client.insert(sealed_header.clone(), body.clone(), bal);
1623 }
1624
1625 (sealed_header, body)
1626 }
1627
1628 impl DownloadClient for FullBlockWithAccessListsClient {
1629 fn report_bad_message(&self, peer_id: PeerId) {
1630 self.bad_messages.fetch_add(1, Ordering::SeqCst);
1631 self.inner.report_bad_message(peer_id);
1632 }
1633
1634 fn num_connected_peers(&self) -> usize {
1635 self.inner.num_connected_peers()
1636 }
1637 }
1638
1639 impl HeadersClient for FullBlockWithAccessListsClient {
1640 type Header = <TestFullBlockClient as HeadersClient>::Header;
1641 type Output = <TestFullBlockClient as HeadersClient>::Output;
1642
1643 fn get_headers_with_priority(
1644 &self,
1645 request: HeadersRequest,
1646 priority: Priority,
1647 ) -> Self::Output {
1648 self.inner.get_headers_with_priority(request, priority)
1649 }
1650 }
1651
1652 impl BodiesClient for FullBlockWithAccessListsClient {
1653 type Body = <TestFullBlockClient as BodiesClient>::Body;
1654 type Output = <TestFullBlockClient as BodiesClient>::Output;
1655
1656 fn get_block_bodies_with_priority_and_range_hint(
1657 &self,
1658 hashes: Vec<B256>,
1659 priority: Priority,
1660 range_hint: Option<RangeInclusive<u64>>,
1661 ) -> Self::Output {
1662 self.inner.get_block_bodies_with_priority_and_range_hint(hashes, priority, range_hint)
1663 }
1664 }
1665
1666 struct MaybePendingAccessLists {
1667 response: Option<PeerRequestResult<BlockAccessLists>>,
1668 pending_polls: usize,
1669 }
1670
1671 impl MaybePendingAccessLists {
1672 const fn new(response: PeerRequestResult<BlockAccessLists>, pending_polls: usize) -> Self {
1673 Self { response: Some(response), pending_polls }
1674 }
1675 }
1676
1677 impl std::future::Future for MaybePendingAccessLists {
1678 type Output = PeerRequestResult<BlockAccessLists>;
1679
1680 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1681 if self.pending_polls > 0 {
1682 self.pending_polls -= 1;
1683 cx.waker().wake_by_ref();
1684 return Poll::Pending
1685 }
1686
1687 Poll::Ready(self.response.take().expect("future polled after completion"))
1688 }
1689 }
1690
1691 impl BlockAccessListsClient for FullBlockWithAccessListsClient {
1692 type Output = MaybePendingAccessLists;
1693
1694 fn get_block_access_lists_with_priority_and_requirement(
1695 &self,
1696 hashes: Vec<B256>,
1697 _priority: Priority,
1698 requirement: BalRequirement,
1699 ) -> Self::Output {
1700 self.access_list_requests.fetch_add(1, Ordering::SeqCst);
1701 *self.last_access_list_requirement.lock() = Some(requirement);
1702 let pending_polls = self.access_list_pending_polls.swap(0, Ordering::SeqCst);
1703
1704 if self.unsupported_access_lists.load(Ordering::SeqCst) {
1705 return MaybePendingAccessLists::new(
1706 Err(RequestError::UnsupportedCapability),
1707 pending_polls,
1708 )
1709 }
1710
1711 if self.empty_first_response.swap(false, Ordering::SeqCst) {
1712 return MaybePendingAccessLists::new(
1713 Ok(WithPeerId::new(PeerId::random(), BlockAccessLists(Vec::new()))),
1714 pending_polls,
1715 )
1716 }
1717
1718 let mut access_lists: Vec<_> = hashes
1719 .into_iter()
1720 .take(self.access_list_soft_limit.load(Ordering::SeqCst))
1721 .map(|hash| self.access_lists.lock().get(&hash).cloned())
1722 .collect();
1723 for _ in 0..self.extra_access_list_entries.load(Ordering::SeqCst) {
1724 access_lists.push(None);
1725 }
1726
1727 MaybePendingAccessLists::new(
1728 Ok(WithPeerId::new(PeerId::random(), BlockAccessLists(access_lists))),
1729 pending_polls,
1730 )
1731 }
1732 }
1733
1734 impl BlockClient for FullBlockWithAccessListsClient {
1735 type Block = reth_ethereum_primitives::Block;
1736 }
1737
1738 #[derive(Clone, Debug)]
1739 struct FailingBodiesClient {
1740 inner: TestFullBlockClient,
1741 fail_on: usize,
1742 body_requests: Arc<AtomicUsize>,
1743 }
1744
1745 impl FailingBodiesClient {
1746 fn new(inner: TestFullBlockClient, fail_on: usize) -> Self {
1747 Self { inner, fail_on, body_requests: Arc::new(AtomicUsize::new(0)) }
1748 }
1749 }
1750
1751 impl DownloadClient for FailingBodiesClient {
1752 fn report_bad_message(&self, peer_id: PeerId) {
1753 self.inner.report_bad_message(peer_id);
1754 }
1755
1756 fn num_connected_peers(&self) -> usize {
1757 self.inner.num_connected_peers()
1758 }
1759 }
1760
1761 impl HeadersClient for FailingBodiesClient {
1762 type Header = <TestFullBlockClient as HeadersClient>::Header;
1763 type Output = <TestFullBlockClient as HeadersClient>::Output;
1764
1765 fn get_headers_with_priority(
1766 &self,
1767 request: HeadersRequest,
1768 priority: Priority,
1769 ) -> Self::Output {
1770 self.inner.get_headers_with_priority(request, priority)
1771 }
1772 }
1773
1774 impl BodiesClient for FailingBodiesClient {
1775 type Body = <TestFullBlockClient as BodiesClient>::Body;
1776 type Output = <TestFullBlockClient as BodiesClient>::Output;
1777
1778 fn get_block_bodies_with_priority_and_range_hint(
1779 &self,
1780 hashes: Vec<B256>,
1781 priority: Priority,
1782 range_hint: Option<RangeInclusive<u64>>,
1783 ) -> Self::Output {
1784 let attempt = self.body_requests.fetch_add(1, Ordering::SeqCst);
1785 if attempt == self.fail_on {
1786 return futures::future::ready(Err(RequestError::Timeout))
1787 }
1788
1789 self.inner.get_block_bodies_with_priority_and_range_hint(hashes, priority, range_hint)
1790 }
1791 }
1792
1793 impl BlockClient for FailingBodiesClient {
1794 type Block = reth_ethereum_primitives::Block;
1795 }
1796
1797 #[derive(Clone, Debug)]
1799 struct SingleHeaderClient {
1800 inner: TestFullBlockClient,
1801 max_header_requests: usize,
1802 header_requests: Arc<AtomicUsize>,
1803 }
1804
1805 impl DownloadClient for SingleHeaderClient {
1806 fn report_bad_message(&self, peer_id: PeerId) {
1807 self.inner.report_bad_message(peer_id);
1808 }
1809
1810 fn num_connected_peers(&self) -> usize {
1811 self.inner.num_connected_peers()
1812 }
1813 }
1814
1815 impl HeadersClient for SingleHeaderClient {
1816 type Header = <TestFullBlockClient as HeadersClient>::Header;
1817 type Output = <TestFullBlockClient as HeadersClient>::Output;
1818
1819 fn get_headers_with_priority(
1820 &self,
1821 request: HeadersRequest,
1822 priority: Priority,
1823 ) -> Self::Output {
1824 let requests = self.header_requests.fetch_add(1, Ordering::SeqCst) + 1;
1825 assert!(requests <= self.max_header_requests, "too many header requests");
1826
1827 let response =
1828 self.inner.get_headers_with_priority(request, priority).into_inner().map(|resp| {
1829 resp.map(|mut headers| {
1830 headers.truncate(1);
1831 headers
1832 })
1833 });
1834 futures::future::ready(response)
1835 }
1836 }
1837
1838 impl BodiesClient for SingleHeaderClient {
1839 type Body = <TestFullBlockClient as BodiesClient>::Body;
1840 type Output = <TestFullBlockClient as BodiesClient>::Output;
1841
1842 fn get_block_bodies_with_priority_and_range_hint(
1843 &self,
1844 hashes: Vec<B256>,
1845 priority: Priority,
1846 range_hint: Option<RangeInclusive<u64>>,
1847 ) -> Self::Output {
1848 self.inner.get_block_bodies_with_priority_and_range_hint(hashes, priority, range_hint)
1849 }
1850 }
1851
1852 impl BlockClient for SingleHeaderClient {
1853 type Block = reth_ethereum_primitives::Block;
1854 }
1855
1856 #[tokio::test]
1857 async fn download_full_block_range() {
1858 let client = TestFullBlockClient::default();
1859 let (header, body) = insert_headers_into_client(&client, 0..50);
1860 let client = FullBlockClient::test_client(client);
1861
1862 let received = client.get_full_block_range(header.num_hash(), 1).await.unwrap();
1863 let received = received.first().expect("response should include a block");
1864 assert_eq!(*received, SealedBlock::from_sealed_parts(header.clone(), body));
1865
1866 let received = client.get_full_block_range(header.num_hash(), 10).await.unwrap();
1867 assert_eq!(received.len(), 10);
1868 for (i, block) in received.iter().enumerate() {
1869 let expected_number = header.number - i as u64;
1870 assert_eq!(block.number, expected_number);
1871 }
1872 }
1873
1874 #[tokio::test]
1875 async fn download_full_block_range_over_soft_limit() {
1876 let client = TestFullBlockClient::default();
1878 let (header, body) = insert_headers_into_client(&client, 0..50);
1879 let client = FullBlockClient::test_client(client);
1880
1881 let received = client.get_full_block_range(header.num_hash(), 1).await.unwrap();
1882 let received = received.first().expect("response should include a block");
1883 assert_eq!(*received, SealedBlock::from_sealed_parts(header.clone(), body));
1884
1885 let received = client.get_full_block_range(header.num_hash(), 50).await.unwrap();
1886 assert_eq!(received.len(), 50);
1887 for (i, block) in received.iter().enumerate() {
1888 let expected_number = header.number - i as u64;
1889 assert_eq!(block.number, expected_number);
1890 }
1891 }
1892
1893 #[tokio::test]
1894 async fn download_full_block_range_retries_after_body_error() {
1895 let mut client = TestFullBlockClient::default();
1896 client.set_soft_limit(2);
1897 let (header, _) = insert_headers_into_client(&client, 0..3);
1898
1899 let client = FailingBodiesClient::new(client, 1);
1900 let body_requests = Arc::clone(&client.body_requests);
1901 let client = FullBlockClient::test_client(client);
1902
1903 let received =
1904 timeout(Duration::from_secs(1), client.get_full_block_range(header.num_hash(), 3))
1905 .await
1906 .expect("body request retry should complete")
1907 .unwrap();
1908
1909 assert_eq!(received.len(), 3);
1910 assert_eq!(body_requests.load(Ordering::SeqCst), 3);
1911 }
1912
1913 #[tokio::test]
1914 async fn download_full_block_range_keeps_partial_headers() {
1915 let client = TestFullBlockClient::default();
1916 let (header, _) = insert_headers_into_client(&client, 0..5);
1917 let client = SingleHeaderClient {
1918 inner: client,
1919 max_header_requests: 3,
1920 header_requests: Arc::default(),
1921 };
1922 let header_requests = Arc::clone(&client.header_requests);
1923 let client = FullBlockClient::test_client(client);
1924
1925 let received = client.get_full_block_range(header.num_hash(), 3).await.unwrap();
1926
1927 assert_eq!(
1928 received.iter().map(|block| block.number).collect::<Vec<_>>(),
1929 vec![header.number, header.number - 1, header.number - 2]
1930 );
1931 assert_eq!(received[0].hash(), header.hash());
1932 assert_eq!(header_requests.load(Ordering::SeqCst), 3);
1933 }
1934
1935 #[tokio::test]
1936 async fn download_full_block_range_with_access_lists() {
1937 let client = FullBlockWithAccessListsClient::default();
1938 let (header, _) = insert_headers_with_access_lists_into_client(&client, 0..3);
1939
1940 let access_lists = Arc::clone(&client.access_lists);
1941 let request_count = Arc::clone(&client.access_list_requests);
1942 let requirement = Arc::clone(&client.last_access_list_requirement);
1943 let client = FullBlockClient::test_client(client);
1944
1945 let response = timeout(
1946 Duration::from_secs(1),
1947 client.get_full_block_range_with_optional_access_lists(header.num_hash(), 3),
1948 )
1949 .await
1950 .expect("range request should complete")
1951 .unwrap();
1952
1953 let blocks = response;
1954 assert_eq!(blocks.len(), 3);
1955 let expected = {
1956 let bals = access_lists.lock();
1957 blocks
1958 .iter()
1959 .map(|block| {
1960 let bal = bals.get(&block.block().hash()).cloned().expect("access list exists");
1961 Some(RawBal::from(bal))
1962 })
1963 .collect::<Vec<_>>()
1964 };
1965 assert_eq!(range_access_lists(&blocks), expected);
1966 assert_eq!(request_count.load(Ordering::SeqCst), 1);
1967 assert_eq!(*requirement.lock(), Some(BalRequirement::Optional));
1968 }
1969
1970 #[tokio::test]
1971 async fn download_full_block_range_with_access_lists_returns_none_for_empty_response() {
1972 let client = FullBlockWithAccessListsClient::default();
1973 client.empty_first_response.store(true, Ordering::SeqCst);
1974 let (header, _) = insert_headers_with_access_lists_into_client(&client, 0..3);
1975
1976 let request_count = Arc::clone(&client.access_list_requests);
1977 let client = FullBlockClient::test_client(client);
1978
1979 let response = timeout(
1980 Duration::from_secs(1),
1981 client.get_full_block_range_with_optional_access_lists(header.num_hash(), 3),
1982 )
1983 .await
1984 .expect("range request should complete without access lists")
1985 .unwrap();
1986
1987 let blocks = response;
1988 assert_eq!(blocks.len(), 3);
1989 assert_eq!(range_access_lists(&blocks), vec![None; blocks.len()]);
1990 assert_eq!(request_count.load(Ordering::SeqCst), 1);
1991 }
1992
1993 #[tokio::test]
1994 async fn download_full_block_range_with_access_lists_uses_requested_requirement() {
1995 let client = FullBlockWithAccessListsClient::default();
1996 let (header, _) = insert_headers_with_access_lists_into_client(&client, 0..3);
1997
1998 let requirement = Arc::clone(&client.last_access_list_requirement);
1999 let client = FullBlockClient::test_client(client);
2000
2001 let blocks = timeout(
2002 Duration::from_secs(1),
2003 client.get_full_block_range_with_optional_access_lists_with_requirement(
2004 header.num_hash(),
2005 3,
2006 BalRequirement::Mandatory,
2007 ),
2008 )
2009 .await
2010 .expect("range request should complete")
2011 .unwrap();
2012
2013 assert_eq!(blocks.len(), 3);
2014 assert_eq!(*requirement.lock(), Some(BalRequirement::Mandatory));
2015 }
2016
2017 #[tokio::test]
2018 async fn download_full_block_range_with_access_lists_preserves_short_response() {
2019 let client = FullBlockWithAccessListsClient::default();
2020 client.set_access_list_soft_limit(2);
2021 let (header, _) = insert_headers_with_access_lists_into_client(&client, 0..5);
2022
2023 let access_lists = Arc::clone(&client.access_lists);
2024 let request_count = Arc::clone(&client.access_list_requests);
2025 let client = FullBlockClient::test_client(client);
2026
2027 let blocks = timeout(
2028 Duration::from_secs(1),
2029 client.get_full_block_range_with_optional_access_lists(header.num_hash(), 5),
2030 )
2031 .await
2032 .expect("range request should complete without access lists")
2033 .unwrap();
2034
2035 assert_eq!(blocks.len(), 5);
2036 let expected = {
2037 let bals = access_lists.lock();
2038 blocks
2039 .iter()
2040 .enumerate()
2041 .map(|(idx, block)| {
2042 if idx >= 2 {
2043 return None
2044 }
2045
2046 let bal = bals.get(&block.block().hash()).cloned().expect("access list exists");
2047 Some(RawBal::from(bal))
2048 })
2049 .collect::<Vec<_>>()
2050 };
2051 assert_eq!(range_access_lists(&blocks), expected);
2052 assert_eq!(request_count.load(Ordering::SeqCst), 1);
2053 }
2054
2055 #[tokio::test]
2056 async fn download_full_block_range_with_access_lists_preserves_unavailable_entries() {
2057 let client = FullBlockWithAccessListsClient::default();
2058 let (header, _) = insert_headers_with_access_lists_into_client(&client, 0..3);
2059 client.access_lists.lock().remove(&header.hash());
2060
2061 let access_lists = Arc::clone(&client.access_lists);
2062 let bad_messages = Arc::clone(&client.bad_messages);
2063 let client = FullBlockClient::test_client(client);
2064
2065 let blocks = timeout(
2066 Duration::from_secs(1),
2067 client.get_full_block_range_with_optional_access_lists(header.num_hash(), 3),
2068 )
2069 .await
2070 .expect("range request should complete")
2071 .unwrap();
2072
2073 assert_eq!(blocks.len(), 3);
2074 let expected = {
2075 let bals = access_lists.lock();
2076 blocks
2077 .iter()
2078 .map(|block| {
2079 if block.block().hash() == header.hash() {
2080 return None
2081 }
2082
2083 let bal = bals.get(&block.block().hash()).cloned().expect("access list exists");
2084 Some(RawBal::from(bal))
2085 })
2086 .collect::<Vec<_>>()
2087 };
2088 assert_eq!(range_access_lists(&blocks), expected);
2089 assert_eq!(bad_messages.load(Ordering::SeqCst), 0);
2090 }
2091
2092 #[tokio::test]
2093 async fn download_full_block_range_with_access_lists_returns_none_when_unavailable() {
2094 let client = FullBlockWithAccessListsClient::default();
2095 client.set_access_lists_unsupported(true);
2096 let (header, _) = insert_headers_with_access_lists_into_client(&client, 0..3);
2097
2098 let request_count = Arc::clone(&client.access_list_requests);
2099 let client = FullBlockClient::test_client(client);
2100
2101 let blocks = timeout(
2102 Duration::from_secs(1),
2103 client.get_full_block_range_with_optional_access_lists(header.num_hash(), 3),
2104 )
2105 .await
2106 .expect("range request should complete without access lists")
2107 .unwrap();
2108
2109 assert_eq!(blocks.len(), 3);
2110 assert_eq!(range_access_lists(&blocks), vec![None; blocks.len()]);
2111 assert_eq!(request_count.load(Ordering::SeqCst), 1);
2112 }
2113
2114 #[tokio::test]
2115 async fn download_full_block_range_with_access_lists_ignores_long_response() {
2116 let client = FullBlockWithAccessListsClient::default();
2117 client.set_extra_access_list_entries(1);
2118 let (header, _) = insert_headers_with_access_lists_into_client(&client, 0..3);
2119
2120 let request_count = Arc::clone(&client.access_list_requests);
2121 let bad_messages = Arc::clone(&client.bad_messages);
2122 let client = FullBlockClient::test_client(client);
2123
2124 let blocks = timeout(
2125 Duration::from_secs(1),
2126 client.get_full_block_range_with_optional_access_lists(header.num_hash(), 3),
2127 )
2128 .await
2129 .expect("range request should complete without access lists")
2130 .unwrap();
2131
2132 assert_eq!(blocks.len(), 3);
2133 assert_eq!(range_access_lists(&blocks), vec![None; blocks.len()]);
2134 assert_eq!(request_count.load(Ordering::SeqCst), 1);
2135 assert_eq!(bad_messages.load(Ordering::SeqCst), 0);
2136 }
2137
2138 #[tokio::test]
2139 async fn download_full_block_range_with_access_lists_rejects_wrong_hash() {
2140 let client = FullBlockWithAccessListsClient::default();
2141 let (header, _) = insert_headers_with_access_lists_into_client(&client, 0..3);
2142 client.access_lists.lock().insert(header.hash(), Bytes::from_static(&[0xc1, 0x7f]));
2143
2144 let bad_messages = Arc::clone(&client.bad_messages);
2145 let client = FullBlockClient::test_client(client);
2146
2147 let blocks = timeout(
2148 Duration::from_secs(1),
2149 client.get_full_block_range_with_optional_access_lists(header.num_hash(), 3),
2150 )
2151 .await
2152 .expect("range request should complete without access lists")
2153 .unwrap();
2154
2155 assert_eq!(blocks.len(), 3);
2156 assert_eq!(range_access_lists(&blocks), vec![None; blocks.len()]);
2157 assert_eq!(bad_messages.load(Ordering::SeqCst), 1);
2158 }
2159
2160 #[tokio::test]
2161 async fn download_full_block_range_with_access_lists_preserves_valid_prefix_until_wrong_hash() {
2162 let client = FullBlockWithAccessListsClient::default();
2163 let (header, _) = insert_headers_with_access_lists_into_client(&client, 0..3);
2164 let first_bal =
2165 client.access_lists.lock().get(&header.hash()).cloned().expect("access list exists");
2166 let second_hash = header.parent_hash;
2167 client.access_lists.lock().insert(second_hash, Bytes::from_static(&[0xc1, 0x7f]));
2168
2169 let bad_messages = Arc::clone(&client.bad_messages);
2170 let client = FullBlockClient::test_client(client);
2171
2172 let blocks = timeout(
2173 Duration::from_secs(1),
2174 client.get_full_block_range_with_optional_access_lists(header.num_hash(), 3),
2175 )
2176 .await
2177 .expect("range request should complete without unvalidated access lists")
2178 .unwrap();
2179
2180 assert_eq!(blocks.len(), 3);
2181 assert_eq!(blocks[1].block().hash(), second_hash);
2182 assert_eq!(range_access_lists(&blocks), vec![Some(RawBal::from(first_bal)), None, None]);
2183 assert_eq!(bad_messages.load(Ordering::SeqCst), 1);
2184 }
2185
2186 #[tokio::test]
2187 async fn download_full_block_range_rejects_invalid_headers() {
2188 let client = TestFullBlockClient::default();
2189 let (header, _) = insert_headers_into_client(&client, 0..3);
2190 let consensus = reth_consensus::test_utils::TestConsensus::default();
2191 consensus.set_fail_validation(true);
2192 let client = FullBlockClient::new(client, Arc::new(consensus));
2193 let mut request = client.get_full_block_range(header.num_hash(), 3);
2194 let headers = client
2195 .client
2196 .get_headers(HeadersRequest::falling(header.hash().into(), 3))
2197 .await
2198 .unwrap();
2199
2200 request.on_headers_response(headers).unwrap();
2201
2202 assert!(request.headers.is_empty());
2203 assert!(request.pending_headers.is_empty());
2204 assert!(request.request.bodies.is_none());
2205 }
2206
2207 #[tokio::test]
2208 async fn download_full_block_range_validates_partial_headers_boundary() {
2209 let client = TestFullBlockClient::default();
2210 let (header, _) = insert_headers_into_client(&client, 0..3);
2211 let consensus = Arc::new(reth_consensus::test_utils::TestConsensus::default());
2212 let client = FullBlockClient::new(client, consensus.clone());
2213 let mut request = client.get_full_block_range(header.num_hash(), 3);
2214
2215 let first = client
2216 .client
2217 .get_headers(HeadersRequest::falling(header.hash().into(), 1))
2218 .await
2219 .unwrap();
2220 request.on_headers_response(first).unwrap();
2221 assert_eq!(request.headers.len(), 1);
2222
2223 let parent_request = HeadersRequest::falling(header.parent_hash.into(), 1);
2225 consensus.set_fail_header_against_parent(true);
2226 request
2227 .on_headers_response(client.client.get_headers(parent_request.clone()).await.unwrap())
2228 .unwrap();
2229 assert_eq!(request.headers.len(), 1);
2230 assert_eq!(client.client.bad_messages(), 0);
2232
2233 consensus.set_fail_header_against_parent(false);
2234 request
2235 .on_headers_response(client.client.get_headers(parent_request).await.unwrap())
2236 .unwrap();
2237 assert_eq!(request.headers.len(), 2);
2238 assert_eq!(request.headers[1].hash(), header.parent_hash);
2239 }
2240
2241 #[tokio::test]
2242 async fn download_full_block_range_rejects_wrong_start_number() {
2243 let client = TestFullBlockClient::default();
2244 let (header, _) = insert_headers_into_client(&client, 0..5);
2245 let client = SingleHeaderClient {
2246 inner: client,
2247 max_header_requests: 1,
2248 header_requests: Arc::default(),
2249 };
2250 let header_requests = Arc::clone(&client.header_requests);
2251 let client = FullBlockClient::test_client(client);
2252
2253 let start = BlockNumHash::new(header.number + 7, header.hash());
2255 let mismatch = timeout(Duration::from_secs(1), client.get_full_block_range(start, 1000))
2256 .await
2257 .unwrap()
2258 .unwrap_err();
2259
2260 assert_eq!(mismatch.header, header);
2261 assert_eq!(header_requests.load(Ordering::SeqCst), 1);
2263 assert_eq!(client.client.inner.bad_messages(), 0);
2264 }
2265}