Skip to main content

reth_eth_wire/
hello.rs

1use crate::{Capability, EthVersion, ProtocolVersion};
2use alloy_rlp::{Decodable, Header, RlpEncodable};
3use reth_codecs::add_arbitrary_tests;
4use reth_network_peers::PeerId;
5use reth_primitives_traits::constants::RETH_CLIENT_VERSION;
6
7/// The default tcp port for p2p.
8///
9/// Note: this is the same as discovery port: `DEFAULT_DISCOVERY_PORT`
10pub(crate) const DEFAULT_TCP_PORT: u16 = 30303;
11
12use crate::protocol::Protocol;
13#[cfg(feature = "serde")]
14use serde::{Deserialize, Serialize};
15
16/// This is a superset of [`HelloMessage`] that provides additional protocol [Protocol] information
17/// about the number of messages used by each capability in order to do proper message ID
18/// multiplexing.
19///
20/// This type is required for the `p2p` handshake because the [`HelloMessage`] does not share the
21/// number of messages used by each capability.
22///
23/// To get the encodable [`HelloMessage`] without the additional protocol information, use the
24/// [`HelloMessageWithProtocols::message`].
25#[derive(Debug, Clone, PartialEq, Eq)]
26#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
27pub struct HelloMessageWithProtocols {
28    /// The version of the `p2p` protocol.
29    pub protocol_version: ProtocolVersion,
30    /// Specifies the client software identity, as a human-readable string (e.g.
31    /// "Ethereum(++)/1.0.0").
32    pub client_version: String,
33    /// The list of supported capabilities and their versions.
34    pub protocols: Vec<Protocol>,
35    /// The port that the client is listening on, zero indicates the client is not listening.
36    ///
37    /// By default this is `30303` which is the same as the default discovery port.
38    pub port: u16,
39    /// The secp256k1 public key corresponding to the node's private key.
40    pub id: PeerId,
41}
42
43impl HelloMessageWithProtocols {
44    /// Starts a new `HelloMessageProtocolsBuilder`
45    ///
46    /// ```
47    /// use reth_eth_wire::HelloMessageWithProtocols;
48    /// use reth_network_peers::pk2id;
49    /// use secp256k1::SecretKey;
50    /// let secret_key = SecretKey::new(&mut rand::rng());
51    /// let id = pk2id(&secret_key.public_key());
52    /// let status = HelloMessageWithProtocols::builder(id).build();
53    /// ```
54    pub const fn builder(id: PeerId) -> HelloMessageBuilder {
55        HelloMessageBuilder::new(id)
56    }
57
58    /// Returns the raw [`HelloMessage`] without the additional protocol information.
59    #[inline]
60    pub fn message(&self) -> HelloMessage {
61        HelloMessage {
62            protocol_version: self.protocol_version,
63            client_version: self.client_version.clone(),
64            capabilities: self.protocols.iter().map(|p| p.cap.clone()).collect(),
65            port: self.port,
66            id: self.id,
67        }
68    }
69
70    /// Converts the type into a [`HelloMessage`] without the additional protocol information.
71    pub fn into_message(self) -> HelloMessage {
72        HelloMessage {
73            protocol_version: self.protocol_version,
74            client_version: self.client_version,
75            capabilities: self.protocols.into_iter().map(|p| p.cap).collect(),
76            port: self.port,
77            id: self.id,
78        }
79    }
80
81    /// Returns true if the set of protocols contains the given protocol.
82    #[inline]
83    pub fn contains_protocol(&self, protocol: &Protocol) -> bool {
84        self.protocols.iter().any(|p| p.cap == protocol.cap)
85    }
86
87    /// Adds a new protocol to the set.
88    ///
89    /// Returns an error if the protocol already exists.
90    #[inline]
91    pub fn try_add_protocol(&mut self, protocol: Protocol) -> Result<(), Protocol> {
92        if self.contains_protocol(&protocol) {
93            Err(protocol)
94        } else {
95            self.protocols.push(protocol);
96            Ok(())
97        }
98    }
99
100    /// Toggles advertisement of the `snap/2` satellite protocol (EIP-8189).
101    ///
102    /// snap/2 is negotiated as an `RLPx` capability and rides alongside `eth` on the same
103    /// connection. Disabling removes any advertised `snap` capability of any version.
104    pub fn with_snap(mut self, enable: bool) -> Self {
105        if enable {
106            let _ = self.try_add_protocol(Protocol::snap_2());
107        } else {
108            self.protocols.retain(|p| p.cap.name != "snap");
109        }
110        self
111    }
112
113    /// Replaces every advertised `eth` capability with the given versions.
114    ///
115    /// The versions are placed first, in the given order. Other capabilities, such as `snap`, are
116    /// kept. Use this to pin the `eth` versions instead of advertising
117    /// [`EthVersion::ALL_VERSIONS`].
118    pub fn set_eth_versions(&mut self, versions: impl IntoIterator<Item = EthVersion>) {
119        self.protocols.retain(|p| p.cap.name != "eth");
120        self.protocols.splice(0..0, versions.into_iter().map(Protocol::eth));
121    }
122
123    /// Builder variant of [`Self::set_eth_versions`].
124    pub fn with_eth_versions(mut self, versions: impl IntoIterator<Item = EthVersion>) -> Self {
125        self.set_eth_versions(versions);
126        self
127    }
128}
129
130/// Raw rlpx protocol message used in the `p2p` handshake, containing information about the
131/// supported `RLPx` protocol version and capabilities.
132///
133/// Decoding ignores list elements after `id`, which the spec reserves for future versions (EIP-8).
134///
135/// See also <https://github.com/ethereum/devp2p/blob/master/rlpx.md#hello-0x00>
136#[derive(Clone, Debug, PartialEq, Eq, RlpEncodable)]
137#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
138#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
139#[add_arbitrary_tests(rlp)]
140pub struct HelloMessage {
141    /// The version of the `p2p` protocol.
142    pub protocol_version: ProtocolVersion,
143    /// Specifies the client software identity, as a human-readable string (e.g.
144    /// "Ethereum(++)/1.0.0").
145    pub client_version: String,
146    /// The list of supported capabilities and their versions.
147    pub capabilities: Vec<Capability>,
148    /// The port that the client is listening on, zero indicates the client is not listening.
149    pub port: u16,
150    /// The secp256k1 public key corresponding to the node's private key.
151    pub id: PeerId,
152}
153
154// === impl HelloMessage ===
155
156impl Decodable for HelloMessage {
157    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
158        let mut payload = Header::decode_bytes(buf, true)?;
159        Ok(Self {
160            protocol_version: Decodable::decode(&mut payload)?,
161            client_version: Decodable::decode(&mut payload)?,
162            capabilities: Decodable::decode(&mut payload)?,
163            port: Decodable::decode(&mut payload)?,
164            id: Decodable::decode(&mut payload)?,
165        })
166    }
167}
168
169impl HelloMessage {
170    /// Starts a new `HelloMessageBuilder`
171    ///
172    /// ```
173    /// use reth_eth_wire::HelloMessage;
174    /// use reth_network_peers::pk2id;
175    /// use secp256k1::SecretKey;
176    /// let secret_key = SecretKey::new(&mut rand::rng());
177    /// let id = pk2id(&secret_key.public_key());
178    /// let status = HelloMessage::builder(id).build();
179    /// ```
180    pub const fn builder(id: PeerId) -> HelloMessageBuilder {
181        HelloMessageBuilder::new(id)
182    }
183}
184
185/// Builder for [`HelloMessageWithProtocols`]
186#[derive(Debug)]
187pub struct HelloMessageBuilder {
188    /// The version of the `p2p` protocol.
189    pub protocol_version: Option<ProtocolVersion>,
190    /// Specifies the client software identity, as a human-readable string (e.g.
191    /// "Ethereum(++)/1.0.0").
192    pub client_version: Option<String>,
193    /// The list of supported protocols.
194    pub protocols: Option<Vec<Protocol>>,
195    /// The port that the client is listening on, zero indicates the client is not listening.
196    pub port: Option<u16>,
197    /// The secp256k1 public key corresponding to the node's private key.
198    pub id: PeerId,
199}
200
201// === impl HelloMessageBuilder ===
202
203impl HelloMessageBuilder {
204    /// Create a new builder to configure a [`HelloMessage`]
205    pub const fn new(id: PeerId) -> Self {
206        Self { protocol_version: None, client_version: None, protocols: None, port: None, id }
207    }
208
209    /// Sets the port the client is listening on
210    pub const fn port(mut self, port: u16) -> Self {
211        self.port = Some(port);
212        self
213    }
214
215    /// Adds a new protocol to use.
216    pub fn protocol(mut self, protocols: impl Into<Protocol>) -> Self {
217        self.protocols.get_or_insert_with(Vec::new).push(protocols.into());
218        self
219    }
220
221    /// Sets protocols to use.
222    pub fn protocols(mut self, protocols: impl IntoIterator<Item = Protocol>) -> Self {
223        self.protocols.get_or_insert_with(Vec::new).extend(protocols);
224        self
225    }
226
227    /// Sets client version.
228    pub fn client_version(mut self, client_version: impl Into<String>) -> Self {
229        self.client_version = Some(client_version.into());
230        self
231    }
232
233    /// Sets protocol version.
234    pub const fn protocol_version(mut self, protocol_version: ProtocolVersion) -> Self {
235        self.protocol_version = Some(protocol_version);
236        self
237    }
238
239    /// Consumes the type and returns the configured [`HelloMessage`]
240    ///
241    /// Unset fields will be set to their default values:
242    /// - `protocol_version`: [`ProtocolVersion::V5`]
243    /// - `client_version`: [`RETH_CLIENT_VERSION`]
244    /// - `capabilities`: All [`EthVersion`]
245    pub fn build(self) -> HelloMessageWithProtocols {
246        let Self { protocol_version, client_version, protocols, port, id } = self;
247        HelloMessageWithProtocols {
248            protocol_version: protocol_version.unwrap_or_default(),
249            client_version: client_version.unwrap_or_else(|| RETH_CLIENT_VERSION.to_string()),
250            protocols: protocols.unwrap_or_else(|| {
251                EthVersion::ALL_VERSIONS.iter().copied().map(Into::into).collect()
252            }),
253            port: port.unwrap_or(DEFAULT_TCP_PORT),
254            id,
255        }
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use crate::{
262        p2pstream::P2PMessage, protocol::Protocol, Capability, EthVersion, HelloMessage,
263        HelloMessageWithProtocols, ProtocolVersion,
264    };
265    use alloy_rlp::{Decodable, Encodable, Header, EMPTY_STRING_CODE};
266    use reth_network_peers::pk2id;
267    use secp256k1::SecretKey;
268
269    #[test]
270    fn test_hello_encoding_round_trip() {
271        let secret_key = SecretKey::new(&mut rand::rng());
272        let id = pk2id(&secret_key.public_key());
273        let hello = P2PMessage::Hello(HelloMessage {
274            protocol_version: ProtocolVersion::V5,
275            client_version: "reth/0.1.0".to_string(),
276            capabilities: vec![Capability::new_static("eth", EthVersion::Eth67 as usize)],
277            port: 30303,
278            id,
279        });
280
281        let mut hello_encoded = Vec::new();
282        hello.encode(&mut hello_encoded);
283
284        let hello_decoded = P2PMessage::decode(&mut &hello_encoded[..]).unwrap();
285
286        assert_eq!(hello, hello_decoded);
287    }
288
289    #[test]
290    fn hello_encoding_length() {
291        let secret_key = SecretKey::new(&mut rand::rng());
292        let id = pk2id(&secret_key.public_key());
293        let hello = P2PMessage::Hello(HelloMessage {
294            protocol_version: ProtocolVersion::V5,
295            client_version: "reth/0.1.0".to_string(),
296            capabilities: vec![Capability::new_static("eth", EthVersion::Eth67 as usize)],
297            port: 30303,
298            id,
299        });
300
301        let mut hello_encoded = Vec::new();
302        hello.encode(&mut hello_encoded);
303
304        assert_eq!(hello_encoded.len(), hello.length());
305    }
306    //TODO: add test for eth70 here once we have fully support it
307
308    #[test]
309    fn test_default_protocols_still_include_eth69() {
310        // ensure that older eth/69 remains advertised for compatibility
311        let secret_key = SecretKey::new(&mut rand::rng());
312        let id = pk2id(&secret_key.public_key());
313        let hello = HelloMessageWithProtocols::builder(id).build();
314
315        let has_eth69 = hello
316            .protocols
317            .iter()
318            .any(|p| p.cap.name == "eth" && p.cap.version == EthVersion::Eth69 as usize);
319        assert!(has_eth69, "Default protocols should include Eth69");
320    }
321
322    #[test]
323    fn hello_message_id_prefix() {
324        // ensure that the hello message id is prefixed
325        let secret_key = SecretKey::new(&mut rand::rng());
326        let id = pk2id(&secret_key.public_key());
327        let hello = P2PMessage::Hello(HelloMessage {
328            protocol_version: ProtocolVersion::V5,
329            client_version: "reth/0.1.0".to_string(),
330            capabilities: vec![Capability::new_static("eth", EthVersion::Eth67 as usize)],
331            port: 30303,
332            id,
333        });
334
335        let mut hello_encoded = Vec::new();
336        hello.encode(&mut hello_encoded);
337
338        // zero is encoded as 0x80, the empty string code in RLP
339        assert_eq!(hello_encoded[0], EMPTY_STRING_CODE);
340    }
341
342    #[test]
343    fn hello_decode_ignores_extra_fields() {
344        // EIP-8: additional list elements must be ignored
345        let secret_key = SecretKey::new(&mut rand::rng());
346        let hello = HelloMessage {
347            protocol_version: ProtocolVersion::V5,
348            client_version: "reth/0.1.0".to_string(),
349            capabilities: vec![Capability::new_static("eth", EthVersion::Eth68 as usize)],
350            port: 30303,
351            id: pk2id(&secret_key.public_key()),
352        };
353
354        let mut payload = Vec::new();
355        hello.protocol_version.encode(&mut payload);
356        hello.client_version.encode(&mut payload);
357        hello.capabilities.encode(&mut payload);
358        hello.port.encode(&mut payload);
359        hello.id.encode(&mut payload);
360        42u8.encode(&mut payload);
361        "future".encode(&mut payload);
362
363        let mut encoded = Vec::new();
364        Header { list: true, payload_length: payload.len() }.encode(&mut encoded);
365        encoded.extend_from_slice(&payload);
366        encoded.push(0xff);
367
368        let mut buf = encoded.as_slice();
369        assert_eq!(HelloMessage::decode(&mut buf).unwrap(), hello);
370        assert_eq!(buf, [0xff]);
371    }
372
373    #[test]
374    fn set_eth_versions_keeps_other_capabilities() {
375        let id = pk2id(&SecretKey::new(&mut rand::rng()).public_key());
376        let mut hello = HelloMessageWithProtocols::builder(id).build().with_snap(true);
377        // An `eth` version reth doesn't know is replaced too.
378        hello.protocols.push(Protocol::new(Capability::new_static("eth", 99), 17));
379        hello.set_eth_versions([EthVersion::Eth70, EthVersion::Eth69]);
380
381        let caps: Vec<_> = hello.protocols.iter().map(|p| p.cap.clone()).collect();
382        assert_eq!(caps, [Capability::eth_70(), Capability::eth_69(), Capability::snap_2()]);
383    }
384}