Skip to main content

reth_eth_wire_types/
message.rs

1//! Implements Ethereum wire protocol for versions 66 through 73.
2//! Defines structs/enums for messages, request-response pairs, and broadcasts.
3//! Handles compatibility with [`EthVersion`].
4//!
5//! Examples include creating, encoding, and decoding protocol messages.
6//!
7//! Reference: [Ethereum Wire Protocol](https://github.com/ethereum/devp2p/blob/master/caps/eth.md).
8
9use super::{
10    broadcast::NewBlockHashes, BlockAccessLists, BlockBodies, BlockHeaders, GetBlockAccessLists,
11    GetBlockBodies, GetBlockHeaders, GetNodeData, GetPooledTransactions, GetReceipts,
12    GetReceipts70, NewPooledTransactionHashes66, NewPooledTransactionHashes68, NodeData,
13    PooledTransactions, Receipts, Status, StatusEth69, Transactions,
14};
15use crate::{
16    status::StatusMessage, BlockRangeUpdate, BroadcastPoolTransactions, CellMasks, Cells,
17    EthNetworkPrimitives, EthVersion, GetCells, NetworkPrimitives, NewPooledTransactionHashes72,
18    RawCapabilityMessage, Receipts69, Receipts70, SharedTransactions,
19};
20use alloc::{boxed::Box, string::String, sync::Arc};
21use alloy_primitives::{
22    bytes::{Buf, BufMut},
23    Bytes,
24};
25use alloy_rlp::{Decodable, Encodable, Header};
26use core::fmt::Debug;
27
28/// [`MAX_MESSAGE_SIZE`] is the maximum cap on the size of a protocol message.
29// https://github.com/ethereum/go-ethereum/blob/30602163d5d8321fbc68afdcbbaf2362b2641bde/eth/protocols/eth/protocol.go#L50
30pub const MAX_MESSAGE_SIZE: usize = 10 * 1024 * 1024;
31
32/// Multiplier applied to `max_message_size` to derive the in-memory budget for decoding
33/// `Transactions` and `PooledTransactions` messages.
34///
35/// Decoded transactions expand relative to their RLP encoding due to struct overhead and heap
36/// allocations. With many peers in flight this can cause significant memory pressure, so we
37/// stop decoding once the cumulative in-memory size of decoded transactions exceeds
38/// `max_message_size * TX_MEMORY_BUDGET_MULTIPLIER`. Remaining transactions are silently dropped.
39pub const TX_MEMORY_BUDGET_MULTIPLIER: usize = 2;
40
41/// Error when sending/receiving a message
42#[derive(thiserror::Error, Debug)]
43pub enum MessageError {
44    /// Flags an unrecognized message ID for a given protocol version.
45    #[error("message id {1:?} is invalid for version {0:?}")]
46    Invalid(EthVersion, EthMessageID),
47    /// Expected a Status message but received a different message type.
48    #[error("expected status message but received {0:?}")]
49    ExpectedStatusMessage(EthMessageID),
50    /// Thrown when rlp decoding a message failed.
51    #[error("RLP error: {0}")]
52    RlpError(#[from] alloy_rlp::Error),
53    /// Other message error with custom message
54    #[error("{0}")]
55    Other(String),
56}
57
58/// An `eth` protocol message, containing a message ID and payload.
59#[derive(Clone, Debug, PartialEq, Eq)]
60#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
61pub struct ProtocolMessage<N: NetworkPrimitives = EthNetworkPrimitives> {
62    /// The unique identifier representing the type of the Ethereum message.
63    pub message_type: EthMessageID,
64    /// The content of the message, including specific data based on the message type.
65    #[cfg_attr(
66        feature = "serde",
67        serde(bound = "EthMessage<N>: serde::Serialize + serde::de::DeserializeOwned")
68    )]
69    pub message: EthMessage<N>,
70}
71
72impl<N: NetworkPrimitives> ProtocolMessage<N> {
73    /// Decode only a Status message from RLP bytes.
74    ///
75    /// This is used during the eth handshake where only a Status message is a valid response.
76    /// Returns an error if the message is not a Status message.
77    pub fn decode_status(
78        version: EthVersion,
79        buf: &mut &[u8],
80    ) -> Result<StatusMessage, MessageError> {
81        let message_type = EthMessageID::decode(buf)?;
82
83        if message_type != EthMessageID::Status {
84            return Err(MessageError::ExpectedStatusMessage(message_type))
85        }
86
87        let status = if version < EthVersion::Eth69 {
88            StatusMessage::Legacy(Status::decode(buf)?)
89        } else {
90            StatusMessage::Eth69(StatusEth69::decode(buf)?)
91        };
92
93        Ok(status)
94    }
95
96    /// Create a new `ProtocolMessage` from a message type and message rlp bytes.
97    ///
98    /// This will enforce decoding according to the given [`EthVersion`] of the connection.
99    pub fn decode_message(version: EthVersion, buf: &mut &[u8]) -> Result<Self, MessageError> {
100        Self::decode_message_with_tx_memory_budget(version, buf, usize::MAX)
101    }
102
103    /// Like [`Self::decode_message`], but caps the cumulative in-memory size of decoded
104    /// transactions in `Transactions` and `PooledTransactions` messages. Once exceeded,
105    /// remaining transactions are silently dropped.
106    ///
107    /// Use [`TX_MEMORY_BUDGET_MULTIPLIER`] to derive a reasonable default.
108    pub fn decode_message_with_tx_memory_budget(
109        version: EthVersion,
110        buf: &mut &[u8],
111        tx_memory_budget: usize,
112    ) -> Result<Self, MessageError> {
113        let message_type = EthMessageID::decode(buf)?;
114
115        // For EIP-7642 (https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7642.md):
116        // pre-merge (legacy) status messages include total difficulty, whereas eth/69 omits it.
117        let message = match message_type {
118            EthMessageID::Status => EthMessage::Status(if version < EthVersion::Eth69 {
119                StatusMessage::Legacy(Status::decode(buf)?)
120            } else {
121                StatusMessage::Eth69(StatusEth69::decode(buf)?)
122            }),
123            EthMessageID::NewBlockHashes => {
124                EthMessage::NewBlockHashes(NewBlockHashes::decode(buf)?)
125            }
126            EthMessageID::NewBlock => {
127                EthMessage::NewBlock(Box::new(N::NewBlockPayload::decode(buf)?))
128            }
129            EthMessageID::Transactions => EthMessage::Transactions(
130                Transactions::decode_with_memory_budget(buf, tx_memory_budget)?,
131            ),
132            EthMessageID::NewPooledTransactionHashes => {
133                if version >= EthVersion::Eth72 {
134                    EthMessage::NewPooledTransactionHashes72(NewPooledTransactionHashes72::decode(
135                        buf,
136                    )?)
137                } else if version >= EthVersion::Eth68 {
138                    EthMessage::NewPooledTransactionHashes68(NewPooledTransactionHashes68::decode(
139                        buf,
140                    )?)
141                } else {
142                    EthMessage::NewPooledTransactionHashes66(NewPooledTransactionHashes66::decode(
143                        buf,
144                    )?)
145                }
146            }
147            EthMessageID::GetBlockHeaders => EthMessage::GetBlockHeaders(RequestPair::decode(buf)?),
148            EthMessageID::BlockHeaders => EthMessage::BlockHeaders(RequestPair::decode(buf)?),
149            EthMessageID::GetBlockBodies => EthMessage::GetBlockBodies(RequestPair::decode(buf)?),
150            EthMessageID::BlockBodies => EthMessage::BlockBodies(RequestPair::decode(buf)?),
151            EthMessageID::GetPooledTransactions => {
152                EthMessage::GetPooledTransactions(RequestPair::decode(buf)?)
153            }
154            EthMessageID::PooledTransactions => {
155                EthMessage::PooledTransactions(RequestPair::decode_with(buf, |buf| {
156                    if version >= EthVersion::Eth72 {
157                        PooledTransactions::decode_eth72_with_memory_budget(buf, tx_memory_budget)
158                    } else {
159                        PooledTransactions::decode_with_memory_budget(buf, tx_memory_budget)
160                    }
161                })?)
162            }
163            EthMessageID::GetNodeData => {
164                if version >= EthVersion::Eth67 {
165                    return Err(MessageError::Invalid(version, EthMessageID::GetNodeData))
166                }
167                EthMessage::GetNodeData(RequestPair::decode(buf)?)
168            }
169            EthMessageID::NodeData => {
170                if version >= EthVersion::Eth67 {
171                    return Err(MessageError::Invalid(version, EthMessageID::NodeData))
172                }
173                EthMessage::NodeData(RequestPair::decode(buf)?)
174            }
175            EthMessageID::GetReceipts => {
176                if version >= EthVersion::Eth70 {
177                    EthMessage::GetReceipts70(RequestPair::decode(buf)?)
178                } else {
179                    EthMessage::GetReceipts(RequestPair::decode(buf)?)
180                }
181            }
182            EthMessageID::Receipts => {
183                match version {
184                    v if v >= EthVersion::Eth70 => {
185                        // eth/70 continues to omit bloom filters and adds the
186                        // `lastBlockIncomplete` flag, encoded as
187                        // `[request-id, lastBlockIncomplete, [[receipt₁, receipt₂], ...]]`.
188                        EthMessage::Receipts70(RequestPair::decode(buf)?)
189                    }
190                    EthVersion::Eth69 => {
191                        // with eth69, receipts no longer include the bloom
192                        EthMessage::Receipts69(RequestPair::decode(buf)?)
193                    }
194                    _ => {
195                        // before eth69 we need to decode the bloom  as well
196                        EthMessage::Receipts(RequestPair::decode(buf)?)
197                    }
198                }
199            }
200            EthMessageID::BlockRangeUpdate => {
201                if version < EthVersion::Eth69 {
202                    return Err(MessageError::Invalid(version, EthMessageID::BlockRangeUpdate))
203                }
204                EthMessage::BlockRangeUpdate(BlockRangeUpdate::decode(buf)?)
205            }
206            EthMessageID::GetBlockAccessLists => {
207                if version < EthVersion::Eth71 {
208                    return Err(MessageError::Invalid(version, EthMessageID::GetBlockAccessLists))
209                }
210                EthMessage::GetBlockAccessLists(RequestPair::decode(buf)?)
211            }
212            EthMessageID::BlockAccessLists => {
213                if version < EthVersion::Eth71 {
214                    return Err(MessageError::Invalid(version, EthMessageID::BlockAccessLists))
215                }
216                EthMessage::BlockAccessLists(RequestPair::decode(buf)?)
217            }
218            EthMessageID::Cells => EthMessage::Cells(RequestPair::<Cells>::decode_cells(
219                version,
220                message_type,
221                buf,
222                |cells| &cells.cell_mask,
223            )?),
224            EthMessageID::GetCells => EthMessage::GetCells(RequestPair::<GetCells>::decode_cells(
225                version,
226                message_type,
227                buf,
228                |request| &request.cell_mask,
229            )?),
230            EthMessageID::Other(_) => {
231                let raw_payload = Bytes::copy_from_slice(buf);
232                buf.advance(raw_payload.len());
233                EthMessage::Other(RawCapabilityMessage::new(
234                    message_type.to_u8() as usize,
235                    raw_payload.into(),
236                ))
237            }
238        };
239        Ok(Self { message_type, message })
240    }
241}
242
243impl<N: NetworkPrimitives> Encodable for ProtocolMessage<N> {
244    /// Encodes the protocol message into bytes. The message type is encoded as a single byte and
245    /// prepended to the message.
246    fn encode(&self, out: &mut dyn BufMut) {
247        self.message_type.encode(out);
248        self.message.encode(out);
249    }
250    fn length(&self) -> usize {
251        self.message_type.length() + self.message.length()
252    }
253}
254
255impl<N: NetworkPrimitives> From<EthMessage<N>> for ProtocolMessage<N> {
256    fn from(message: EthMessage<N>) -> Self {
257        Self { message_type: message.message_id(), message }
258    }
259}
260
261/// Represents messages that can be sent to multiple peers.
262#[derive(Clone, Debug)]
263pub struct ProtocolBroadcastMessage<N: NetworkPrimitives = EthNetworkPrimitives> {
264    /// The unique identifier representing the type of the Ethereum message.
265    pub message_type: EthMessageID,
266    /// The content of the message to be broadcasted, including specific data based on the message
267    /// type.
268    pub message: EthBroadcastMessage<N>,
269}
270
271impl<N: NetworkPrimitives> Encodable for ProtocolBroadcastMessage<N> {
272    /// Encodes the protocol message into bytes. The message type is encoded as a single byte and
273    /// prepended to the message.
274    fn encode(&self, out: &mut dyn BufMut) {
275        self.message_type.encode(out);
276        self.message.encode(out);
277    }
278    fn length(&self) -> usize {
279        self.message_type.length() + self.message.length()
280    }
281}
282
283impl<N: NetworkPrimitives> From<EthBroadcastMessage<N>> for ProtocolBroadcastMessage<N> {
284    fn from(message: EthBroadcastMessage<N>) -> Self {
285        Self { message_type: message.message_id(), message }
286    }
287}
288
289/// Represents a message in the eth wire protocol, versions 66, 67, 68 and 69.
290///
291/// The ethereum wire protocol is a set of messages that are broadcast to the network in two
292/// styles:
293///  * A request message sent by a peer (such as [`GetPooledTransactions`]), and an associated
294///    response message (such as [`PooledTransactions`]).
295///  * A message that is broadcast to the network, without a corresponding request.
296///
297/// The newer `eth/66` is an efficiency upgrade on top of `eth/65`, introducing a request id to
298/// correlate request-response message pairs. This allows for request multiplexing.
299///
300/// The `eth/67` is based on `eth/66` but only removes two messages, [`GetNodeData`] and
301/// [`NodeData`].
302///
303/// The `eth/68` changes only `NewPooledTransactionHashes` to include `types` and `sized`. For
304/// it, `NewPooledTransactionHashes` is renamed as [`NewPooledTransactionHashes66`] and
305/// [`NewPooledTransactionHashes68`] is defined.
306///
307/// The `eth/69` announces the historical block range served by the node. Removes total difficulty
308/// information. And removes the Bloom field from receipts transferred over the protocol.
309///
310/// The `eth/70` (EIP-7975) keeps the eth/69 status format and introduces partial receipts.
311/// requests/responses.
312///
313/// The `eth/71` draft extends eth/70 with block access list request/response messages.
314#[derive(Clone, Debug, PartialEq, Eq)]
315#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
316pub enum EthMessage<N: NetworkPrimitives = EthNetworkPrimitives> {
317    /// Represents a Status message required for the protocol handshake.
318    Status(StatusMessage),
319    /// Represents a `NewBlockHashes` message broadcast to the network.
320    NewBlockHashes(NewBlockHashes),
321    /// Represents a `NewBlock` message broadcast to the network.
322    #[cfg_attr(
323        feature = "serde",
324        serde(bound = "N::NewBlockPayload: serde::Serialize + serde::de::DeserializeOwned")
325    )]
326    NewBlock(Box<N::NewBlockPayload>),
327    /// Represents a Transactions message broadcast to the network.
328    #[cfg_attr(
329        feature = "serde",
330        serde(bound = "N::BroadcastedTransaction: serde::Serialize + serde::de::DeserializeOwned")
331    )]
332    Transactions(Transactions<N::BroadcastedTransaction>),
333    /// Represents a `NewPooledTransactionHashes` message for eth/66 version.
334    NewPooledTransactionHashes66(NewPooledTransactionHashes66),
335    /// Represents a `NewPooledTransactionHashes` message for eth/68 version.
336    NewPooledTransactionHashes68(NewPooledTransactionHashes68),
337    /// Represents a `NewPooledTransactionHashes` message for eth/72 version.
338    NewPooledTransactionHashes72(NewPooledTransactionHashes72),
339
340    // The following messages are request-response message pairs
341    /// Represents a `GetBlockHeaders` request-response pair.
342    GetBlockHeaders(RequestPair<GetBlockHeaders>),
343    /// Represents a `BlockHeaders` request-response pair.
344    #[cfg_attr(
345        feature = "serde",
346        serde(bound = "N::BlockHeader: serde::Serialize + serde::de::DeserializeOwned")
347    )]
348    BlockHeaders(RequestPair<BlockHeaders<N::BlockHeader>>),
349    /// Represents a `GetBlockBodies` request-response pair.
350    GetBlockBodies(RequestPair<GetBlockBodies>),
351    /// Represents a `BlockBodies` request-response pair.
352    #[cfg_attr(
353        feature = "serde",
354        serde(bound = "N::BlockBody: serde::Serialize + serde::de::DeserializeOwned")
355    )]
356    BlockBodies(RequestPair<BlockBodies<N::BlockBody>>),
357    /// Represents a `GetPooledTransactions` request-response pair.
358    GetPooledTransactions(RequestPair<GetPooledTransactions>),
359    /// Represents a `PooledTransactions` request-response pair.
360    #[cfg_attr(
361        feature = "serde",
362        serde(bound = "N::PooledTransaction: serde::Serialize + serde::de::DeserializeOwned")
363    )]
364    PooledTransactions(RequestPair<PooledTransactions<N::PooledTransaction>>),
365    /// Represents a `GetNodeData` request-response pair.
366    GetNodeData(RequestPair<GetNodeData>),
367    /// Represents a `NodeData` request-response pair.
368    NodeData(RequestPair<NodeData>),
369    /// Represents a `GetReceipts` request-response pair.
370    GetReceipts(RequestPair<GetReceipts>),
371    /// Represents a `GetReceipts` request for eth/70.
372    ///
373    /// Note: Unlike earlier protocol versions, the eth/70 encoding for
374    /// `GetReceipts` in EIP-7975 inlines the request id. The type still wraps
375    /// a [`RequestPair`], but with a custom inline encoding.
376    GetReceipts70(RequestPair<GetReceipts70>),
377    /// Represents a `GetBlockAccessLists` request-response pair for eth/71.
378    GetBlockAccessLists(RequestPair<GetBlockAccessLists>),
379    /// Represents a Receipts request-response pair.
380    #[cfg_attr(
381        feature = "serde",
382        serde(bound = "N::Receipt: serde::Serialize + serde::de::DeserializeOwned")
383    )]
384    Receipts(RequestPair<Receipts<N::Receipt>>),
385    /// Represents a Receipts request-response pair for eth/69.
386    #[cfg_attr(
387        feature = "serde",
388        serde(bound = "N::Receipt: serde::Serialize + serde::de::DeserializeOwned")
389    )]
390    Receipts69(RequestPair<Receipts69<N::Receipt>>),
391    /// Represents a Receipts request-response pair for eth/70.
392    #[cfg_attr(
393        feature = "serde",
394        serde(bound = "N::Receipt: serde::Serialize + serde::de::DeserializeOwned")
395    )]
396    ///
397    /// Note: The eth/70 encoding for `Receipts` in EIP-7975 inlines the
398    /// request id. The type still wraps a [`RequestPair`], but with a custom
399    /// inline encoding.
400    Receipts70(RequestPair<Receipts70<N::Receipt>>),
401    /// Represents a `BlockAccessLists` request-response pair for eth/71.
402    BlockAccessLists(RequestPair<BlockAccessLists>),
403    /// Represents shared (eth/72+) or indexed (eth/73+) cells.
404    Cells(RequestPair<Cells>),
405    /// Represents a shared (eth/72+) or indexed (eth/73+) cell request.
406    GetCells(RequestPair<GetCells>),
407    /// Represents a `BlockRangeUpdate` message broadcast to the network.
408    #[cfg_attr(
409        feature = "serde",
410        serde(bound = "N::BroadcastedTransaction: serde::Serialize + serde::de::DeserializeOwned")
411    )]
412    BlockRangeUpdate(BlockRangeUpdate),
413    /// Represents an encoded message that doesn't match any other variant
414    Other(RawCapabilityMessage),
415}
416
417impl<N: NetworkPrimitives> EthMessage<N> {
418    /// Returns the message's ID.
419    pub const fn message_id(&self) -> EthMessageID {
420        match self {
421            Self::Status(_) => EthMessageID::Status,
422            Self::NewBlockHashes(_) => EthMessageID::NewBlockHashes,
423            Self::NewBlock(_) => EthMessageID::NewBlock,
424            Self::Transactions(_) => EthMessageID::Transactions,
425            Self::NewPooledTransactionHashes66(_) |
426            Self::NewPooledTransactionHashes68(_) |
427            Self::NewPooledTransactionHashes72(_) => EthMessageID::NewPooledTransactionHashes,
428            Self::GetBlockHeaders(_) => EthMessageID::GetBlockHeaders,
429            Self::BlockHeaders(_) => EthMessageID::BlockHeaders,
430            Self::GetBlockBodies(_) => EthMessageID::GetBlockBodies,
431            Self::BlockBodies(_) => EthMessageID::BlockBodies,
432            Self::GetPooledTransactions(_) => EthMessageID::GetPooledTransactions,
433            Self::PooledTransactions(_) => EthMessageID::PooledTransactions,
434            Self::GetNodeData(_) => EthMessageID::GetNodeData,
435            Self::NodeData(_) => EthMessageID::NodeData,
436            Self::GetReceipts(_) | Self::GetReceipts70(_) => EthMessageID::GetReceipts,
437            Self::Receipts(_) | Self::Receipts69(_) | Self::Receipts70(_) => EthMessageID::Receipts,
438            Self::BlockRangeUpdate(_) => EthMessageID::BlockRangeUpdate,
439            Self::GetBlockAccessLists(_) => EthMessageID::GetBlockAccessLists,
440            Self::BlockAccessLists(_) => EthMessageID::BlockAccessLists,
441            Self::Cells(_) => EthMessageID::Cells,
442            Self::GetCells(_) => EthMessageID::GetCells,
443            Self::Other(msg) => EthMessageID::Other(msg.id as u8),
444        }
445    }
446
447    /// Returns true if the message variant is a request.
448    pub const fn is_request(&self) -> bool {
449        matches!(
450            self,
451            Self::GetBlockBodies(_) |
452                Self::GetBlockHeaders(_) |
453                Self::GetReceipts(_) |
454                Self::GetReceipts70(_) |
455                Self::GetBlockAccessLists(_) |
456                Self::GetCells(_) |
457                Self::GetPooledTransactions(_) |
458                Self::GetNodeData(_)
459        )
460    }
461
462    /// Returns true if the message variant is a response to a request.
463    pub const fn is_response(&self) -> bool {
464        matches!(
465            self,
466            Self::PooledTransactions(_) |
467                Self::Receipts(_) |
468                Self::Receipts69(_) |
469                Self::Receipts70(_) |
470                Self::BlockAccessLists(_) |
471                Self::BlockHeaders(_) |
472                Self::BlockBodies(_) |
473                Self::NodeData(_) |
474                Self::Cells(_)
475        )
476    }
477}
478
479impl<N: NetworkPrimitives> Encodable for EthMessage<N> {
480    fn encode(&self, out: &mut dyn BufMut) {
481        match self {
482            Self::Status(status) => status.encode(out),
483            Self::NewBlockHashes(new_block_hashes) => new_block_hashes.encode(out),
484            Self::NewBlock(new_block) => new_block.encode(out),
485            Self::Transactions(transactions) => transactions.encode(out),
486            Self::NewPooledTransactionHashes66(hashes) => hashes.encode(out),
487            Self::NewPooledTransactionHashes68(hashes) => hashes.encode(out),
488            Self::NewPooledTransactionHashes72(hashes) => hashes.encode(out),
489            Self::GetBlockHeaders(request) => request.encode(out),
490            Self::BlockHeaders(headers) => headers.encode(out),
491            Self::GetBlockBodies(request) => request.encode(out),
492            Self::BlockBodies(bodies) => bodies.encode(out),
493            Self::GetPooledTransactions(request) => request.encode(out),
494            Self::PooledTransactions(transactions) => transactions.encode(out),
495            Self::GetNodeData(request) => request.encode(out),
496            Self::NodeData(data) => data.encode(out),
497            Self::GetReceipts(request) => request.encode(out),
498            Self::GetReceipts70(request) => request.encode(out),
499            Self::GetBlockAccessLists(request) => request.encode(out),
500            Self::GetCells(request) => request.encode(out),
501            Self::Receipts(receipts) => receipts.encode(out),
502            Self::Receipts69(receipt69) => receipt69.encode(out),
503            Self::Receipts70(receipt70) => receipt70.encode(out),
504            Self::BlockAccessLists(block_access_lists) => block_access_lists.encode(out),
505            Self::BlockRangeUpdate(block_range_update) => block_range_update.encode(out),
506            Self::Cells(cells) => cells.encode(out),
507            Self::Other(unknown) => out.put_slice(&unknown.payload),
508        }
509    }
510    fn length(&self) -> usize {
511        match self {
512            Self::Status(status) => status.length(),
513            Self::NewBlockHashes(new_block_hashes) => new_block_hashes.length(),
514            Self::NewBlock(new_block) => new_block.length(),
515            Self::Transactions(transactions) => transactions.length(),
516            Self::NewPooledTransactionHashes66(hashes) => hashes.length(),
517            Self::NewPooledTransactionHashes68(hashes) => hashes.length(),
518            Self::NewPooledTransactionHashes72(hashes) => hashes.length(),
519            Self::GetBlockHeaders(request) => request.length(),
520            Self::BlockHeaders(headers) => headers.length(),
521            Self::GetBlockBodies(request) => request.length(),
522            Self::BlockBodies(bodies) => bodies.length(),
523            Self::GetPooledTransactions(request) => request.length(),
524            Self::PooledTransactions(transactions) => transactions.length(),
525            Self::GetNodeData(request) => request.length(),
526            Self::NodeData(data) => data.length(),
527            Self::GetReceipts(request) => request.length(),
528            Self::GetReceipts70(request) => request.length(),
529            Self::GetBlockAccessLists(request) => request.length(),
530            Self::GetCells(request) => request.length(),
531            Self::Receipts(receipts) => receipts.length(),
532            Self::Receipts69(receipt69) => receipt69.length(),
533            Self::Receipts70(receipt70) => receipt70.length(),
534            Self::BlockAccessLists(block_access_lists) => block_access_lists.length(),
535            Self::BlockRangeUpdate(block_range_update) => block_range_update.length(),
536            Self::Cells(cells) => cells.length(),
537            Self::Other(unknown) => unknown.payload.len(),
538        }
539    }
540}
541
542/// Represents broadcast messages of [`EthMessage`] with the same object that can be sent to
543/// multiple peers.
544///
545/// Messages that contain a list of hashes depend on the peer the message is sent to. A peer should
546/// never receive a hash of an object (block, transaction) it has already seen.
547///
548/// Note: This is only useful for outgoing messages.
549#[derive(Clone, Debug)]
550pub enum EthBroadcastMessage<N: NetworkPrimitives = EthNetworkPrimitives> {
551    /// Represents a new block broadcast message.
552    NewBlock(Arc<N::NewBlockPayload>),
553    /// Represents a transactions broadcast message.
554    Transactions(SharedTransactions<N::BroadcastedTransaction>),
555    /// Represents cached outbound pool transactions broadcast message.
556    BroadcastPoolTransactions(BroadcastPoolTransactions),
557}
558
559// === impl EthBroadcastMessage ===
560
561impl<N: NetworkPrimitives> EthBroadcastMessage<N> {
562    /// Returns the message's ID.
563    pub const fn message_id(&self) -> EthMessageID {
564        match self {
565            Self::NewBlock(_) => EthMessageID::NewBlock,
566            Self::Transactions(_) | Self::BroadcastPoolTransactions(_) => {
567                EthMessageID::Transactions
568            }
569        }
570    }
571
572    /// Encodes this broadcast to its id-prefixed `RLPx` message bytes.
573    pub fn encoded(self) -> alloy_primitives::bytes::Bytes {
574        alloy_rlp::encode(ProtocolBroadcastMessage::from(self)).into()
575    }
576}
577
578impl<N: NetworkPrimitives> Encodable for EthBroadcastMessage<N> {
579    fn encode(&self, out: &mut dyn BufMut) {
580        match self {
581            Self::NewBlock(new_block) => new_block.encode(out),
582            Self::Transactions(transactions) => transactions.encode(out),
583            Self::BroadcastPoolTransactions(transactions) => transactions.encode(out),
584        }
585    }
586
587    fn length(&self) -> usize {
588        match self {
589            Self::NewBlock(new_block) => new_block.length(),
590            Self::Transactions(transactions) => transactions.length(),
591            Self::BroadcastPoolTransactions(transactions) => transactions.length(),
592        }
593    }
594}
595
596/// Represents message IDs for eth protocol messages.
597#[repr(u8)]
598#[derive(Clone, Copy, Debug, PartialEq, Eq)]
599#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
600pub enum EthMessageID {
601    /// Status message.
602    Status = 0x00,
603    /// New block hashes message.
604    NewBlockHashes = 0x01,
605    /// Transactions message.
606    Transactions = 0x02,
607    /// Get block headers message.
608    GetBlockHeaders = 0x03,
609    /// Block headers message.
610    BlockHeaders = 0x04,
611    /// Get block bodies message.
612    GetBlockBodies = 0x05,
613    /// Block bodies message.
614    BlockBodies = 0x06,
615    /// New block message.
616    NewBlock = 0x07,
617    /// New pooled transaction hashes message.
618    NewPooledTransactionHashes = 0x08,
619    /// Requests pooled transactions.
620    GetPooledTransactions = 0x09,
621    /// Represents pooled transactions.
622    PooledTransactions = 0x0a,
623    /// Requests node data.
624    GetNodeData = 0x0d,
625    /// Represents node data.
626    NodeData = 0x0e,
627    /// Requests receipts.
628    GetReceipts = 0x0f,
629    /// Represents receipts.
630    Receipts = 0x10,
631    /// Block range update.
632    ///
633    /// Introduced in Eth69
634    BlockRangeUpdate = 0x11,
635    /// Requests block access lists.
636    ///
637    /// Introduced in Eth71
638    GetBlockAccessLists = 0x12,
639    /// Represents block access lists.
640    ///
641    /// Introduced in Eth71
642    BlockAccessLists = 0x13,
643
644    /// Requests cells.
645    ///
646    /// Introduced in Eth72
647    GetCells = 0x14,
648    /// Represents Cells
649    ///
650    /// Introduced in Eth72
651    Cells = 0x15,
652    /// Represents unknown message types.
653    Other(u8),
654}
655
656impl EthMessageID {
657    /// Returns the corresponding `u8` value for an `EthMessageID`.
658    pub const fn to_u8(&self) -> u8 {
659        match self {
660            Self::Status => 0x00,
661            Self::NewBlockHashes => 0x01,
662            Self::Transactions => 0x02,
663            Self::GetBlockHeaders => 0x03,
664            Self::BlockHeaders => 0x04,
665            Self::GetBlockBodies => 0x05,
666            Self::BlockBodies => 0x06,
667            Self::NewBlock => 0x07,
668            Self::NewPooledTransactionHashes => 0x08,
669            Self::GetPooledTransactions => 0x09,
670            Self::PooledTransactions => 0x0a,
671            Self::GetNodeData => 0x0d,
672            Self::NodeData => 0x0e,
673            Self::GetReceipts => 0x0f,
674            Self::Receipts => 0x10,
675            Self::BlockRangeUpdate => 0x11,
676            Self::GetBlockAccessLists => 0x12,
677            Self::BlockAccessLists => 0x13,
678            Self::GetCells => 0x14,
679            Self::Cells => 0x15,
680            Self::Other(value) => *value, // Return the stored `u8`
681        }
682    }
683
684    /// Returns the max value for the given version.
685    pub const fn max(version: EthVersion) -> u8 {
686        if version.is_eth72_or_newer() {
687            Self::Cells.to_u8()
688        } else if version.is_eth71() {
689            Self::BlockAccessLists.to_u8()
690        } else if version.is_eth69_or_newer() {
691            Self::BlockRangeUpdate.to_u8()
692        } else {
693            Self::Receipts.to_u8()
694        }
695    }
696
697    /// Returns the total number of message types for the given version.
698    ///
699    /// This is used for message ID multiplexing.
700    ///
701    /// <https://github.com/ethereum/go-ethereum/blob/85077be58edea572f29c3b1a6a055077f1a56a8b/eth/protocols/eth/protocol.go#L45-L47>
702    pub const fn message_count(version: EthVersion) -> u8 {
703        Self::max(version) + 1
704    }
705}
706
707impl Encodable for EthMessageID {
708    fn encode(&self, out: &mut dyn BufMut) {
709        out.put_u8(self.to_u8());
710    }
711    fn length(&self) -> usize {
712        1
713    }
714}
715
716impl Decodable for EthMessageID {
717    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
718        let id = match buf.first().ok_or(alloy_rlp::Error::InputTooShort)? {
719            0x00 => Self::Status,
720            0x01 => Self::NewBlockHashes,
721            0x02 => Self::Transactions,
722            0x03 => Self::GetBlockHeaders,
723            0x04 => Self::BlockHeaders,
724            0x05 => Self::GetBlockBodies,
725            0x06 => Self::BlockBodies,
726            0x07 => Self::NewBlock,
727            0x08 => Self::NewPooledTransactionHashes,
728            0x09 => Self::GetPooledTransactions,
729            0x0a => Self::PooledTransactions,
730            0x0d => Self::GetNodeData,
731            0x0e => Self::NodeData,
732            0x0f => Self::GetReceipts,
733            0x10 => Self::Receipts,
734            0x11 => Self::BlockRangeUpdate,
735            0x12 => Self::GetBlockAccessLists,
736            0x13 => Self::BlockAccessLists,
737            0x14 => Self::GetCells,
738            0x15 => Self::Cells,
739            unknown => Self::Other(*unknown),
740        };
741        buf.advance(1);
742        Ok(id)
743    }
744}
745
746impl TryFrom<usize> for EthMessageID {
747    type Error = &'static str;
748
749    fn try_from(value: usize) -> Result<Self, Self::Error> {
750        match value {
751            0x00 => Ok(Self::Status),
752            0x01 => Ok(Self::NewBlockHashes),
753            0x02 => Ok(Self::Transactions),
754            0x03 => Ok(Self::GetBlockHeaders),
755            0x04 => Ok(Self::BlockHeaders),
756            0x05 => Ok(Self::GetBlockBodies),
757            0x06 => Ok(Self::BlockBodies),
758            0x07 => Ok(Self::NewBlock),
759            0x08 => Ok(Self::NewPooledTransactionHashes),
760            0x09 => Ok(Self::GetPooledTransactions),
761            0x0a => Ok(Self::PooledTransactions),
762            0x0d => Ok(Self::GetNodeData),
763            0x0e => Ok(Self::NodeData),
764            0x0f => Ok(Self::GetReceipts),
765            0x10 => Ok(Self::Receipts),
766            0x11 => Ok(Self::BlockRangeUpdate),
767            0x12 => Ok(Self::GetBlockAccessLists),
768            0x13 => Ok(Self::BlockAccessLists),
769            0x14 => Ok(Self::GetCells),
770            0x15 => Ok(Self::Cells),
771            _ => Err("Invalid message ID"),
772        }
773    }
774}
775
776/// This is used for all request-response style `eth` protocol messages.
777/// This can represent either a request or a response, since both include a message payload and
778/// request id.
779#[derive(Clone, Debug, PartialEq, Eq)]
780#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
781#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
782pub struct RequestPair<T> {
783    /// id for the contained request or response message
784    pub request_id: u64,
785
786    /// the request or response message payload
787    pub message: T,
788}
789
790impl<T> RequestPair<T> {
791    /// Converts the message type with the given closure.
792    pub fn map<F, R>(self, f: F) -> RequestPair<R>
793    where
794        F: FnOnce(T) -> R,
795    {
796        let Self { request_id, message } = self;
797        RequestPair { request_id, message: f(message) }
798    }
799
800    /// Decodes the request id and then decodes the message payload using `decode_msg`.
801    pub fn decode_with<F>(buf: &mut &[u8], decode_msg: F) -> alloy_rlp::Result<Self>
802    where
803        F: FnOnce(&mut &[u8]) -> alloy_rlp::Result<T>,
804    {
805        let header = Header::decode(buf)?;
806        if !header.list {
807            return Err(alloy_rlp::Error::UnexpectedString)
808        }
809
810        let (mut payload, remaining) = buf.split_at(header.payload_length);
811        let request_id = u64::decode(&mut payload)?;
812        let message = decode_msg(&mut payload)?;
813        if !payload.is_empty() {
814            return Err(alloy_rlp::Error::UnexpectedLength)
815        }
816
817        *buf = remaining;
818        Ok(Self { request_id, message })
819    }
820}
821
822/// Allows messages with request ids to be serialized into RLP bytes.
823impl<T> Encodable for RequestPair<T>
824where
825    T: Encodable,
826{
827    fn encode(&self, out: &mut dyn alloy_rlp::BufMut) {
828        let header =
829            Header { list: true, payload_length: self.request_id.length() + self.message.length() };
830
831        header.encode(out);
832        self.request_id.encode(out);
833        self.message.encode(out);
834    }
835
836    fn length(&self) -> usize {
837        let payload_length = self.request_id.length() + self.message.length();
838        Header { list: true, payload_length }.length_with_payload()
839    }
840}
841
842impl<T: Decodable> RequestPair<T> {
843    /// Decodes a cell message using its negotiated version and mask form.
844    fn decode_cells(
845        version: EthVersion,
846        id: EthMessageID,
847        buf: &mut &[u8],
848        cell_mask: fn(&T) -> &CellMasks,
849    ) -> Result<Self, MessageError> {
850        if version < EthVersion::Eth72 {
851            return Err(MessageError::Invalid(version, id))
852        }
853        let pair = Self::decode(buf)?;
854        if version == EthVersion::Eth72 && cell_mask(&pair.message).is_indexed() {
855            return Err(MessageError::Invalid(version, id))
856        }
857        Ok(pair)
858    }
859}
860
861/// Allows messages with request ids to be deserialized into RLP bytes.
862impl<T> Decodable for RequestPair<T>
863where
864    T: Decodable,
865{
866    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
867        Self::decode_with(buf, T::decode)
868    }
869}
870
871#[cfg(test)]
872mod tests {
873    use super::MessageError;
874    use crate::{
875        message::RequestPair, BlockAccessLists, Cells, EthMessage, EthMessageID,
876        EthNetworkPrimitives, EthVersion, GetBlockAccessLists, GetCells, GetNodeData, NodeData,
877        PooledTransactions, ProtocolMessage, RawCapabilityMessage, Status, StatusMessage,
878    };
879    use alloy_consensus::{SignableTransaction, TxEip4844, TxEip4844WithSidecar};
880    use alloy_eips::{
881        eip4844::{Blob, Bytes48},
882        eip7594::{BlobTransactionSidecarEip7594, Cell},
883    };
884    use alloy_hardforks::{ForkHash, ForkId};
885    use alloy_primitives::{hex, keccak256, Signature, B128, B256, U256};
886    use alloy_rlp::{Decodable, Encodable, Error, Header};
887    use reth_ethereum_primitives::{BlockBody, PooledTransactionVariant};
888
889    fn encode<T: Encodable>(value: T) -> Vec<u8> {
890        let mut buf = vec![];
891        value.encode(&mut buf);
892        buf
893    }
894
895    #[test]
896    fn test_removed_message_at_eth67() {
897        let get_node_data = EthMessage::<EthNetworkPrimitives>::GetNodeData(RequestPair {
898            request_id: 1337,
899            message: GetNodeData(vec![]),
900        });
901        let buf = encode(ProtocolMessage {
902            message_type: EthMessageID::GetNodeData,
903            message: get_node_data,
904        });
905        let msg = ProtocolMessage::<EthNetworkPrimitives>::decode_message(
906            crate::EthVersion::Eth67,
907            &mut &buf[..],
908        );
909        assert!(matches!(msg, Err(MessageError::Invalid(..))));
910
911        let node_data = EthMessage::<EthNetworkPrimitives>::NodeData(RequestPair {
912            request_id: 1337,
913            message: NodeData(vec![]),
914        });
915        let buf =
916            encode(ProtocolMessage { message_type: EthMessageID::NodeData, message: node_data });
917        let msg = ProtocolMessage::<EthNetworkPrimitives>::decode_message(
918            crate::EthVersion::Eth67,
919            &mut &buf[..],
920        );
921        assert!(matches!(msg, Err(MessageError::Invalid(..))));
922    }
923
924    #[test]
925    fn test_bal_message_version_gating() {
926        let get_block_access_lists =
927            EthMessage::<EthNetworkPrimitives>::GetBlockAccessLists(RequestPair {
928                request_id: 1337,
929                message: GetBlockAccessLists(vec![]),
930            });
931        let buf = encode(ProtocolMessage {
932            message_type: EthMessageID::GetBlockAccessLists,
933            message: get_block_access_lists,
934        });
935        let msg = ProtocolMessage::<EthNetworkPrimitives>::decode_message(
936            EthVersion::Eth70,
937            &mut &buf[..],
938        );
939        assert!(matches!(
940            msg,
941            Err(MessageError::Invalid(EthVersion::Eth70, EthMessageID::GetBlockAccessLists))
942        ));
943
944        let block_access_lists =
945            EthMessage::<EthNetworkPrimitives>::BlockAccessLists(RequestPair {
946                request_id: 1337,
947                message: BlockAccessLists(vec![]),
948            });
949        let buf = encode(ProtocolMessage {
950            message_type: EthMessageID::BlockAccessLists,
951            message: block_access_lists,
952        });
953        let msg = ProtocolMessage::<EthNetworkPrimitives>::decode_message(
954            EthVersion::Eth70,
955            &mut &buf[..],
956        );
957        assert!(matches!(
958            msg,
959            Err(MessageError::Invalid(EthVersion::Eth70, EthMessageID::BlockAccessLists))
960        ));
961    }
962
963    #[test]
964    fn test_bal_message_eth71_roundtrip() {
965        let msg = ProtocolMessage::from(EthMessage::<EthNetworkPrimitives>::GetBlockAccessLists(
966            RequestPair { request_id: 42, message: GetBlockAccessLists(vec![]) },
967        ));
968        let encoded = encode(msg.clone());
969        let decoded = ProtocolMessage::<EthNetworkPrimitives>::decode_message(
970            EthVersion::Eth71,
971            &mut &encoded[..],
972        )
973        .unwrap();
974
975        assert_eq!(decoded, msg);
976    }
977
978    #[test]
979    fn eth72_cell_packets_match_geth_vectors() {
980        // Generated with Geth 24b38e763fdd7dee8b91007d5f1a94cd21c9a7f0.
981        let mask = B128::from((1u128 | (1 << 8) | (1 << 127)).to_le_bytes());
982        let hash =
983            B256::from(hex!("0000000000000000000000000000000000000000000000000000000000001234"));
984        let request = EthMessage::<EthNetworkPrimitives>::GetCells(RequestPair {
985            request_id: 42,
986            message: GetCells { hashes: vec![hash], cell_mask: mask.into() },
987        });
988        let empty = EthMessage::Cells(RequestPair {
989            request_id: 42,
990            message: Cells { cell_mask: mask.into(), ..Default::default() },
991        });
992        assert_eq!(alloy_rlp::encode(&request), hex!("f42ae1a000000000000000000000000000000000000000000000000000000000000012349001010000000000000000000000000080"));
993        assert_eq!(alloy_rlp::encode(&empty), hex!("d42ac0c09001010000000000000000000000000080"));
994        let mut cell = Cell::default();
995        cell[0] = 1;
996        cell[2047] = 2;
997        let response = EthMessage::Cells(RequestPair {
998            request_id: 42,
999            message: Cells {
1000                hashes: vec![hash],
1001                cells: vec![vec![cell; 3]],
1002                cell_mask: mask.into(),
1003            },
1004        });
1005        let encoded = alloy_rlp::encode(&response);
1006        assert_eq!(encoded.len(), 6214);
1007        assert_eq!(
1008            keccak256(&encoded),
1009            B256::from(hex!("72c2afa3c896b0666ae473f075c1fc48133563f4bc8d22f7c1abb2aaf215dc3f"))
1010        );
1011        for message in [request, empty, response] {
1012            let encoded = alloy_rlp::encode(&message);
1013            assert_eq!(encoded.len(), message.length());
1014            let mut packet = vec![message.message_id().to_u8()];
1015            packet.extend_from_slice(&encoded);
1016            for version in [EthVersion::Eth72, EthVersion::Eth73] {
1017                let mut input = packet.as_slice();
1018                assert_eq!(
1019                    ProtocolMessage::decode_message(version, &mut input).unwrap().message,
1020                    message
1021                );
1022                assert!(input.is_empty());
1023            }
1024            let err = ProtocolMessage::<EthNetworkPrimitives>::decode_message(
1025                EthVersion::Eth71,
1026                &mut packet.as_slice(),
1027            )
1028            .unwrap_err();
1029            assert!(
1030                matches!(err, MessageError::Invalid(EthVersion::Eth71, id) if id == message.message_id())
1031            );
1032        }
1033    }
1034
1035    #[test]
1036    fn eth72_cell_packets_reject_nested_fields() {
1037        // The layout before EIP-8070 fixed it: `[request_id, [fields...]]`.
1038        let nested = |fields: &dyn Encodable| {
1039            let inner = Header { list: true, payload_length: fields.length() };
1040            let mut packet = Vec::new();
1041            Header { list: true, payload_length: 42u64.length() + inner.length_with_payload() }
1042                .encode(&mut packet);
1043            42u64.encode(&mut packet);
1044            inner.encode(&mut packet);
1045            fields.encode(&mut packet);
1046            packet
1047        };
1048        for (id, payload) in [
1049            (EthMessageID::GetCells, nested(&GetCells::default())),
1050            (EthMessageID::Cells, nested(&Cells::default())),
1051        ] {
1052            let mut packet = vec![id.to_u8()];
1053            packet.extend(payload);
1054            let err = ProtocolMessage::<EthNetworkPrimitives>::decode_message(
1055                EthVersion::Eth72,
1056                &mut packet.as_slice(),
1057            )
1058            .unwrap_err();
1059            assert!(matches!(err, MessageError::RlpError(Error::InputTooShort)), "{err:?}");
1060        }
1061    }
1062
1063    #[test]
1064    fn pooled_transactions_decode_by_eth_version() {
1065        let sidecar = BlobTransactionSidecarEip7594::new(
1066            vec![Blob::repeat_byte(1)],
1067            vec![Bytes48::repeat_byte(2)],
1068            vec![Bytes48::repeat_byte(3); 128],
1069        );
1070        let full = PooledTransactionVariant::Eip4844(
1071            TxEip4844WithSidecar {
1072                tx: TxEip4844 { blob_versioned_hashes: vec![B256::ZERO], ..Default::default() },
1073                sidecar: sidecar.into(),
1074            }
1075            .into_signed(Signature::test_signature()),
1076        );
1077        let mut without_blobs = full.clone();
1078        without_blobs.clear_eip7594_blobs();
1079        let decode = |version, tx: &PooledTransactionVariant| {
1080            let response =
1081                RequestPair { request_id: 7, message: PooledTransactions(vec![tx.clone()]) };
1082            let mut packet = vec![EthMessageID::PooledTransactions.to_u8()];
1083            packet.extend(alloy_rlp::encode(&response));
1084            let decoded = ProtocolMessage::<EthNetworkPrimitives>::decode_message(
1085                version,
1086                &mut packet.as_slice(),
1087            );
1088            (decoded.map(|message| message.message), EthMessage::PooledTransactions(response))
1089        };
1090
1091        for (version, tx) in [
1092            (EthVersion::Eth71, &full),
1093            (EthVersion::Eth71, &without_blobs),
1094            (EthVersion::Eth72, &without_blobs),
1095        ] {
1096            let (decoded, expected) = decode(version, tx);
1097            assert_eq!(decoded.unwrap(), expected);
1098        }
1099        // eth/72 peers fetch blobs with `GetCells`, so a body with blobs is invalid.
1100        let (decoded, _) = decode(EthVersion::Eth72, &full);
1101        assert!(matches!(
1102            decoded,
1103            Err(MessageError::RlpError(Error::Custom(
1104                "expected a blobless eth/72 pooled transaction"
1105            )))
1106        ));
1107    }
1108
1109    #[test]
1110    fn request_pair_encode() {
1111        let request_pair = RequestPair { request_id: 1337, message: vec![5u8] };
1112
1113        // c5: start of list (c0) + len(full_list) (length is <55 bytes)
1114        // 82: 0x80 + len(1337)
1115        // 05 39: 1337 (request_id)
1116        // === full_list ===
1117        // c1: start of list (c0) + len(list) (length is <55 bytes)
1118        // 05: 5 (message)
1119        let expected = hex!("c5820539c105");
1120        let got = encode(request_pair);
1121        assert_eq!(expected[..], got, "expected: {expected:X?}, got: {got:X?}",);
1122    }
1123
1124    #[test]
1125    fn request_pair_decode() {
1126        let raw_pair = &hex!("c5820539c105")[..];
1127
1128        let expected = RequestPair { request_id: 1337, message: vec![5u8] };
1129
1130        let got = RequestPair::<Vec<u8>>::decode(&mut &*raw_pair).unwrap();
1131        assert_eq!(expected.length(), raw_pair.len());
1132        assert_eq!(expected, got);
1133    }
1134
1135    #[test]
1136    fn malicious_request_pair_decode() {
1137        // A maliciously encoded request pair, where the len(full_list) is 5, but it
1138        // actually consumes 6 bytes when decoding
1139        //
1140        // c5: start of list (c0) + len(full_list) (length is <55 bytes)
1141        // 82: 0x80 + len(1337)
1142        // 05 39: 1337 (request_id)
1143        // === full_list ===
1144        // c2: start of list (c0) + len(list) (length is <55 bytes)
1145        // 05 05: 5 5(message)
1146        let raw_pair = &hex!("c5820539c20505")[..];
1147
1148        let result = RequestPair::<Vec<u8>>::decode(&mut &*raw_pair);
1149        // The inner decoder is bounded by the outer list and cannot consume the extra byte.
1150        assert_eq!(result, Err(Error::InputTooShort));
1151    }
1152
1153    #[test]
1154    fn request_pair_decode_rejects_string_header() {
1155        // A request pair wrapped in a string header instead of a list header
1156        //
1157        // 82: start of string (80) + len(payload)
1158        // 2d: 45 (request_id)
1159        // c0: empty list (message)
1160        let raw_pair = &hex!("822dc0")[..];
1161
1162        let result = RequestPair::<Vec<u8>>::decode(&mut &*raw_pair);
1163        assert_eq!(result, Err(Error::UnexpectedString));
1164
1165        let result = RequestPair::decode_with(&mut &*raw_pair, Vec::<u8>::decode);
1166        assert_eq!(result, Err(Error::UnexpectedString));
1167    }
1168
1169    #[test]
1170    fn empty_block_bodies_protocol() {
1171        let empty_block_bodies =
1172            ProtocolMessage::from(EthMessage::<EthNetworkPrimitives>::BlockBodies(RequestPair {
1173                request_id: 0,
1174                message: Default::default(),
1175            }));
1176        let mut buf = Vec::new();
1177        empty_block_bodies.encode(&mut buf);
1178        let decoded =
1179            ProtocolMessage::decode_message(EthVersion::Eth68, &mut buf.as_slice()).unwrap();
1180        assert_eq!(empty_block_bodies, decoded);
1181    }
1182
1183    #[test]
1184    fn empty_block_body_protocol() {
1185        let empty_block_bodies =
1186            ProtocolMessage::from(EthMessage::<EthNetworkPrimitives>::BlockBodies(RequestPair {
1187                request_id: 0,
1188                message: vec![BlockBody {
1189                    transactions: vec![],
1190                    ommers: vec![],
1191                    withdrawals: Some(Default::default()),
1192                }]
1193                .into(),
1194            }));
1195        let mut buf = Vec::new();
1196        empty_block_bodies.encode(&mut buf);
1197        let decoded =
1198            ProtocolMessage::decode_message(EthVersion::Eth68, &mut buf.as_slice()).unwrap();
1199        assert_eq!(empty_block_bodies, decoded);
1200    }
1201
1202    #[test]
1203    fn decode_block_bodies_message() {
1204        let buf = hex!("06c48199c1c0");
1205        let msg = ProtocolMessage::<EthNetworkPrimitives>::decode_message(
1206            EthVersion::Eth68,
1207            &mut &buf[..],
1208        )
1209        .unwrap_err();
1210        assert!(matches!(msg, MessageError::RlpError(alloy_rlp::Error::InputTooShort)));
1211    }
1212
1213    #[test]
1214    fn custom_message_roundtrip() {
1215        let custom_payload = vec![1, 2, 3, 4, 5];
1216        let custom_message = RawCapabilityMessage::new(0x20, custom_payload.into());
1217        let protocol_message = ProtocolMessage::<EthNetworkPrimitives> {
1218            message_type: EthMessageID::Other(0x20),
1219            message: EthMessage::Other(custom_message),
1220        };
1221
1222        let encoded = encode(protocol_message.clone());
1223        assert_eq!(protocol_message.length(), encoded.len());
1224        let decoded = ProtocolMessage::<EthNetworkPrimitives>::decode_message(
1225            EthVersion::Eth68,
1226            &mut &encoded[..],
1227        )
1228        .unwrap();
1229
1230        assert_eq!(protocol_message, decoded);
1231    }
1232
1233    #[test]
1234    fn custom_message_empty_payload_roundtrip() {
1235        let custom_message = RawCapabilityMessage::new(0x30, vec![].into());
1236        let protocol_message = ProtocolMessage::<EthNetworkPrimitives> {
1237            message_type: EthMessageID::Other(0x30),
1238            message: EthMessage::Other(custom_message),
1239        };
1240
1241        let encoded = encode(protocol_message.clone());
1242        let decoded = ProtocolMessage::<EthNetworkPrimitives>::decode_message(
1243            EthVersion::Eth68,
1244            &mut &encoded[..],
1245        )
1246        .unwrap();
1247
1248        assert_eq!(protocol_message, decoded);
1249    }
1250
1251    #[test]
1252    fn decode_status_success() {
1253        let status = Status {
1254            version: EthVersion::Eth68,
1255            chain: alloy_chains::Chain::mainnet(),
1256            total_difficulty: U256::from(100u64),
1257            blockhash: B256::random(),
1258            genesis: B256::random(),
1259            forkid: ForkId { hash: ForkHash([0xb7, 0x15, 0x07, 0x7d]), next: 0 },
1260        };
1261
1262        let protocol_message = ProtocolMessage::<EthNetworkPrimitives>::from(EthMessage::Status(
1263            StatusMessage::Legacy(status),
1264        ));
1265        let encoded = encode(protocol_message);
1266
1267        let decoded = ProtocolMessage::<EthNetworkPrimitives>::decode_status(
1268            EthVersion::Eth68,
1269            &mut &encoded[..],
1270        )
1271        .unwrap();
1272
1273        assert!(matches!(decoded, StatusMessage::Legacy(s) if s == status));
1274    }
1275
1276    #[test]
1277    fn eth_message_id_max_includes_block_range_update() {
1278        assert_eq!(EthMessageID::max(EthVersion::Eth69), EthMessageID::BlockRangeUpdate.to_u8(),);
1279        assert_eq!(EthMessageID::max(EthVersion::Eth70), EthMessageID::BlockRangeUpdate.to_u8(),);
1280        assert_eq!(EthMessageID::max(EthVersion::Eth68), EthMessageID::Receipts.to_u8());
1281    }
1282
1283    #[test]
1284    fn decode_status_rejects_non_status() {
1285        let msg = EthMessage::<EthNetworkPrimitives>::GetBlockBodies(RequestPair {
1286            request_id: 1,
1287            message: crate::GetBlockBodies::default(),
1288        });
1289        let protocol_message =
1290            ProtocolMessage { message_type: EthMessageID::GetBlockBodies, message: msg };
1291        let encoded = encode(protocol_message);
1292
1293        let result = ProtocolMessage::<EthNetworkPrimitives>::decode_status(
1294            EthVersion::Eth68,
1295            &mut &encoded[..],
1296        );
1297
1298        assert!(matches!(
1299            result,
1300            Err(MessageError::ExpectedStatusMessage(EthMessageID::GetBlockBodies))
1301        ));
1302    }
1303}