reth_network_p2p/headers/
client.rsuse crate::{download::DownloadClient, error::PeerRequestResult, priority::Priority};
use alloy_eips::BlockHashOrNumber;
use futures::{Future, FutureExt};
pub use reth_eth_wire_types::{BlockHeaders, HeadersDirection};
use reth_primitives::Header;
use std::{
fmt::Debug,
pin::Pin,
task::{ready, Context, Poll},
};
#[derive(Clone, Debug)]
pub struct HeadersRequest {
pub start: BlockHashOrNumber,
pub limit: u64,
pub direction: HeadersDirection,
}
pub type HeadersFut = Pin<Box<dyn Future<Output = PeerRequestResult<Vec<Header>>> + Send + Sync>>;
#[auto_impl::auto_impl(&, Arc, Box)]
pub trait HeadersClient: DownloadClient {
type Header: Send + Sync + Unpin;
type Output: Future<Output = PeerRequestResult<Vec<Self::Header>>> + Sync + Send + Unpin;
fn get_headers(&self, request: HeadersRequest) -> Self::Output {
self.get_headers_with_priority(request, Priority::Normal)
}
fn get_headers_with_priority(
&self,
request: HeadersRequest,
priority: Priority,
) -> Self::Output;
fn get_header(&self, start: BlockHashOrNumber) -> SingleHeaderRequest<Self::Output> {
self.get_header_with_priority(start, Priority::Normal)
}
fn get_header_with_priority(
&self,
start: BlockHashOrNumber,
priority: Priority,
) -> SingleHeaderRequest<Self::Output> {
let req = HeadersRequest {
start,
limit: 1,
direction: HeadersDirection::Rising,
};
let fut = self.get_headers_with_priority(req, priority);
SingleHeaderRequest { fut }
}
}
#[derive(Debug)]
#[must_use = "futures do nothing unless polled"]
pub struct SingleHeaderRequest<Fut> {
fut: Fut,
}
impl<Fut, H> Future for SingleHeaderRequest<Fut>
where
Fut: Future<Output = PeerRequestResult<Vec<H>>> + Sync + Send + Unpin,
{
type Output = PeerRequestResult<Option<H>>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let resp = ready!(self.get_mut().fut.poll_unpin(cx));
let resp = resp.map(|res| res.map(|headers| headers.into_iter().next()));
Poll::Ready(resp)
}
}