mod client;
pub use client::FetchClient;
use crate::message::BlockRequest;
use alloy_primitives::B256;
use futures::StreamExt;
use reth_eth_wire::{EthNetworkPrimitives, GetBlockBodies, GetBlockHeaders, NetworkPrimitives};
use reth_network_api::test_utils::PeersHandle;
use reth_network_p2p::{
error::{EthResponseValidator, PeerRequestResult, RequestError, RequestResult},
headers::client::HeadersRequest,
priority::Priority,
};
use reth_network_peers::PeerId;
use reth_network_types::ReputationChangeKind;
use std::{
collections::{HashMap, VecDeque},
sync::{
atomic::{AtomicU64, AtomicUsize, Ordering},
Arc,
},
task::{Context, Poll},
};
use tokio::sync::{mpsc, mpsc::UnboundedSender, oneshot};
use tokio_stream::wrappers::UnboundedReceiverStream;
type InflightHeadersRequest<H> = Request<HeadersRequest, PeerRequestResult<Vec<H>>>;
type InflightBodiesRequest<B> = Request<Vec<B256>, PeerRequestResult<Vec<B>>>;
#[derive(Debug)]
pub struct StateFetcher<N: NetworkPrimitives = EthNetworkPrimitives> {
inflight_headers_requests: HashMap<PeerId, InflightHeadersRequest<N::BlockHeader>>,
inflight_bodies_requests: HashMap<PeerId, InflightBodiesRequest<N::BlockBody>>,
peers: HashMap<PeerId, Peer>,
peers_handle: PeersHandle,
num_active_peers: Arc<AtomicUsize>,
queued_requests: VecDeque<DownloadRequest<N>>,
download_requests_rx: UnboundedReceiverStream<DownloadRequest<N>>,
download_requests_tx: UnboundedSender<DownloadRequest<N>>,
}
impl<N: NetworkPrimitives> StateFetcher<N> {
pub(crate) fn new(peers_handle: PeersHandle, num_active_peers: Arc<AtomicUsize>) -> Self {
let (download_requests_tx, download_requests_rx) = mpsc::unbounded_channel();
Self {
inflight_headers_requests: Default::default(),
inflight_bodies_requests: Default::default(),
peers: Default::default(),
peers_handle,
num_active_peers,
queued_requests: Default::default(),
download_requests_rx: UnboundedReceiverStream::new(download_requests_rx),
download_requests_tx,
}
}
pub(crate) fn new_active_peer(
&mut self,
peer_id: PeerId,
best_hash: B256,
best_number: u64,
timeout: Arc<AtomicU64>,
) {
self.peers.insert(
peer_id,
Peer {
state: PeerState::Idle,
best_hash,
best_number,
timeout,
last_response_likely_bad: false,
},
);
}
pub(crate) fn on_session_closed(&mut self, peer: &PeerId) {
self.peers.remove(peer);
if let Some(req) = self.inflight_headers_requests.remove(peer) {
let _ = req.response.send(Err(RequestError::ConnectionDropped));
}
if let Some(req) = self.inflight_bodies_requests.remove(peer) {
let _ = req.response.send(Err(RequestError::ConnectionDropped));
}
}
pub(crate) fn update_peer_block(&mut self, peer_id: &PeerId, hash: B256, number: u64) -> bool {
if let Some(peer) = self.peers.get_mut(peer_id) {
if number > peer.best_number {
peer.best_hash = hash;
peer.best_number = number;
return true
}
}
false
}
pub(crate) fn on_pending_disconnect(&mut self, peer_id: &PeerId) {
if let Some(peer) = self.peers.get_mut(peer_id) {
peer.state = PeerState::Closing;
}
}
fn next_best_peer(&self) -> Option<PeerId> {
let mut idle = self.peers.iter().filter(|(_, peer)| peer.state.is_idle());
let mut best_peer = idle.next()?;
for maybe_better in idle {
if best_peer.1.last_response_likely_bad && !maybe_better.1.last_response_likely_bad {
best_peer = maybe_better;
continue
}
if maybe_better.1.timeout() < best_peer.1.timeout() &&
!maybe_better.1.last_response_likely_bad
{
best_peer = maybe_better;
}
}
Some(*best_peer.0)
}
fn poll_action(&mut self) -> PollAction {
if self.queued_requests.is_empty() {
return PollAction::NoRequests
}
let Some(peer_id) = self.next_best_peer() else { return PollAction::NoPeersAvailable };
let request = self.queued_requests.pop_front().expect("not empty");
let request = self.prepare_block_request(peer_id, request);
PollAction::Ready(FetchAction::BlockRequest { peer_id, request })
}
pub(crate) fn poll(&mut self, cx: &mut Context<'_>) -> Poll<FetchAction> {
loop {
let no_peers_available = match self.poll_action() {
PollAction::Ready(action) => return Poll::Ready(action),
PollAction::NoRequests => false,
PollAction::NoPeersAvailable => true,
};
loop {
match self.download_requests_rx.poll_next_unpin(cx) {
Poll::Ready(Some(request)) => match request.get_priority() {
Priority::High => {
let pos = self
.queued_requests
.iter()
.position(|req| req.is_normal_priority())
.unwrap_or(0);
self.queued_requests.insert(pos, request);
}
Priority::Normal => {
self.queued_requests.push_back(request);
}
},
Poll::Ready(None) => {
unreachable!("channel can't close")
}
Poll::Pending => break,
}
}
if self.queued_requests.is_empty() || no_peers_available {
return Poll::Pending
}
}
}
fn prepare_block_request(&mut self, peer_id: PeerId, req: DownloadRequest<N>) -> BlockRequest {
if let Some(peer) = self.peers.get_mut(&peer_id) {
peer.state = req.peer_state();
}
match req {
DownloadRequest::GetBlockHeaders { request, response, .. } => {
let inflight = Request { request: request.clone(), response };
self.inflight_headers_requests.insert(peer_id, inflight);
let HeadersRequest { start, limit, direction } = request;
BlockRequest::GetBlockHeaders(GetBlockHeaders {
start_block: start,
limit,
skip: 0,
direction,
})
}
DownloadRequest::GetBlockBodies { request, response, .. } => {
let inflight = Request { request: request.clone(), response };
self.inflight_bodies_requests.insert(peer_id, inflight);
BlockRequest::GetBlockBodies(GetBlockBodies(request))
}
}
}
fn followup_request(&mut self, peer_id: PeerId) -> Option<BlockResponseOutcome> {
let req = self.queued_requests.pop_front()?;
let req = self.prepare_block_request(peer_id, req);
Some(BlockResponseOutcome::Request(peer_id, req))
}
pub(crate) fn on_block_headers_response(
&mut self,
peer_id: PeerId,
res: RequestResult<Vec<N::BlockHeader>>,
) -> Option<BlockResponseOutcome> {
let is_error = res.is_err();
let maybe_reputation_change = res.reputation_change_err();
let resp = self.inflight_headers_requests.remove(&peer_id);
let is_likely_bad_response =
resp.as_ref().is_some_and(|r| res.is_likely_bad_headers_response(&r.request));
if let Some(resp) = resp {
let _ = resp.response.send(res.map(|h| (peer_id, h).into()));
}
if let Some(peer) = self.peers.get_mut(&peer_id) {
peer.last_response_likely_bad = is_likely_bad_response;
if peer.state.on_request_finished() && !is_error && !is_likely_bad_response {
return self.followup_request(peer_id)
}
}
maybe_reputation_change
.map(|reputation_change| BlockResponseOutcome::BadResponse(peer_id, reputation_change))
}
pub(crate) fn on_block_bodies_response(
&mut self,
peer_id: PeerId,
res: RequestResult<Vec<N::BlockBody>>,
) -> Option<BlockResponseOutcome> {
let is_likely_bad_response = res.as_ref().map_or(true, |bodies| bodies.is_empty());
if let Some(resp) = self.inflight_bodies_requests.remove(&peer_id) {
let _ = resp.response.send(res.map(|b| (peer_id, b).into()));
}
if let Some(peer) = self.peers.get_mut(&peer_id) {
peer.last_response_likely_bad = is_likely_bad_response;
if peer.state.on_request_finished() && !is_likely_bad_response {
return self.followup_request(peer_id)
}
}
None
}
pub(crate) fn client(&self) -> FetchClient<N> {
FetchClient {
request_tx: self.download_requests_tx.clone(),
peers_handle: self.peers_handle.clone(),
num_active_peers: Arc::clone(&self.num_active_peers),
}
}
}
enum PollAction {
Ready(FetchAction),
NoRequests,
NoPeersAvailable,
}
#[derive(Debug)]
struct Peer {
state: PeerState,
best_hash: B256,
best_number: u64,
timeout: Arc<AtomicU64>,
last_response_likely_bad: bool,
}
impl Peer {
fn timeout(&self) -> u64 {
self.timeout.load(Ordering::Relaxed)
}
}
#[derive(Debug)]
enum PeerState {
Idle,
GetBlockHeaders,
GetBlockBodies,
Closing,
}
impl PeerState {
const fn is_idle(&self) -> bool {
matches!(self, Self::Idle)
}
fn on_request_finished(&mut self) -> bool {
if !matches!(self, Self::Closing) {
*self = Self::Idle;
return true
}
false
}
}
#[derive(Debug)]
struct Request<Req, Resp> {
#[allow(dead_code)]
request: Req,
response: oneshot::Sender<Resp>,
}
#[derive(Debug)]
pub(crate) enum DownloadRequest<N: NetworkPrimitives> {
GetBlockHeaders {
request: HeadersRequest,
response: oneshot::Sender<PeerRequestResult<Vec<N::BlockHeader>>>,
priority: Priority,
},
GetBlockBodies {
request: Vec<B256>,
response: oneshot::Sender<PeerRequestResult<Vec<N::BlockBody>>>,
priority: Priority,
},
}
impl<N: NetworkPrimitives> DownloadRequest<N> {
const fn peer_state(&self) -> PeerState {
match self {
Self::GetBlockHeaders { .. } => PeerState::GetBlockHeaders,
Self::GetBlockBodies { .. } => PeerState::GetBlockBodies,
}
}
const fn get_priority(&self) -> &Priority {
match self {
Self::GetBlockHeaders { priority, .. } | Self::GetBlockBodies { priority, .. } => {
priority
}
}
}
const fn is_normal_priority(&self) -> bool {
self.get_priority().is_normal()
}
}
pub(crate) enum FetchAction {
BlockRequest {
peer_id: PeerId,
request: BlockRequest,
},
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum BlockResponseOutcome {
Request(PeerId, BlockRequest),
BadResponse(PeerId, ReputationChangeKind),
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{peers::PeersManager, PeersConfig};
use alloy_consensus::Header;
use alloy_primitives::B512;
use std::future::poll_fn;
#[tokio::test(flavor = "multi_thread")]
async fn test_poll_fetcher() {
let manager = PeersManager::new(PeersConfig::default());
let mut fetcher =
StateFetcher::<EthNetworkPrimitives>::new(manager.handle(), Default::default());
poll_fn(move |cx| {
assert!(fetcher.poll(cx).is_pending());
let (tx, _rx) = oneshot::channel();
fetcher.queued_requests.push_back(DownloadRequest::GetBlockBodies {
request: vec![],
response: tx,
priority: Priority::default(),
});
assert!(fetcher.poll(cx).is_pending());
Poll::Ready(())
})
.await;
}
#[tokio::test]
async fn test_peer_rotation() {
let manager = PeersManager::new(PeersConfig::default());
let mut fetcher =
StateFetcher::<EthNetworkPrimitives>::new(manager.handle(), Default::default());
let peer1 = B512::random();
let peer2 = B512::random();
fetcher.new_active_peer(peer1, B256::random(), 1, Arc::new(AtomicU64::new(1)));
fetcher.new_active_peer(peer2, B256::random(), 2, Arc::new(AtomicU64::new(1)));
let first_peer = fetcher.next_best_peer().unwrap();
assert!(first_peer == peer1 || first_peer == peer2);
fetcher.on_pending_disconnect(&first_peer);
let second_peer = fetcher.next_best_peer().unwrap();
assert!(first_peer == peer1 || first_peer == peer2);
assert_ne!(first_peer, second_peer);
fetcher.on_pending_disconnect(&second_peer);
assert_eq!(fetcher.next_best_peer(), None);
}
#[tokio::test]
async fn test_peer_prioritization() {
let manager = PeersManager::new(PeersConfig::default());
let mut fetcher =
StateFetcher::<EthNetworkPrimitives>::new(manager.handle(), Default::default());
let peer1 = B512::random();
let peer2 = B512::random();
let peer3 = B512::random();
let peer2_timeout = Arc::new(AtomicU64::new(300));
fetcher.new_active_peer(peer1, B256::random(), 1, Arc::new(AtomicU64::new(30)));
fetcher.new_active_peer(peer2, B256::random(), 2, Arc::clone(&peer2_timeout));
fetcher.new_active_peer(peer3, B256::random(), 3, Arc::new(AtomicU64::new(50)));
assert_eq!(fetcher.next_best_peer(), Some(peer1));
assert_eq!(fetcher.next_best_peer(), Some(peer1));
peer2_timeout.store(10, Ordering::Relaxed);
assert_eq!(fetcher.next_best_peer(), Some(peer2));
assert_eq!(fetcher.next_best_peer(), Some(peer2));
}
#[tokio::test]
async fn test_on_block_headers_response() {
let manager = PeersManager::new(PeersConfig::default());
let mut fetcher =
StateFetcher::<EthNetworkPrimitives>::new(manager.handle(), Default::default());
let peer_id = B512::random();
assert_eq!(fetcher.on_block_headers_response(peer_id, Ok(vec![Header::default()])), None);
assert_eq!(
fetcher.on_block_headers_response(peer_id, Err(RequestError::Timeout)),
Some(BlockResponseOutcome::BadResponse(peer_id, ReputationChangeKind::Timeout))
);
assert_eq!(
fetcher.on_block_headers_response(peer_id, Err(RequestError::BadResponse)),
None
);
assert_eq!(
fetcher.on_block_headers_response(peer_id, Err(RequestError::ChannelClosed)),
None
);
assert_eq!(
fetcher.on_block_headers_response(peer_id, Err(RequestError::ConnectionDropped)),
None
);
assert_eq!(
fetcher.on_block_headers_response(peer_id, Err(RequestError::UnsupportedCapability)),
None
);
}
#[tokio::test]
async fn test_header_response_outcome() {
let manager = PeersManager::new(PeersConfig::default());
let mut fetcher =
StateFetcher::<EthNetworkPrimitives>::new(manager.handle(), Default::default());
let peer_id = B512::random();
let request_pair = || {
let (tx, _rx) = oneshot::channel();
let req = Request {
request: HeadersRequest {
start: 0u64.into(),
limit: 1,
direction: Default::default(),
},
response: tx,
};
let header = Header { number: 0, ..Default::default() };
(req, header)
};
fetcher.new_active_peer(
peer_id,
Default::default(),
Default::default(),
Default::default(),
);
let (req, header) = request_pair();
fetcher.inflight_headers_requests.insert(peer_id, req);
let outcome = fetcher.on_block_headers_response(peer_id, Ok(vec![header]));
assert!(outcome.is_none());
assert!(fetcher.peers[&peer_id].state.is_idle());
let outcome =
fetcher.on_block_headers_response(peer_id, Err(RequestError::Timeout)).unwrap();
assert!(EthResponseValidator::reputation_change_err(&Err::<Vec<Header>, _>(
RequestError::Timeout
))
.is_some());
match outcome {
BlockResponseOutcome::BadResponse(peer, _) => {
assert_eq!(peer, peer_id)
}
BlockResponseOutcome::Request(_, _) => {
unreachable!()
}
};
assert!(fetcher.peers[&peer_id].state.is_idle());
}
}