reth_eth_wire_types/
disconnect_reason.rs

1//! `RLPx` disconnect reason sent to/received from peer
2
3use alloc::vec;
4use alloy_primitives::bytes::{Buf, BufMut};
5use alloy_rlp::{Decodable, Encodable, Header};
6use derive_more::Display;
7use reth_codecs_derive::add_arbitrary_tests;
8use thiserror::Error;
9
10/// RLPx disconnect reason.
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Display)]
12#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
13#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
14#[add_arbitrary_tests(rlp)]
15pub enum DisconnectReason {
16    /// Disconnect requested by the local node or remote peer.
17    #[default]
18    #[display("disconnect requested")]
19    DisconnectRequested = 0x00,
20    /// TCP related error
21    #[display("TCP sub-system error")]
22    TcpSubsystemError = 0x01,
23    /// Breach of protocol at the transport or p2p level
24    #[display("breach of protocol, e.g. a malformed message, bad RLP, etc.")]
25    ProtocolBreach = 0x02,
26    /// Node has no matching protocols.
27    #[display("useless peer")]
28    UselessPeer = 0x03,
29    /// Either the remote or local node has too many peers.
30    #[display("too many peers")]
31    TooManyPeers = 0x04,
32    /// Already connected to the peer.
33    #[display("already connected")]
34    AlreadyConnected = 0x05,
35    /// `p2p` protocol version is incompatible
36    #[display("incompatible P2P protocol version")]
37    IncompatibleP2PProtocolVersion = 0x06,
38    /// Received a null node identity.
39    #[display("null node identity received - this is automatically invalid")]
40    NullNodeIdentity = 0x07,
41    /// Reason when the client is shutting down.
42    #[display("client quitting")]
43    ClientQuitting = 0x08,
44    /// When the received handshake's identify is different from what is expected.
45    #[display("unexpected identity in handshake")]
46    UnexpectedHandshakeIdentity = 0x09,
47    /// The node is connected to itself
48    #[display("identity is the same as this node (i.e. connected to itself)")]
49    ConnectedToSelf = 0x0a,
50    /// Peer or local node did not respond to a ping in time.
51    #[display("ping timeout")]
52    PingTimeout = 0x0b,
53    /// Peer or local node violated a subprotocol-specific rule.
54    #[display("some other reason specific to a subprotocol")]
55    SubprotocolSpecific = 0x10,
56}
57
58impl TryFrom<u8> for DisconnectReason {
59    // This error type should not be used to crash the node, but rather to log the error and
60    // disconnect the peer.
61    type Error = UnknownDisconnectReason;
62
63    fn try_from(value: u8) -> Result<Self, Self::Error> {
64        match value {
65            0x00 => Ok(Self::DisconnectRequested),
66            0x01 => Ok(Self::TcpSubsystemError),
67            0x02 => Ok(Self::ProtocolBreach),
68            0x03 => Ok(Self::UselessPeer),
69            0x04 => Ok(Self::TooManyPeers),
70            0x05 => Ok(Self::AlreadyConnected),
71            0x06 => Ok(Self::IncompatibleP2PProtocolVersion),
72            0x07 => Ok(Self::NullNodeIdentity),
73            0x08 => Ok(Self::ClientQuitting),
74            0x09 => Ok(Self::UnexpectedHandshakeIdentity),
75            0x0a => Ok(Self::ConnectedToSelf),
76            0x0b => Ok(Self::PingTimeout),
77            0x10 => Ok(Self::SubprotocolSpecific),
78            _ => Err(UnknownDisconnectReason(value)),
79        }
80    }
81}
82
83impl Encodable for DisconnectReason {
84    /// The [`Encodable`] implementation for [`DisconnectReason`] encodes the disconnect reason in
85    /// a single-element RLP list.
86    fn encode(&self, out: &mut dyn BufMut) {
87        vec![*self as u8].encode(out);
88    }
89    fn length(&self) -> usize {
90        vec![*self as u8].length()
91    }
92}
93
94impl Decodable for DisconnectReason {
95    /// The [`Decodable`] implementation for [`DisconnectReason`] supports either a disconnect
96    /// reason encoded a single byte or a RLP list containing the disconnect reason.
97    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
98        if buf.is_empty() {
99            return Err(alloy_rlp::Error::InputTooShort)
100        } else if buf.len() > 2 {
101            return Err(alloy_rlp::Error::Overflow)
102        }
103
104        if buf.len() > 1 {
105            // this should be a list, so decode the list header. this should advance the buffer so
106            // buf[0] is the first (and only) element of the list.
107            let header = Header::decode(buf)?;
108
109            if !header.list {
110                return Err(alloy_rlp::Error::UnexpectedString)
111            }
112
113            if header.payload_length != 1 {
114                return Err(alloy_rlp::Error::ListLengthMismatch {
115                    expected: 1,
116                    got: header.payload_length,
117                })
118            }
119        }
120
121        // geth rlp encodes [`DisconnectReason::DisconnectRequested`] as 0x00 and not as empty
122        // string 0x80
123        if buf[0] == 0x00 {
124            buf.advance(1);
125            Ok(Self::DisconnectRequested)
126        } else {
127            Self::try_from(u8::decode(buf)?)
128                .map_err(|_| alloy_rlp::Error::Custom("unknown disconnect reason"))
129        }
130    }
131}
132
133/// This represents an unknown disconnect reason with the given code.
134#[derive(Debug, Clone, Error)]
135#[error("unknown disconnect reason: {0}")]
136pub struct UnknownDisconnectReason(u8);