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 the number of items in the message payload, if applicable.
84    pub fn message_item_count(&self) -> usize {
85        match self {
86            Self::NewBlockHashes(msg) => msg.len(),
87            Self::ReceivedTransaction(msg) => msg.len(),
88            Self::SendTransactions(msg) => msg.len(),
89            Self::PooledTransactions(msg) => msg.len(),
90            Self::NewBlock(_) |
91            Self::EthRequest(_) |
92            Self::BlockRangeUpdated(_) |
93            Self::Other(_) => 1,
94        }
95    }
96}
97
98/// Request Variants that only target block related data.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum BlockRequest {
101    /// Requests block headers from the peer.
102    ///
103    /// The response should be sent through the channel.
104    GetBlockHeaders(GetBlockHeaders),
105
106    /// Requests block bodies from the peer.
107    ///
108    /// The response should be sent through the channel.
109    GetBlockBodies(GetBlockBodies),
110
111    /// Requests receipts from the peer.
112    ///
113    /// The response should be sent through the channel.
114    GetReceipts(GetReceipts),
115}
116
117/// Corresponding variant for [`PeerRequest`].
118#[derive(Debug)]
119pub enum PeerResponse<N: NetworkPrimitives = EthNetworkPrimitives> {
120    /// Represents a response to a request for block headers.
121    BlockHeaders {
122        /// The receiver channel for the response to a block headers request.
123        response: oneshot::Receiver<RequestResult<BlockHeaders<N::BlockHeader>>>,
124    },
125    /// Represents a response to a request for block bodies.
126    BlockBodies {
127        /// The receiver channel for the response to a block bodies request.
128        response: oneshot::Receiver<RequestResult<BlockBodies<N::BlockBody>>>,
129    },
130    /// Represents a response to a request for pooled transactions.
131    PooledTransactions {
132        /// The receiver channel for the response to a pooled transactions request.
133        response: oneshot::Receiver<RequestResult<PooledTransactions<N::PooledTransaction>>>,
134    },
135    /// Represents a response to a request for `NodeData`.
136    NodeData {
137        /// The receiver channel for the response to a `NodeData` request.
138        response: oneshot::Receiver<RequestResult<NodeData>>,
139    },
140    /// Represents a response to a request for receipts.
141    Receipts {
142        /// The receiver channel for the response to a receipts request.
143        response: oneshot::Receiver<RequestResult<Receipts<N::Receipt>>>,
144    },
145    /// Represents a response to a request for receipts.
146    ///
147    /// This is a variant of `Receipts` that was introduced in `eth/69`.
148    /// The difference is that this variant does not require the inclusion of bloom filters in the
149    /// response, making it more lightweight.
150    Receipts69 {
151        /// The receiver channel for the response to a receipts request.
152        response: oneshot::Receiver<RequestResult<Receipts69<N::Receipt>>>,
153    },
154    /// Represents a response to a request for receipts using eth/70.
155    Receipts70 {
156        /// The receiver channel for the response to a receipts request.
157        response: oneshot::Receiver<RequestResult<Receipts70<N::Receipt>>>,
158    },
159    /// Represents a response to a request for block access lists.
160    BlockAccessLists {
161        /// The receiver channel for the response to a block access lists request.
162        response: oneshot::Receiver<RequestResult<BlockAccessLists>>,
163    },
164}
165
166// === impl PeerResponse ===
167
168impl<N: NetworkPrimitives> PeerResponse<N> {
169    /// Polls the type to completion.
170    pub(crate) fn poll(&mut self, cx: &mut Context<'_>) -> Poll<PeerResponseResult<N>> {
171        macro_rules! poll_request {
172            ($response:ident, $item:ident, $cx:ident) => {
173                match ready!($response.poll_unpin($cx)) {
174                    Ok(res) => PeerResponseResult::$item(res.map(|item| item.0)),
175                    Err(err) => PeerResponseResult::$item(Err(err.into())),
176                }
177            };
178        }
179
180        let res = match self {
181            Self::BlockHeaders { response } => {
182                poll_request!(response, BlockHeaders, cx)
183            }
184            Self::BlockBodies { response } => {
185                poll_request!(response, BlockBodies, cx)
186            }
187            Self::PooledTransactions { response } => {
188                poll_request!(response, PooledTransactions, cx)
189            }
190            Self::NodeData { response } => {
191                poll_request!(response, NodeData, cx)
192            }
193            Self::Receipts { response } => {
194                poll_request!(response, Receipts, cx)
195            }
196            Self::Receipts69 { response } => {
197                poll_request!(response, Receipts69, cx)
198            }
199            Self::Receipts70 { response } => match ready!(response.poll_unpin(cx)) {
200                Ok(res) => PeerResponseResult::Receipts70(res),
201                Err(err) => PeerResponseResult::Receipts70(Err(err.into())),
202            },
203            Self::BlockAccessLists { response } => match ready!(response.poll_unpin(cx)) {
204                Ok(res) => PeerResponseResult::BlockAccessLists(res),
205                Err(err) => PeerResponseResult::BlockAccessLists(Err(err.into())),
206            },
207        };
208        Poll::Ready(res)
209    }
210}
211
212/// All response variants for [`PeerResponse`]
213#[derive(Debug)]
214pub enum PeerResponseResult<N: NetworkPrimitives = EthNetworkPrimitives> {
215    /// Represents a result containing block headers or an error.
216    BlockHeaders(RequestResult<Vec<N::BlockHeader>>),
217    /// Represents a result containing block bodies or an error.
218    BlockBodies(RequestResult<Vec<N::BlockBody>>),
219    /// Represents a result containing pooled transactions or an error.
220    PooledTransactions(RequestResult<Vec<N::PooledTransaction>>),
221    /// Represents a result containing node data or an error.
222    NodeData(RequestResult<Vec<Bytes>>),
223    /// Represents a result containing receipts or an error.
224    Receipts(RequestResult<Vec<Vec<ReceiptWithBloom<N::Receipt>>>>),
225    /// Represents a result containing receipts or an error for eth/69.
226    Receipts69(RequestResult<Vec<Vec<N::Receipt>>>),
227    /// Represents a result containing receipts or an error for eth/70.
228    Receipts70(RequestResult<Receipts70<N::Receipt>>),
229    /// Represents a result containing block access lists or an error.
230    BlockAccessLists(RequestResult<BlockAccessLists>),
231}
232
233// === impl PeerResponseResult ===
234
235impl<N: NetworkPrimitives> PeerResponseResult<N> {
236    /// Converts this response into an [`EthMessage`]
237    pub fn try_into_message(self, id: u64) -> RequestResult<EthMessage<N>> {
238        macro_rules! to_message {
239            ($response:ident, $item:ident, $request_id:ident) => {
240                match $response {
241                    Ok(res) => {
242                        let request = RequestPair { request_id: $request_id, message: $item(res) };
243                        Ok(EthMessage::$item(request))
244                    }
245                    Err(err) => Err(err),
246                }
247            };
248        }
249        match self {
250            Self::BlockHeaders(resp) => {
251                to_message!(resp, BlockHeaders, id)
252            }
253            Self::BlockBodies(resp) => {
254                to_message!(resp, BlockBodies, id)
255            }
256            Self::PooledTransactions(resp) => {
257                to_message!(resp, PooledTransactions, id)
258            }
259            Self::NodeData(resp) => {
260                to_message!(resp, NodeData, id)
261            }
262            Self::Receipts(resp) => {
263                to_message!(resp, Receipts, id)
264            }
265            Self::Receipts69(resp) => {
266                to_message!(resp, Receipts69, id)
267            }
268            Self::Receipts70(resp) => match resp {
269                Ok(res) => {
270                    let request = RequestPair { request_id: id, message: res };
271                    Ok(EthMessage::Receipts70(request))
272                }
273                Err(err) => Err(err),
274            },
275            Self::BlockAccessLists(resp) => match resp {
276                Ok(res) => {
277                    let request = RequestPair { request_id: id, message: res };
278                    Ok(EthMessage::BlockAccessLists(request))
279                }
280                Err(err) => Err(err),
281            },
282        }
283    }
284
285    /// Returns the `Err` value if the result is an error.
286    pub fn err(&self) -> Option<&RequestError> {
287        match self {
288            Self::BlockHeaders(res) => res.as_ref().err(),
289            Self::BlockBodies(res) => res.as_ref().err(),
290            Self::PooledTransactions(res) => res.as_ref().err(),
291            Self::NodeData(res) => res.as_ref().err(),
292            Self::Receipts(res) => res.as_ref().err(),
293            Self::Receipts69(res) => res.as_ref().err(),
294            Self::Receipts70(res) => res.as_ref().err(),
295            Self::BlockAccessLists(res) => res.as_ref().err(),
296        }
297    }
298
299    /// Returns whether this result is an error.
300    pub fn is_err(&self) -> bool {
301        self.err().is_some()
302    }
303}