Skip to main content

reth_network_p2p/
error.rs

1use std::ops::RangeInclusive;
2
3use super::headers::client::HeadersRequest;
4use alloy_consensus::BlockHeader;
5use alloy_eips::BlockHashOrNumber;
6use alloy_primitives::{BlockNumber, B256};
7use derive_more::{Display, Error};
8use reth_consensus::ConsensusError;
9use reth_network_peers::WithPeerId;
10use reth_network_types::ReputationChangeKind;
11use reth_primitives_traits::{GotExpected, GotExpectedBoxed};
12use reth_storage_errors::{db::DatabaseError, provider::ProviderError};
13use tokio::sync::{mpsc, oneshot};
14
15/// Result alias for result of a request.
16pub type RequestResult<T> = Result<T, RequestError>;
17
18/// Result with [`PeerId`][reth_network_peers::PeerId]
19pub type PeerRequestResult<T> = RequestResult<WithPeerId<T>>;
20
21/// Helper trait used to validate responses.
22pub trait EthResponseValidator {
23    /// Determine whether the response matches what we requested in [`HeadersRequest`]
24    fn is_likely_bad_headers_response(&self, request: &HeadersRequest) -> bool;
25
26    /// Return the response reputation impact if any
27    fn reputation_change_err(&self) -> Option<ReputationChangeKind>;
28}
29
30impl<H: BlockHeader> EthResponseValidator for RequestResult<Vec<H>> {
31    fn is_likely_bad_headers_response(&self, request: &HeadersRequest) -> bool {
32        match self {
33            Ok(headers) => {
34                let request_length = headers.len() as u64;
35
36                if (request_length == 0 && request.limit > 0) || request_length > request.limit {
37                    return true
38                }
39
40                match request.start {
41                    BlockHashOrNumber::Number(block_number) => {
42                        headers.first().is_some_and(|header| block_number != header.number())
43                    }
44                    BlockHashOrNumber::Hash(_) => {
45                        // we don't want to hash the header
46                        false
47                    }
48                }
49            }
50            Err(_) => true,
51        }
52    }
53
54    /// [`RequestError::ChannelClosed`] is not possible here since these errors are mapped to
55    /// `ConnectionDropped`, which will be handled when the dropped connection is cleaned up.
56    ///
57    /// [`RequestError::ConnectionDropped`] should be ignored here because this is already handled
58    /// when the dropped connection is handled.
59    ///
60    /// [`RequestError::UnsupportedCapability`] is also used for locally rejected optional requests,
61    /// which should not affect peer reputation.
62    fn reputation_change_err(&self) -> Option<ReputationChangeKind> {
63        if let Err(err) = self {
64            match err {
65                RequestError::ChannelClosed |
66                RequestError::ConnectionDropped |
67                RequestError::UnsupportedCapability |
68                RequestError::InvalidRequest |
69                RequestError::BadResponse => None,
70                RequestError::Timeout => Some(ReputationChangeKind::Timeout),
71            }
72        } else {
73            None
74        }
75    }
76}
77
78/// Error variants that can happen when sending requests to a session.
79///
80/// Represents errors encountered when sending requests.
81#[derive(Clone, Debug, Eq, PartialEq, Display, Error)]
82pub enum RequestError {
83    /// Closed channel to the peer.
84    /// Indicates the channel to the peer is closed.
85    #[display("closed channel to the peer")]
86    ChannelClosed,
87    /// Connection to a peer dropped while handling the request.
88    /// Represents a dropped connection while handling the request.
89    #[display("connection to a peer dropped while handling the request")]
90    ConnectionDropped,
91    /// Capability message is not supported by the remote peer.
92    /// Indicates an unsupported capability message from the remote peer.
93    #[display("capability message is not supported by remote peer")]
94    UnsupportedCapability,
95    /// Request timed out while awaiting response.
96    /// Represents a timeout while waiting for a response.
97    #[display("request timed out while awaiting response")]
98    Timeout,
99    /// Received bad response.
100    /// Indicates a bad response was received.
101    #[display("received bad response")]
102    BadResponse,
103    /// The locally supplied request is invalid and was rejected before sending.
104    /// This error must not affect peer reputation and is not retryable without fixing the request.
105    #[display("invalid local request")]
106    InvalidRequest,
107}
108
109// === impl RequestError ===
110
111impl RequestError {
112    /// Indicates whether this error is retryable or fatal.
113    pub const fn is_retryable(&self) -> bool {
114        matches!(self, Self::Timeout | Self::ConnectionDropped)
115    }
116
117    /// Whether the error happened because the channel was closed.
118    pub const fn is_channel_closed(&self) -> bool {
119        matches!(self, Self::ChannelClosed)
120    }
121}
122
123impl<T> From<mpsc::error::SendError<T>> for RequestError {
124    fn from(_: mpsc::error::SendError<T>) -> Self {
125        Self::ChannelClosed
126    }
127}
128
129impl From<oneshot::error::RecvError> for RequestError {
130    fn from(_: oneshot::error::RecvError) -> Self {
131        Self::ChannelClosed
132    }
133}
134
135/// The download result type
136pub type DownloadResult<T> = Result<T, DownloadError>;
137
138/// The downloader error type
139#[derive(Debug, Clone, Display, Error)]
140pub enum DownloadError {
141    /* ==================== HEADER ERRORS ==================== */
142    /// Header validation failed.
143    #[display("failed to validate header {hash}, block number {number}: {error}")]
144    HeaderValidation {
145        /// Hash of header failing validation
146        hash: B256,
147        /// Number of header failing validation
148        number: u64,
149        /// The details of validation failure
150        #[error(source)]
151        error: Box<ConsensusError>,
152    },
153    /// Received an invalid tip.
154    #[display("received invalid tip: {_0}")]
155    InvalidTip(GotExpectedBoxed<B256>),
156    /// Received a tip with an invalid tip number.
157    #[display("received invalid tip number: {_0}")]
158    InvalidTipNumber(GotExpected<u64>),
159    /// Received a response to a request with unexpected start block
160    #[display("headers response starts at unexpected block: {_0}")]
161    HeadersResponseStartBlockMismatch(GotExpected<u64>),
162    /// Received more headers than requested.
163    #[display("received more headers than requested: {_0}")]
164    HeadersResponseTooLong(GotExpected<u64>),
165
166    /* ==================== BODIES ERRORS ==================== */
167    /// Block validation failed
168    #[display("failed to validate body for header {hash}, block number {number}: {error}")]
169    BodyValidation {
170        /// Hash of the block failing validation
171        hash: B256,
172        /// Number of the block failing validation
173        number: u64,
174        /// The details of validation failure
175        error: Box<ConsensusError>,
176    },
177    /// Received more bodies than requested.
178    #[display("received more bodies than requested: {_0}")]
179    TooManyBodies(GotExpected<usize>),
180    /// Headers missing from the database.
181    #[display("header missing from the database: {block_number}")]
182    MissingHeader {
183        /// Missing header block number.
184        block_number: BlockNumber,
185    },
186    /// Body range invalid
187    #[display("requested body range is invalid: {range:?}")]
188    InvalidBodyRange {
189        /// Invalid block number range.
190        range: RangeInclusive<BlockNumber>,
191    },
192    /* ==================== COMMON ERRORS ==================== */
193    /// Timed out while waiting for request id response.
194    #[display("timed out while waiting for response")]
195    Timeout,
196    /// Received empty response while expecting non empty
197    #[display("received empty response")]
198    EmptyResponse,
199    /// Error while executing the request.
200    RequestError(RequestError),
201    /// Provider error.
202    Provider(ProviderError),
203}
204
205impl From<DatabaseError> for DownloadError {
206    fn from(error: DatabaseError) -> Self {
207        Self::Provider(ProviderError::Database(error))
208    }
209}
210
211impl From<RequestError> for DownloadError {
212    fn from(error: RequestError) -> Self {
213        Self::RequestError(error)
214    }
215}
216
217impl From<ProviderError> for DownloadError {
218    fn from(error: ProviderError) -> Self {
219        Self::Provider(error)
220    }
221}
222
223#[cfg(test)]
224mod tests {
225    use alloy_consensus::Header;
226
227    use super::*;
228
229    #[test]
230    fn invalid_local_requests_are_not_retryable_or_peer_faults() {
231        let result: RequestResult<Vec<Header>> = Err(RequestError::InvalidRequest);
232        assert!(!RequestError::InvalidRequest.is_retryable());
233        assert_eq!(result.reputation_change_err(), None);
234        assert_eq!(RequestError::InvalidRequest.to_string(), "invalid local request");
235    }
236
237    #[test]
238    fn test_is_likely_bad_headers_response() {
239        let request =
240            HeadersRequest { start: 0u64.into(), limit: 0, direction: Default::default() };
241        let headers: Vec<Header> = vec![];
242        assert!(!Ok(headers).is_likely_bad_headers_response(&request));
243
244        let request =
245            HeadersRequest { start: 0u64.into(), limit: 1, direction: Default::default() };
246        let headers: Vec<Header> = vec![];
247        assert!(Ok(headers).is_likely_bad_headers_response(&request));
248
249        let request =
250            HeadersRequest { start: 0u64.into(), limit: 2, direction: Default::default() };
251        let headers = vec![Header::default()];
252        assert!(!Ok(headers).is_likely_bad_headers_response(&request));
253
254        let request =
255            HeadersRequest { start: 0u64.into(), limit: 1, direction: Default::default() };
256        let headers = vec![Header::default(), Header::default()];
257        assert!(Ok(headers).is_likely_bad_headers_response(&request));
258    }
259}