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