Skip to main content

reth_network/
message.rs

1//! Capability messaging
2//!
3//! An `RLPx` stream is multiplexed via the prepended message-id of a framed message.
4//! Capabilities are exchanged via the `RLPx` `Hello` message as pairs of `(id, version)`, <https://github.com/ethereum/devp2p/blob/master/rlpx.md#capability-messaging>
5
6use crate::types::{BlockAccessLists, Receipts69, Receipts70};
7use alloy_consensus::{BlockHeader, ReceiptWithBloom};
8use alloy_primitives::{Bytes, B256};
9use futures::FutureExt;
10use reth_eth_wire::{
11    message::RequestPair, BlockBodies, BlockHeaders, BlockRangeUpdate, BroadcastPoolTransactions,
12    Cells, EthMessage, EthNetworkPrimitives, GetBlockAccessLists, GetBlockBodies, GetBlockHeaders,
13    GetReceipts, NetworkPrimitives, NewBlock, NewBlockHashes, NewBlockPayload,
14    NewPooledTransactionHashes, NodeData, PooledTransactions, Receipts, SharedTransactions,
15    Transactions,
16};
17use reth_eth_wire_types::{snap::SnapProtocolMessage, RawCapabilityMessage};
18use reth_network_api::{PeerRequest, RequestMessage};
19use reth_network_p2p::{
20    error::{RequestError, RequestResult},
21    snap::client::SnapResponse,
22};
23use reth_primitives_traits::Block;
24use std::{
25    sync::Arc,
26    task::{ready, Context, Poll},
27};
28use tokio::sync::oneshot;
29
30/// Internal form of a `NewBlock` message
31#[derive(Debug, Clone)]
32pub struct NewBlockMessage<P = NewBlock<reth_ethereum_primitives::Block>> {
33    /// Hash of the block
34    pub hash: B256,
35    /// Raw received message
36    pub block: Arc<P>,
37}
38
39// === impl NewBlockMessage ===
40
41impl<P: NewBlockPayload> NewBlockMessage<P> {
42    /// Returns the block number of the block
43    pub fn number(&self) -> u64 {
44        self.block.block().header().number()
45    }
46}
47
48/// All Bi-directional eth-message variants that can be sent to a session or received from a
49/// session.
50#[derive(Debug)]
51pub enum PeerMessage<N: NetworkPrimitives = EthNetworkPrimitives> {
52    /// Announce new block hashes
53    NewBlockHashes(NewBlockHashes),
54    /// Broadcast new block.
55    NewBlock(NewBlockMessage<N::NewBlockPayload>),
56    /// Received transactions _from_ the peer
57    ReceivedTransaction(Transactions<N::BroadcastedTransaction>),
58    /// Broadcast transactions _from_ local _to_ a peer.
59    SendTransactions(SharedTransactions<N::BroadcastedTransaction>),
60    /// Broadcast cached pool transactions _from_ local _to_ a peer.
61    SendBroadcastPoolTransactions(BroadcastPoolTransactions),
62    /// Send new pooled transactions
63    PooledTransactions(NewPooledTransactionHashes),
64    /// All `eth` request variants.
65    EthRequest(PeerRequest<N>),
66    /// Announces when `BlockRange` is updated.
67    BlockRangeUpdated(BlockRangeUpdate),
68    /// Any other or manually crafted eth message.
69    ///
70    /// Caution: It is expected that this is a valid `eth_` capability message.
71    Other(RawCapabilityMessage),
72}
73
74impl<N: NetworkPrimitives> PeerMessage<N> {
75    /// Returns a static string identifying the message variant for logging.
76    pub const fn message_kind(&self) -> &'static str {
77        match self {
78            Self::NewBlockHashes(_) => "NewBlockHashes",
79            Self::NewBlock(_) => "NewBlock",
80            Self::ReceivedTransaction(_) => "ReceivedTransaction",
81            Self::SendTransactions(_) => "SendTransactions",
82            Self::SendBroadcastPoolTransactions(_) => "SendBroadcastPoolTransactions",
83            Self::PooledTransactions(_) => "PooledTransactions",
84            Self::EthRequest(_) => "EthRequest",
85            Self::BlockRangeUpdated(_) => "BlockRangeUpdated",
86            Self::Other(_) => "Other",
87        }
88    }
89
90    /// Returns `true` if this message is a broadcast (block/transaction announcement or
91    /// propagation) rather than a request/response.
92    pub const fn is_broadcast(&self) -> bool {
93        matches!(
94            self,
95            Self::NewBlockHashes(_) |
96                Self::NewBlock(_) |
97                Self::SendTransactions(_) |
98                Self::SendBroadcastPoolTransactions(_) |
99                Self::PooledTransactions(_)
100        )
101    }
102
103    /// Returns the number of items in the message payload, if applicable.
104    pub fn message_item_count(&self) -> usize {
105        match self {
106            Self::NewBlockHashes(msg) => msg.len(),
107            Self::ReceivedTransaction(msg) => msg.len(),
108            Self::SendTransactions(msg) => msg.len(),
109            Self::SendBroadcastPoolTransactions(msg) => msg.len(),
110            Self::PooledTransactions(msg) => msg.len(),
111            Self::NewBlock(_) |
112            Self::EthRequest(_) |
113            Self::BlockRangeUpdated(_) |
114            Self::Other(_) => 1,
115        }
116    }
117}
118
119/// Request Variants that only target block related data.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub enum BlockRequest {
122    /// Requests block headers from the peer.
123    ///
124    /// The response should be sent through the channel.
125    GetBlockHeaders(GetBlockHeaders),
126
127    /// Requests block bodies from the peer.
128    ///
129    /// The response should be sent through the channel.
130    GetBlockBodies(GetBlockBodies),
131    /// Requests block access lists from the peer.
132    ///
133    /// The response should be sent through the channel.
134    GetBlockAccessLists(GetBlockAccessLists),
135
136    /// Requests receipts from the peer.
137    ///
138    /// The response should be sent through the channel.
139    GetReceipts(GetReceipts),
140    /// Requests a `snap/2` (EIP-8189) message from the peer.
141    ///
142    /// The response should be sent through the channel.
143    GetSnap(SnapProtocolMessage),
144}
145
146/// Corresponding variant for [`PeerRequest`].
147#[derive(Debug)]
148pub enum PeerResponse<N: NetworkPrimitives = EthNetworkPrimitives> {
149    /// Represents a response to a request for block headers.
150    BlockHeaders {
151        /// The receiver channel for the response to a block headers request.
152        response: oneshot::Receiver<RequestResult<BlockHeaders<N::BlockHeader>>>,
153    },
154    /// Represents a response to a request for block bodies.
155    BlockBodies {
156        /// The receiver channel for the response to a block bodies request.
157        response: oneshot::Receiver<RequestResult<BlockBodies<N::BlockBody>>>,
158    },
159    /// Represents a response to a request for pooled transactions.
160    PooledTransactions {
161        /// The receiver channel for the response to a pooled transactions request.
162        response: oneshot::Receiver<RequestResult<PooledTransactions<N::PooledTransaction>>>,
163    },
164    /// Represents a response to a request for `NodeData`.
165    NodeData {
166        /// The receiver channel for the response to a `NodeData` request.
167        response: oneshot::Receiver<RequestResult<NodeData>>,
168    },
169    /// Represents a response to a request for receipts.
170    Receipts {
171        /// The receiver channel for the response to a receipts request.
172        response: oneshot::Receiver<RequestResult<Receipts<N::Receipt>>>,
173    },
174    /// Represents a response to a request for receipts.
175    ///
176    /// This is a variant of `Receipts` that was introduced in `eth/69`.
177    /// The difference is that this variant does not require the inclusion of bloom filters in the
178    /// response, making it more lightweight.
179    Receipts69 {
180        /// The receiver channel for the response to a receipts request.
181        response: oneshot::Receiver<RequestResult<Receipts69<N::Receipt>>>,
182    },
183    /// Represents a response to a request for receipts using eth/70.
184    Receipts70 {
185        /// The receiver channel for the response to a receipts request.
186        response: oneshot::Receiver<RequestResult<Receipts70<N::Receipt>>>,
187    },
188    /// Represents a response to a request for block access lists.
189    BlockAccessLists {
190        /// The receiver channel for the response to a block access lists request.
191        response: oneshot::Receiver<RequestResult<BlockAccessLists>>,
192    },
193    ///
194    /// Represents a response to a request for cells.
195    Cells {
196        /// The receiver channel for the response to a cells request.
197        response: oneshot::Receiver<RequestResult<Cells>>,
198    },
199    /// Represents a response to a `snap/2` (EIP-8189) request.
200    Snap {
201        /// The receiver channel for the response to a `snap/2` request.
202        response: oneshot::Receiver<RequestResult<SnapResponse>>,
203    },
204}
205
206// === impl PeerResponse ===
207
208impl<N: NetworkPrimitives> PeerResponse<N> {
209    /// Polls the type to completion.
210    pub(crate) fn poll(&mut self, cx: &mut Context<'_>) -> Poll<PeerResponseResult<N>> {
211        macro_rules! poll_request {
212            ($response:ident, $item:ident, $cx:ident) => {
213                match ready!($response.poll_unpin($cx)) {
214                    Ok(res) => PeerResponseResult::$item(res.map(|item| item.0)),
215                    Err(err) => PeerResponseResult::$item(Err(err.into())),
216                }
217            };
218        }
219
220        let res = match self {
221            Self::BlockHeaders { response } => {
222                poll_request!(response, BlockHeaders, cx)
223            }
224            Self::BlockBodies { response } => {
225                poll_request!(response, BlockBodies, cx)
226            }
227            Self::PooledTransactions { response } => {
228                poll_request!(response, PooledTransactions, cx)
229            }
230            Self::NodeData { response } => {
231                poll_request!(response, NodeData, cx)
232            }
233            Self::Receipts { response } => {
234                poll_request!(response, Receipts, cx)
235            }
236            Self::Receipts69 { response } => {
237                poll_request!(response, Receipts69, cx)
238            }
239            Self::Receipts70 { response } => match ready!(response.poll_unpin(cx)) {
240                Ok(res) => PeerResponseResult::Receipts70(res),
241                Err(err) => PeerResponseResult::Receipts70(Err(err.into())),
242            },
243            Self::BlockAccessLists { response } => match ready!(response.poll_unpin(cx)) {
244                Ok(res) => PeerResponseResult::BlockAccessLists(res),
245                Err(err) => PeerResponseResult::BlockAccessLists(Err(err.into())),
246            },
247            Self::Cells { response } => match ready!(response.poll_unpin(cx)) {
248                Ok(res) => PeerResponseResult::Cells(res),
249                Err(err) => PeerResponseResult::Cells(Err(err.into())),
250            },
251            Self::Snap { response } => match ready!(response.poll_unpin(cx)) {
252                Ok(res) => PeerResponseResult::Snap(res),
253                Err(err) => PeerResponseResult::Snap(Err(err.into())),
254            },
255        };
256        Poll::Ready(res)
257    }
258}
259
260/// All response variants for [`PeerResponse`]
261#[derive(Debug)]
262pub enum PeerResponseResult<N: NetworkPrimitives = EthNetworkPrimitives> {
263    /// Represents a result containing block headers or an error.
264    BlockHeaders(RequestResult<Vec<N::BlockHeader>>),
265    /// Represents a result containing block bodies or an error.
266    BlockBodies(RequestResult<Vec<N::BlockBody>>),
267    /// Represents a result containing pooled transactions or an error.
268    PooledTransactions(RequestResult<Vec<N::PooledTransaction>>),
269    /// Represents a result containing node data or an error.
270    NodeData(RequestResult<Vec<Bytes>>),
271    /// Represents a result containing receipts or an error.
272    Receipts(RequestResult<Vec<Vec<ReceiptWithBloom<N::Receipt>>>>),
273    /// Represents a result containing receipts or an error for eth/69.
274    Receipts69(RequestResult<Vec<Vec<N::Receipt>>>),
275    /// Represents a result containing receipts or an error for eth/70.
276    Receipts70(RequestResult<Receipts70<N::Receipt>>),
277    /// Represents a result containing block access lists or an error.
278    BlockAccessLists(RequestResult<BlockAccessLists>),
279    /// Represents a result containing cells or an error.
280    Cells(RequestResult<Cells>),
281    /// Represents a result containing a `snap/2` response or an error.
282    Snap(RequestResult<SnapResponse>),
283}
284
285// === impl PeerResponseResult ===
286
287impl<N: NetworkPrimitives> PeerResponseResult<N> {
288    /// Converts this response into the [`RequestMessage`] to send back to the peer: an
289    /// [`EthMessage`] for every variant except [`Self::Snap`], which becomes a
290    /// [`SnapProtocolMessage`].
291    pub fn try_into_message(self, id: u64) -> RequestResult<RequestMessage<N>> {
292        macro_rules! to_message {
293            ($response:ident, $item:ident, $request_id:ident) => {
294                match $response {
295                    Ok(res) => {
296                        let request = RequestPair { request_id: $request_id, message: $item(res) };
297                        Ok(RequestMessage::Eth(EthMessage::$item(request)))
298                    }
299                    Err(err) => Err(err),
300                }
301            };
302        }
303        match self {
304            Self::BlockHeaders(resp) => {
305                to_message!(resp, BlockHeaders, id)
306            }
307            Self::BlockBodies(resp) => {
308                to_message!(resp, BlockBodies, id)
309            }
310            Self::PooledTransactions(resp) => {
311                to_message!(resp, PooledTransactions, id)
312            }
313            Self::NodeData(resp) => {
314                to_message!(resp, NodeData, id)
315            }
316            Self::Receipts(resp) => {
317                to_message!(resp, Receipts, id)
318            }
319            Self::Receipts69(resp) => {
320                to_message!(resp, Receipts69, id)
321            }
322            Self::Receipts70(resp) => match resp {
323                Ok(res) => {
324                    let request = RequestPair { request_id: id, message: res };
325                    Ok(RequestMessage::Eth(EthMessage::Receipts70(request)))
326                }
327                Err(err) => Err(err),
328            },
329            Self::BlockAccessLists(resp) => match resp {
330                Ok(res) => {
331                    let request = RequestPair { request_id: id, message: res };
332                    Ok(RequestMessage::Eth(EthMessage::BlockAccessLists(request)))
333                }
334                Err(err) => Err(err),
335            },
336            Self::Cells(resp) => match resp {
337                Ok(res) => {
338                    let request = RequestPair { request_id: id, message: res };
339                    Ok(RequestMessage::Eth(EthMessage::Cells(request)))
340                }
341                Err(err) => Err(err),
342            },
343            Self::Snap(resp) => match resp {
344                Ok(res) => {
345                    let mut message: SnapProtocolMessage = res.into();
346                    message.set_request_id(id);
347                    Ok(RequestMessage::Snap(message))
348                }
349                Err(err) => Err(err),
350            },
351        }
352    }
353
354    /// Returns the `Err` value if the result is an error.
355    pub fn err(&self) -> Option<&RequestError> {
356        match self {
357            Self::BlockHeaders(res) => res.as_ref().err(),
358            Self::BlockBodies(res) => res.as_ref().err(),
359            Self::PooledTransactions(res) => res.as_ref().err(),
360            Self::NodeData(res) => res.as_ref().err(),
361            Self::Receipts(res) => res.as_ref().err(),
362            Self::Receipts69(res) => res.as_ref().err(),
363            Self::Receipts70(res) => res.as_ref().err(),
364            Self::BlockAccessLists(res) => res.as_ref().err(),
365            Self::Cells(res) => res.as_ref().err(),
366            Self::Snap(res) => res.as_ref().err(),
367        }
368    }
369
370    /// Returns whether this result is an error.
371    pub fn is_err(&self) -> bool {
372        self.err().is_some()
373    }
374}