Skip to main content

reth_network/
error.rs

1//! Possible errors when interacting with the network.
2
3use crate::session::PendingSessionHandshakeError;
4use reth_dns_discovery::resolver::NetError;
5use reth_ecies::ECIESErrorImpl;
6use reth_eth_wire::{
7    errors::{EthHandshakeError, EthStreamError, P2PHandshakeError, P2PStreamError},
8    DisconnectReason,
9};
10use reth_network_types::BackoffKind;
11use std::{fmt, io, io::ErrorKind, net::SocketAddr};
12
13/// Service kind.
14#[derive(Debug, PartialEq, Eq, Copy, Clone)]
15pub enum ServiceKind {
16    /// Listener service.
17    Listener(SocketAddr),
18    /// Discovery service.
19    Discovery(SocketAddr),
20}
21
22impl ServiceKind {
23    /// Returns the appropriate flags for each variant.
24    pub const fn flags(&self) -> &'static str {
25        match self {
26            Self::Listener(_) => "--port",
27            Self::Discovery(_) => "--discovery.port",
28        }
29    }
30}
31
32impl fmt::Display for ServiceKind {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match self {
35            Self::Listener(addr) => write!(f, "{addr} (listener service)"),
36            Self::Discovery(addr) => write!(f, "{addr} (discovery service)"),
37        }
38    }
39}
40
41/// All error variants for the network
42#[derive(Debug, thiserror::Error)]
43pub enum NetworkError {
44    /// General IO error.
45    #[error(transparent)]
46    Io(#[from] io::Error),
47    /// Error when an address is already in use.
48    #[error("address {kind} is already in use (os error 98). Choose a different port using {}", kind.flags())]
49    AddressAlreadyInUse {
50        /// Service kind.
51        kind: ServiceKind,
52        /// IO error.
53        error: io::Error,
54    },
55    /// IO error when creating the discovery service
56    #[error("failed to launch discovery service on {0}: {1}")]
57    Discovery(SocketAddr, io::Error),
58    /// An error occurred with discovery v5 node.
59    #[error("discv5 error, {0}")]
60    Discv5Error(#[from] reth_discv5::Error),
61    /// Error when setting up the DNS resolver failed
62    ///
63    /// See also [`DnsResolver`](reth_dns_discovery::DnsResolver::from_system_conf)
64    #[error("failed to configure DNS resolver: {0}")]
65    DnsResolver(#[from] NetError),
66}
67
68impl NetworkError {
69    /// Converts a `std::io::Error` to a more descriptive `NetworkError`.
70    pub fn from_io_error(err: io::Error, kind: ServiceKind) -> Self {
71        match err.kind() {
72            ErrorKind::AddrInUse => Self::AddressAlreadyInUse { kind, error: err },
73            _ => {
74                if let ServiceKind::Discovery(address) = kind {
75                    return Self::Discovery(address, err)
76                }
77                Self::Io(err)
78            }
79        }
80    }
81}
82
83/// Abstraction over errors that can lead to a failed session
84#[auto_impl::auto_impl(&)]
85pub(crate) trait SessionError: fmt::Debug + fmt::Display {
86    /// Returns true if the error indicates that the corresponding peer should be removed from peer
87    /// discovery, for example if it's using a different genesis hash.
88    fn merits_discovery_ban(&self) -> bool;
89
90    /// Returns true if the error indicates that we'll never be able to establish a connection to
91    /// that peer. For example, not matching capabilities or a mismatch in protocols.
92    ///
93    /// Note: This does not necessarily mean that either of the peers are in violation of the
94    /// protocol but rather that they'll never be able to connect with each other. This check is
95    /// a superset of [`Self::merits_discovery_ban`] which checks if the peer should not be part
96    /// of the gossip network.
97    fn is_fatal_protocol_error(&self) -> bool;
98
99    /// Whether we should backoff.
100    ///
101    /// Returns the severity of the backoff that should be applied, or `None`, if no backoff should
102    /// be applied.
103    ///
104    /// In case of `Some(BackoffKind)` will temporarily prevent additional
105    /// connection attempts.
106    fn should_backoff(&self) -> Option<BackoffKind>;
107}
108
109impl SessionError for EthStreamError {
110    fn merits_discovery_ban(&self) -> bool {
111        match self {
112            Self::P2PStreamError(P2PStreamError::HandshakeError(
113                P2PHandshakeError::HelloNotInHandshake |
114                P2PHandshakeError::NonHelloMessageInHandshake,
115            )) => true,
116            Self::EthHandshakeError(err) => {
117                #[expect(clippy::match_same_arms)]
118                match err {
119                    EthHandshakeError::NoResponse => {
120                        // this happens when the conn simply stalled
121                        false
122                    }
123                    EthHandshakeError::InvalidFork(_) => {
124                        // this can occur when the remote or our node is running an outdated client,
125                        // we shouldn't treat this as fatal, because the node can come back online
126                        // with an updated version any time
127                        false
128                    }
129                    _ => true,
130                }
131            }
132            _ => false,
133        }
134    }
135
136    fn is_fatal_protocol_error(&self) -> bool {
137        match self {
138            Self::P2PStreamError(err) => {
139                matches!(
140                    err,
141                    P2PStreamError::HandshakeError(
142                        P2PHandshakeError::NoSharedCapabilities |
143                            P2PHandshakeError::HelloNotInHandshake |
144                            P2PHandshakeError::NonHelloMessageInHandshake |
145                            P2PHandshakeError::Disconnected(
146                                DisconnectReason::UselessPeer |
147                                    DisconnectReason::IncompatibleP2PProtocolVersion |
148                                    DisconnectReason::ProtocolBreach
149                            )
150                    ) | P2PStreamError::UnknownReservedMessageId(_) |
151                        P2PStreamError::UnknownSubprotocolMessageId(_) |
152                        P2PStreamError::EmptyProtocolMessage |
153                        P2PStreamError::ParseSharedCapability(_) |
154                        P2PStreamError::CapabilityNotShared |
155                        // `UselessPeer` is not fatal here: peer rotation sends it to healthy
156                        // peers on established sessions.
157                        P2PStreamError::Disconnected(
158                            DisconnectReason::IncompatibleP2PProtocolVersion |
159                                DisconnectReason::ProtocolBreach
160                        ) |
161                        P2PStreamError::MismatchedProtocolVersion { .. }
162                )
163            }
164            Self::EthHandshakeError(err) => {
165                #[expect(clippy::match_same_arms)]
166                match err {
167                    EthHandshakeError::NoResponse => {
168                        // this happens when the conn simply stalled
169                        false
170                    }
171                    EthHandshakeError::InvalidFork(_) => {
172                        // this can occur when the remote or our node is running an outdated client,
173                        // we shouldn't treat this as fatal, because the node can come back online
174                        // with an updated version any time
175                        false
176                    }
177                    _ => true,
178                }
179            }
180            _ => false,
181        }
182    }
183
184    fn should_backoff(&self) -> Option<BackoffKind> {
185        if let Some(err) = self.as_io() {
186            return err.should_backoff()
187        }
188
189        if let Some(err) = self.as_disconnected() {
190            return match err {
191                DisconnectReason::TooManyPeers |
192                DisconnectReason::UselessPeer |
193                DisconnectReason::AlreadyConnected |
194                DisconnectReason::PingTimeout |
195                DisconnectReason::DisconnectRequested |
196                DisconnectReason::TcpSubsystemError => Some(BackoffKind::Low),
197
198                DisconnectReason::ProtocolBreach |
199                DisconnectReason::IncompatibleP2PProtocolVersion |
200                DisconnectReason::NullNodeIdentity |
201                DisconnectReason::ClientQuitting |
202                DisconnectReason::UnexpectedHandshakeIdentity |
203                DisconnectReason::ConnectedToSelf |
204                DisconnectReason::SubprotocolSpecific => {
205                    // These are considered fatal, and are handled by the
206                    // [`SessionError::is_fatal_protocol_error`]
207                    Some(BackoffKind::High)
208                }
209            }
210        }
211
212        // This only checks for a subset of error variants, the counterpart of
213        // [`SessionError::is_fatal_protocol_error`]
214        match self {
215            // timeouts
216            Self::EthHandshakeError(EthHandshakeError::NoResponse) |
217            Self::P2PStreamError(
218                P2PStreamError::HandshakeError(P2PHandshakeError::NoResponse) |
219                P2PStreamError::PingTimeout,
220            ) => Some(BackoffKind::Low),
221            // malformed or abusive messages
222            Self::P2PStreamError(
223                P2PStreamError::Rlp(_) |
224                P2PStreamError::UnknownReservedMessageId(_) |
225                P2PStreamError::UnknownSubprotocolMessageId(_) |
226                P2PStreamError::UnknownDisconnectReason(_) |
227                P2PStreamError::MessageTooBig { .. } |
228                P2PStreamError::SubprotocolMessageTooBig { .. } |
229                P2PStreamError::EmptyProtocolMessage |
230                P2PStreamError::InvalidPingPongPayload(_) |
231                P2PStreamError::TooManyPings |
232                P2PStreamError::PingerError(_) |
233                P2PStreamError::Snap(_),
234            ) => Some(BackoffKind::Medium),
235            Self::P2PStreamError(P2PStreamError::SubprotocolInboundBufferFull { .. }) => {
236                Some(BackoffKind::Low)
237            }
238            Self::EthHandshakeError(EthHandshakeError::InvalidFork(_)) => {
239                // the remote can come back online after updating client version, so we can back off
240                // for a bit
241                Some(BackoffKind::Medium)
242            }
243            _ => None,
244        }
245    }
246}
247
248impl SessionError for PendingSessionHandshakeError {
249    fn merits_discovery_ban(&self) -> bool {
250        match self {
251            Self::Eth(eth) => eth.merits_discovery_ban(),
252            Self::Ecies(err) => matches!(
253                err.inner(),
254                ECIESErrorImpl::TagCheckDecryptFailed |
255                    ECIESErrorImpl::TagCheckHeaderFailed |
256                    ECIESErrorImpl::TagCheckBodyFailed |
257                    ECIESErrorImpl::InvalidAuthData |
258                    ECIESErrorImpl::InvalidAckData |
259                    ECIESErrorImpl::InvalidHeader |
260                    ECIESErrorImpl::Secp256k1(_) |
261                    ECIESErrorImpl::InvalidHandshake { .. }
262            ),
263            // A peer that announces someone else's node id is broken or hostile, and its discovery
264            // record cannot be trusted to point at a usable peer.
265            Self::UnexpectedHandshakeIdentity(_) => true,
266            Self::Timeout | Self::UnsupportedExtraCapability => false,
267        }
268    }
269
270    fn is_fatal_protocol_error(&self) -> bool {
271        match self {
272            // During session setup, `UselessPeer` means the remote has no use for us at all.
273            Self::Eth(eth) => {
274                eth.is_fatal_protocol_error() ||
275                    eth.as_disconnected() == Some(DisconnectReason::UselessPeer)
276            }
277            Self::Ecies(err) => matches!(
278                err.inner(),
279                ECIESErrorImpl::TagCheckDecryptFailed |
280                    ECIESErrorImpl::TagCheckHeaderFailed |
281                    ECIESErrorImpl::TagCheckBodyFailed |
282                    ECIESErrorImpl::InvalidAuthData |
283                    ECIESErrorImpl::InvalidAckData |
284                    ECIESErrorImpl::InvalidHeader |
285                    ECIESErrorImpl::Secp256k1(_) |
286                    ECIESErrorImpl::InvalidHandshake { .. }
287            ),
288            Self::Timeout => false,
289            Self::UnsupportedExtraCapability | Self::UnexpectedHandshakeIdentity(_) => true,
290        }
291    }
292
293    fn should_backoff(&self) -> Option<BackoffKind> {
294        match self {
295            Self::Eth(eth) => eth.should_backoff(),
296            Self::Ecies(_) => Some(BackoffKind::Low),
297            Self::Timeout => Some(BackoffKind::Medium),
298            Self::UnsupportedExtraCapability | Self::UnexpectedHandshakeIdentity(_) => {
299                Some(BackoffKind::High)
300            }
301        }
302    }
303}
304
305impl SessionError for io::Error {
306    fn merits_discovery_ban(&self) -> bool {
307        false
308    }
309
310    fn is_fatal_protocol_error(&self) -> bool {
311        false
312    }
313
314    fn should_backoff(&self) -> Option<BackoffKind> {
315        match self.kind() {
316            // these usually happen when the remote instantly drops the connection, for example
317            // if the previous connection isn't properly cleaned up yet and the peer is temp.
318            // banned.
319            ErrorKind::ConnectionReset | ErrorKind::BrokenPipe => Some(BackoffKind::Low),
320            ErrorKind::ConnectionRefused => {
321                // peer is unreachable, e.g. port not open or down
322                Some(BackoffKind::High)
323            }
324            _ => Some(BackoffKind::Medium),
325        }
326    }
327}
328
329#[cfg(test)]
330mod tests {
331    use super::*;
332    use std::net::{Ipv4Addr, SocketAddrV4};
333
334    #[test]
335    fn test_is_fatal_disconnect() {
336        let err = PendingSessionHandshakeError::Eth(EthStreamError::P2PStreamError(
337            P2PStreamError::HandshakeError(P2PHandshakeError::Disconnected(
338                DisconnectReason::UselessPeer,
339            )),
340        ));
341
342        assert!(err.is_fatal_protocol_error());
343
344        // Peer rotation sends `UselessPeer` on established sessions.
345        let err = EthStreamError::P2PStreamError(P2PStreamError::Disconnected(
346            DisconnectReason::UselessPeer,
347        ));
348        assert!(!err.is_fatal_protocol_error());
349        assert!(PendingSessionHandshakeError::Eth(err).is_fatal_protocol_error());
350    }
351
352    #[test]
353    fn ecies_unreadable_stream_is_not_banned() {
354        let err = PendingSessionHandshakeError::Ecies(ECIESErrorImpl::UnreadableStream.into());
355
356        assert!(!err.is_fatal_protocol_error());
357        assert!(!err.merits_discovery_ban());
358    }
359
360    #[test]
361    fn test_should_backoff() {
362        let err = EthStreamError::P2PStreamError(P2PStreamError::HandshakeError(
363            P2PHandshakeError::Disconnected(DisconnectReason::TooManyPeers),
364        ));
365
366        assert_eq!(err.as_disconnected(), Some(DisconnectReason::TooManyPeers));
367        assert_eq!(err.should_backoff(), Some(BackoffKind::Low));
368
369        let err = EthStreamError::P2PStreamError(P2PStreamError::Disconnected(
370            DisconnectReason::UselessPeer,
371        ));
372        assert_eq!(err.should_backoff(), Some(BackoffKind::Low));
373
374        let err = EthStreamError::P2PStreamError(P2PStreamError::HandshakeError(
375            P2PHandshakeError::NoResponse,
376        ));
377        assert_eq!(err.should_backoff(), Some(BackoffKind::Low));
378
379        let err = EthStreamError::P2PStreamError(P2PStreamError::InvalidPingPongPayload(0x02));
380        assert_eq!(err.should_backoff(), Some(BackoffKind::Medium));
381
382        let err = EthStreamError::P2PStreamError(P2PStreamError::TooManyPings);
383        assert!(err.is_protocol_breach());
384        assert_eq!(err.should_backoff(), Some(BackoffKind::Medium));
385    }
386
387    #[test]
388    fn subprotocol_ingress_errors_have_distinct_reputation_outcomes() {
389        let capability = reth_eth_wire::Capability::new_static("test", 1);
390        let unknown =
391            EthStreamError::P2PStreamError(P2PStreamError::UnknownSubprotocolMessageId(0xff));
392        assert!(unknown.is_protocol_breach());
393        assert!(unknown.is_fatal_protocol_error());
394
395        let oversized = EthStreamError::P2PStreamError(P2PStreamError::SubprotocolMessageTooBig {
396            capability: capability.clone(),
397            message_size: 5,
398            max_size: 4,
399        });
400        assert!(!oversized.is_protocol_breach());
401        assert!(!oversized.is_fatal_protocol_error());
402        assert_eq!(oversized.should_backoff(), Some(BackoffKind::Medium));
403
404        let full = EthStreamError::P2PStreamError(P2PStreamError::SubprotocolInboundBufferFull {
405            capability,
406        });
407        assert!(!full.is_protocol_breach());
408        assert!(!full.is_fatal_protocol_error());
409        assert_eq!(full.should_backoff(), Some(BackoffKind::Low));
410    }
411
412    #[test]
413    fn test_address_in_use_message() {
414        let addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 1234));
415        let kinds = [ServiceKind::Discovery(addr), ServiceKind::Listener(addr)];
416
417        for kind in &kinds {
418            let err = NetworkError::AddressAlreadyInUse {
419                kind: *kind,
420                error: io::Error::from(ErrorKind::AddrInUse),
421            };
422
423            assert!(err.to_string().contains(kind.flags()));
424        }
425    }
426}