reth_network_api/
events.rs

1//! API related to listening for network events.
2
3use reth_eth_wire_types::{
4    message::RequestPair, BlockBodies, BlockHeaders, Capabilities, DisconnectReason, EthMessage,
5    EthNetworkPrimitives, EthVersion, GetBlockBodies, GetBlockHeaders, GetNodeData,
6    GetPooledTransactions, GetReceipts, NetworkPrimitives, NodeData, PooledTransactions, Receipts,
7    Status,
8};
9use reth_ethereum_forks::ForkId;
10use reth_network_p2p::error::{RequestError, RequestResult};
11use reth_network_peers::PeerId;
12use reth_network_types::PeerAddr;
13use reth_tokio_util::EventStream;
14use std::{
15    fmt,
16    net::SocketAddr,
17    pin::Pin,
18    sync::Arc,
19    task::{Context, Poll},
20};
21use tokio::sync::{mpsc, oneshot};
22use tokio_stream::{wrappers::UnboundedReceiverStream, Stream, StreamExt};
23
24/// A boxed stream of network peer events that provides a type-erased interface.
25pub struct PeerEventStream(Pin<Box<dyn Stream<Item = PeerEvent> + Send + Sync>>);
26
27impl fmt::Debug for PeerEventStream {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        f.debug_struct("PeerEventStream").finish_non_exhaustive()
30    }
31}
32
33impl PeerEventStream {
34    /// Create a new stream [`PeerEventStream`] by converting the provided stream's items into peer
35    /// events [`PeerEvent`]
36    pub fn new<S, T>(stream: S) -> Self
37    where
38        S: Stream<Item = T> + Send + Sync + 'static,
39        T: Into<PeerEvent> + 'static,
40    {
41        let mapped_stream = stream.map(Into::into);
42        Self(Box::pin(mapped_stream))
43    }
44}
45
46impl Stream for PeerEventStream {
47    type Item = PeerEvent;
48
49    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
50        self.0.as_mut().poll_next(cx)
51    }
52}
53
54/// Represents information about an established peer session.
55#[derive(Debug, Clone)]
56pub struct SessionInfo {
57    /// The identifier of the peer to which a session was established.
58    pub peer_id: PeerId,
59    /// The remote addr of the peer to which a session was established.
60    pub remote_addr: SocketAddr,
61    /// The client version of the peer to which a session was established.
62    pub client_version: Arc<str>,
63    /// Capabilities the peer announced.
64    pub capabilities: Arc<Capabilities>,
65    /// The status of the peer to which a session was established.
66    pub status: Arc<Status>,
67    /// Negotiated eth version of the session.
68    pub version: EthVersion,
69}
70
71/// (Non-exhaustive) List of the different events emitted by the network that are of interest for
72/// subscribers.
73///
74/// This includes any event types that may be relevant to tasks, for metrics, keep track of peers
75/// etc.
76#[derive(Debug, Clone)]
77pub enum PeerEvent {
78    /// Closed the peer session.
79    SessionClosed {
80        /// The identifier of the peer to which a session was closed.
81        peer_id: PeerId,
82        /// Why the disconnect was triggered
83        reason: Option<DisconnectReason>,
84    },
85    /// Established a new session with the given peer.
86    SessionEstablished(SessionInfo),
87    /// Event emitted when a new peer is added
88    PeerAdded(PeerId),
89    /// Event emitted when a new peer is removed
90    PeerRemoved(PeerId),
91}
92
93/// (Non-exhaustive) Network events representing peer lifecycle events and session requests.
94#[derive(Debug)]
95pub enum NetworkEvent<R = PeerRequest> {
96    /// Basic peer lifecycle event.
97    Peer(PeerEvent),
98    /// Session established with requests.
99    ActivePeerSession {
100        /// Session information
101        info: SessionInfo,
102        /// A request channel to the session task.
103        messages: PeerRequestSender<R>,
104    },
105}
106
107impl<R> Clone for NetworkEvent<R> {
108    fn clone(&self) -> Self {
109        match self {
110            Self::Peer(event) => Self::Peer(event.clone()),
111            Self::ActivePeerSession { info, messages } => {
112                Self::ActivePeerSession { info: info.clone(), messages: messages.clone() }
113            }
114        }
115    }
116}
117
118impl<R> From<NetworkEvent<R>> for PeerEvent {
119    fn from(event: NetworkEvent<R>) -> Self {
120        match event {
121            NetworkEvent::Peer(peer_event) => peer_event,
122            NetworkEvent::ActivePeerSession { info, .. } => Self::SessionEstablished(info),
123        }
124    }
125}
126
127/// Provides peer event subscription for the network.
128#[auto_impl::auto_impl(&, Arc)]
129pub trait NetworkPeersEvents: Send + Sync {
130    /// Creates a new peer event listener stream.
131    fn peer_events(&self) -> PeerEventStream;
132}
133
134/// Provides event subscription for the network.
135#[auto_impl::auto_impl(&, Arc)]
136pub trait NetworkEventListenerProvider: NetworkPeersEvents {
137    /// The primitive types to use in the `PeerRequest` used in the stream.
138    type Primitives: NetworkPrimitives;
139
140    /// Creates a new [`NetworkEvent`] listener channel.
141    fn event_listener(&self) -> EventStream<NetworkEvent<PeerRequest<Self::Primitives>>>;
142    /// Returns a new [`DiscoveryEvent`] stream.
143    ///
144    /// This stream yields [`DiscoveryEvent`]s for each peer that is discovered.
145    fn discovery_listener(&self) -> UnboundedReceiverStream<DiscoveryEvent>;
146}
147
148/// Events produced by the `Discovery` manager.
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub enum DiscoveryEvent {
151    /// Discovered a node
152    NewNode(DiscoveredEvent),
153    /// Retrieved a [`ForkId`] from the peer via ENR request, See <https://eips.ethereum.org/EIPS/eip-868>
154    EnrForkId(PeerId, ForkId),
155}
156
157/// Represents events related to peer discovery in the network.
158#[derive(Debug, Clone, PartialEq, Eq)]
159pub enum DiscoveredEvent {
160    /// Indicates that a new peer has been discovered and queued for potential connection.
161    ///
162    /// This event is generated when the system becomes aware of a new peer
163    /// but hasn't yet established a connection.
164    ///
165    /// # Fields
166    ///
167    /// * `peer_id` - The unique identifier of the discovered peer.
168    /// * `addr` - The network address of the discovered peer.
169    /// * `fork_id` - An optional identifier for the fork that this peer is associated with. `None`
170    ///   if the peer is not associated with a specific fork.
171    EventQueued {
172        /// The unique identifier of the discovered peer.
173        peer_id: PeerId,
174        /// The network address of the discovered peer.
175        addr: PeerAddr,
176        /// An optional identifier for the fork that this peer is associated with.
177        /// `None` if the peer is not associated with a specific fork.
178        fork_id: Option<ForkId>,
179    },
180}
181
182/// Protocol related request messages that expect a response
183#[derive(Debug)]
184pub enum PeerRequest<N: NetworkPrimitives = EthNetworkPrimitives> {
185    /// Requests block headers from the peer.
186    ///
187    /// The response should be sent through the channel.
188    GetBlockHeaders {
189        /// The request for block headers.
190        request: GetBlockHeaders,
191        /// The channel to send the response for block headers.
192        response: oneshot::Sender<RequestResult<BlockHeaders<N::BlockHeader>>>,
193    },
194    /// Requests block bodies from the peer.
195    ///
196    /// The response should be sent through the channel.
197    GetBlockBodies {
198        /// The request for block bodies.
199        request: GetBlockBodies,
200        /// The channel to send the response for block bodies.
201        response: oneshot::Sender<RequestResult<BlockBodies<N::BlockBody>>>,
202    },
203    /// Requests pooled transactions from the peer.
204    ///
205    /// The response should be sent through the channel.
206    GetPooledTransactions {
207        /// The request for pooled transactions.
208        request: GetPooledTransactions,
209        /// The channel to send the response for pooled transactions.
210        response: oneshot::Sender<RequestResult<PooledTransactions<N::PooledTransaction>>>,
211    },
212    /// Requests `NodeData` from the peer.
213    ///
214    /// The response should be sent through the channel.
215    GetNodeData {
216        /// The request for `NodeData`.
217        request: GetNodeData,
218        /// The channel to send the response for `NodeData`.
219        response: oneshot::Sender<RequestResult<NodeData>>,
220    },
221    /// Requests receipts from the peer.
222    ///
223    /// The response should be sent through the channel.
224    GetReceipts {
225        /// The request for receipts.
226        request: GetReceipts,
227        /// The channel to send the response for receipts.
228        response: oneshot::Sender<RequestResult<Receipts>>,
229    },
230}
231
232// === impl PeerRequest ===
233
234impl<N: NetworkPrimitives> PeerRequest<N> {
235    /// Invoked if we received a response which does not match the request
236    pub fn send_bad_response(self) {
237        self.send_err_response(RequestError::BadResponse)
238    }
239
240    /// Send an error back to the receiver.
241    pub fn send_err_response(self, err: RequestError) {
242        let _ = match self {
243            Self::GetBlockHeaders { response, .. } => response.send(Err(err)).ok(),
244            Self::GetBlockBodies { response, .. } => response.send(Err(err)).ok(),
245            Self::GetPooledTransactions { response, .. } => response.send(Err(err)).ok(),
246            Self::GetNodeData { response, .. } => response.send(Err(err)).ok(),
247            Self::GetReceipts { response, .. } => response.send(Err(err)).ok(),
248        };
249    }
250
251    /// Returns the [`EthMessage`] for this type
252    pub fn create_request_message(&self, request_id: u64) -> EthMessage<N> {
253        match self {
254            Self::GetBlockHeaders { request, .. } => {
255                EthMessage::GetBlockHeaders(RequestPair { request_id, message: *request })
256            }
257            Self::GetBlockBodies { request, .. } => {
258                EthMessage::GetBlockBodies(RequestPair { request_id, message: request.clone() })
259            }
260            Self::GetPooledTransactions { request, .. } => {
261                EthMessage::GetPooledTransactions(RequestPair {
262                    request_id,
263                    message: request.clone(),
264                })
265            }
266            Self::GetNodeData { request, .. } => {
267                EthMessage::GetNodeData(RequestPair { request_id, message: request.clone() })
268            }
269            Self::GetReceipts { request, .. } => {
270                EthMessage::GetReceipts(RequestPair { request_id, message: request.clone() })
271            }
272        }
273    }
274
275    /// Consumes the type and returns the inner [`GetPooledTransactions`] variant.
276    pub fn into_get_pooled_transactions(self) -> Option<GetPooledTransactions> {
277        match self {
278            Self::GetPooledTransactions { request, .. } => Some(request),
279            _ => None,
280        }
281    }
282}
283
284/// A Cloneable connection for sending _requests_ directly to the session of a peer.
285pub struct PeerRequestSender<R = PeerRequest> {
286    /// id of the remote node.
287    pub peer_id: PeerId,
288    /// The Sender half connected to a session.
289    pub to_session_tx: mpsc::Sender<R>,
290}
291
292impl<R> Clone for PeerRequestSender<R> {
293    fn clone(&self) -> Self {
294        Self { peer_id: self.peer_id, to_session_tx: self.to_session_tx.clone() }
295    }
296}
297
298// === impl PeerRequestSender ===
299
300impl<R> PeerRequestSender<R> {
301    /// Constructs a new sender instance that's wired to a session
302    pub const fn new(peer_id: PeerId, to_session_tx: mpsc::Sender<R>) -> Self {
303        Self { peer_id, to_session_tx }
304    }
305
306    /// Attempts to immediately send a message on this Sender
307    pub fn try_send(&self, req: R) -> Result<(), mpsc::error::TrySendError<R>> {
308        self.to_session_tx.try_send(req)
309    }
310
311    /// Returns the peer id of the remote peer.
312    pub const fn peer_id(&self) -> &PeerId {
313        &self.peer_id
314    }
315}
316
317impl<R> fmt::Debug for PeerRequestSender<R> {
318    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
319        f.debug_struct("PeerRequestSender").field("peer_id", &self.peer_id).finish_non_exhaustive()
320    }
321}