Skip to main content

reth_network_api/
lib.rs

1//! Reth interface definitions and commonly used types for the reth-network crate.
2//!
3//! Provides abstractions for the reth-network crate.
4//!
5//! ## Feature Flags
6//!
7//! - `serde` (default): Enable serde support
8
9#![doc(
10    html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
11    html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
12    issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
13)]
14#![cfg_attr(docsrs, feature(doc_cfg))]
15
16/// Shared blob cell custody state.
17pub mod custody;
18pub mod downloaders;
19/// Network Error
20pub mod error;
21pub mod events;
22/// Implementation of network traits for that does nothing.
23pub mod noop;
24
25pub mod test_utils;
26use test_utils::PeersHandleProvider;
27
28pub use alloy_rpc_types_admin::EthProtocolInfo;
29pub use reth_network_p2p::{BlockClient, HeadersClient};
30pub use reth_network_types::{PeerKind, Reputation, ReputationChangeKind};
31
32pub use custody::CellCustody;
33pub use downloaders::BlockDownloaderProvider;
34pub use error::NetworkError;
35pub use events::{
36    DiscoveredEvent, DiscoveryEvent, NetworkEvent, NetworkEventListenerProvider, PeerRequest,
37    PeerRequestSender, RequestMessage,
38};
39
40use reth_eth_wire_types::{
41    capability::Capabilities, Capability, DisconnectReason, EthVersion, NetworkPrimitives,
42    UnifiedStatus,
43};
44use reth_network_p2p::sync::NetworkSyncUpdater;
45use reth_network_peers::NodeRecord;
46use std::{future::Future, net::SocketAddr, sync::Arc, time::Instant};
47
48/// The `PeerId` type.
49pub type PeerId = alloy_primitives::B512;
50
51/// Helper trait that unifies network API needed to launch node.
52pub trait FullNetwork:
53    BlockDownloaderProvider<
54        Client: BlockClient<Block = <Self::Primitives as NetworkPrimitives>::Block>,
55    > + NetworkSyncUpdater
56    + NetworkInfo
57    + NetworkEventListenerProvider
58    + Peers
59    + PeersHandleProvider
60    + Clone
61    + Unpin
62{
63}
64
65impl<T> FullNetwork for T where
66    T: BlockDownloaderProvider<
67            Client: BlockClient<Block = <Self::Primitives as NetworkPrimitives>::Block>,
68        > + NetworkSyncUpdater
69        + NetworkInfo
70        + NetworkEventListenerProvider
71        + Peers
72        + PeersHandleProvider
73        + Clone
74        + Unpin
75{
76}
77
78/// Provides general purpose information about the network.
79#[auto_impl::auto_impl(&, Arc)]
80pub trait NetworkInfo: Send + Sync {
81    /// Returns the [`SocketAddr`] that listens for incoming connections.
82    fn local_addr(&self) -> SocketAddr;
83
84    /// Returns the current status of the network being ran by the local node.
85    fn network_status(&self) -> impl Future<Output = Result<NetworkStatus, NetworkError>> + Send;
86
87    /// Returns the chain id
88    fn chain_id(&self) -> u64;
89
90    /// Returns shared blob cell custody state for [EIP-8070] sparse blobpool sampling.
91    ///
92    /// This is updated from non-null `custodyColumns` values received through
93    /// `engine_forkchoiceUpdatedV4` and should be treated as a lightweight sampling hint.
94    ///
95    /// [EIP-8070]: https://eips.ethereum.org/EIPS/eip-8070
96    fn cell_custody(&self) -> &CellCustody;
97
98    /// Returns `true` if the network is undergoing sync.
99    fn is_syncing(&self) -> bool;
100
101    /// Returns `true` when the node is undergoing the very first Pipeline sync.
102    fn is_initially_syncing(&self) -> bool;
103}
104
105/// Provides general purpose information about Peers in the network.
106#[auto_impl::auto_impl(&, Arc)]
107pub trait PeersInfo: Send + Sync {
108    /// Returns how many peers the network is currently connected to.
109    ///
110    /// Note: this should only include established connections and _not_ ongoing attempts.
111    fn num_connected_peers(&self) -> usize;
112
113    /// Returns the Ethereum Node Record of the node.
114    fn local_node_record(&self) -> NodeRecord;
115
116    /// Returns the local ENR of the node.
117    fn local_enr(&self) -> enr::Enr<enr::secp256k1::SecretKey>;
118}
119
120/// Provides an API for managing the peers of the network.
121#[auto_impl::auto_impl(&, Arc)]
122pub trait Peers: PeersInfo {
123    /// Adds a peer to the peer set with TCP `SocketAddr`.
124    ///
125    /// If the peer already exists, then this will update its tracked info.
126    fn add_peer(&self, peer: PeerId, tcp_addr: SocketAddr) {
127        self.add_peer_kind(peer, Some(PeerKind::Static), tcp_addr, None);
128    }
129
130    /// Adds a peer to the peer set with TCP and UDP `SocketAddr`.
131    ///
132    /// If the peer already exists, then this will update its tracked info.
133    fn add_peer_with_udp(&self, peer: PeerId, tcp_addr: SocketAddr, udp_addr: SocketAddr) {
134        self.add_peer_kind(peer, Some(PeerKind::Static), tcp_addr, Some(udp_addr));
135    }
136
137    /// Adds a trusted [`PeerId`] to the peer set.
138    ///
139    /// This allows marking a peer as trusted without having to know the peer's address.
140    fn add_trusted_peer_id(&self, peer: PeerId);
141
142    /// Adds a trusted peer to the peer set with TCP `SocketAddr`.
143    fn add_trusted_peer(&self, peer: PeerId, tcp_addr: SocketAddr) {
144        self.add_peer_kind(peer, Some(PeerKind::Trusted), tcp_addr, None);
145    }
146
147    /// Adds a trusted peer with TCP and UDP `SocketAddr` to the peer set.
148    fn add_trusted_peer_with_udp(&self, peer: PeerId, tcp_addr: SocketAddr, udp_addr: SocketAddr) {
149        self.add_peer_kind(peer, Some(PeerKind::Trusted), tcp_addr, Some(udp_addr));
150    }
151
152    /// Registers a trusted peer that may use a hostname instead of an IP address.
153    ///
154    /// Resolution is performed asynchronously by the periodic DNS resolver; the peer is
155    /// added to the peer set on first successful resolution and re-resolved periodically
156    /// so address changes are picked up automatically.
157    fn add_trusted_peer_node(&self, _peer: reth_network_peers::TrustedPeer) {}
158
159    /// Adds a peer to the known peer set, with the given kind.
160    ///
161    /// If the peer already exists, then this will update its tracked info.
162    fn add_peer_kind(
163        &self,
164        peer: PeerId,
165        kind: Option<PeerKind>,
166        tcp_addr: SocketAddr,
167        udp_addr: Option<SocketAddr>,
168    );
169
170    /// Returns the rpc [`PeerInfo`] for all connected [`PeerKind::Trusted`] peers.
171    fn get_trusted_peers(
172        &self,
173    ) -> impl Future<Output = Result<Vec<PeerInfo>, NetworkError>> + Send {
174        self.get_peers_by_kind(PeerKind::Trusted)
175    }
176
177    /// Returns the rpc [`PeerInfo`] for all connected [`PeerKind::Basic`] peers.
178    fn get_basic_peers(&self) -> impl Future<Output = Result<Vec<PeerInfo>, NetworkError>> + Send {
179        self.get_peers_by_kind(PeerKind::Basic)
180    }
181
182    /// Returns the rpc [`PeerInfo`] for all connected peers with the given kind.
183    fn get_peers_by_kind(
184        &self,
185        kind: PeerKind,
186    ) -> impl Future<Output = Result<Vec<PeerInfo>, NetworkError>> + Send;
187
188    /// Returns the rpc [`PeerInfo`] for all connected peers.
189    fn get_all_peers(&self) -> impl Future<Output = Result<Vec<PeerInfo>, NetworkError>> + Send;
190
191    /// Returns the rpc [`PeerInfo`] for the given peer id.
192    ///
193    /// Returns `None` if the peer is not connected.
194    fn get_peer_by_id(
195        &self,
196        peer_id: PeerId,
197    ) -> impl Future<Output = Result<Option<PeerInfo>, NetworkError>> + Send;
198
199    /// Returns the rpc [`PeerInfo`] for the given peers if they are connected.
200    ///
201    /// Note: This only returns peers that are connected, unconnected peers are ignored but keeping
202    /// the order in which they were requested.
203    fn get_peers_by_id(
204        &self,
205        peer_ids: Vec<PeerId>,
206    ) -> impl Future<Output = Result<Vec<PeerInfo>, NetworkError>> + Send;
207
208    /// Removes a peer from the peer set that corresponds to given kind.
209    fn remove_peer(&self, peer: PeerId, kind: PeerKind);
210
211    /// Disconnect an existing connection to the given peer.
212    fn disconnect_peer(&self, peer: PeerId);
213
214    /// Disconnect an existing connection to the given peer using the provided reason
215    fn disconnect_peer_with_reason(&self, peer: PeerId, reason: DisconnectReason);
216
217    /// Bans the given peer and disconnects an active non-trusted session if one exists.
218    fn ban_peer(&self, peer: PeerId);
219
220    /// Unbans the given peer.
221    fn unban_peer(&self, peer: PeerId);
222
223    /// Connect to the given peer. NOTE: if the maximum number of outbound sessions is reached,
224    /// this won't do anything. See `reth_network::SessionManager::dial_outbound`.
225    fn connect_peer(&self, peer: PeerId, tcp_addr: SocketAddr) {
226        self.connect_peer_kind(peer, PeerKind::Static, tcp_addr, None)
227    }
228
229    /// Connects a peer to the known peer set, with the given kind.
230    fn connect_peer_kind(
231        &self,
232        peer: PeerId,
233        kind: PeerKind,
234        tcp_addr: SocketAddr,
235        udp_addr: Option<SocketAddr>,
236    );
237
238    /// Send a reputation change for the given peer.
239    fn reputation_change(&self, peer_id: PeerId, kind: ReputationChangeKind);
240
241    /// Get the reputation of a peer.
242    fn reputation_by_id(
243        &self,
244        peer_id: PeerId,
245    ) -> impl Future<Output = Result<Option<Reputation>, NetworkError>> + Send;
246}
247
248/// Info about an active peer session.
249#[derive(Debug, Clone)]
250pub struct PeerInfo {
251    /// Announced capabilities of the peer
252    pub capabilities: Arc<Capabilities>,
253    /// The identifier of the remote peer
254    pub remote_id: PeerId,
255    /// The client's name and version
256    pub client_version: Arc<str>,
257    /// The peer's enode
258    pub enode: String,
259    /// The peer's enr
260    pub enr: Option<String>,
261    /// The peer's address we're connected to
262    pub remote_addr: SocketAddr,
263    /// The local address of the connection
264    pub local_addr: Option<SocketAddr>,
265    /// The direction of the session
266    pub direction: Direction,
267    /// The negotiated eth version.
268    pub eth_version: EthVersion,
269    /// The Status message the peer sent for the `eth` handshake
270    pub status: Arc<UnifiedStatus>,
271    /// The timestamp when the session to that peer has been established.
272    pub session_established: Instant,
273    /// The peer's connection kind
274    pub kind: PeerKind,
275}
276
277/// The direction of the connection.
278#[derive(Debug, Copy, Clone, PartialEq, Eq)]
279pub enum Direction {
280    /// Incoming connection.
281    Incoming,
282    /// Outgoing connection to a specific node.
283    Outgoing(PeerId),
284}
285
286impl Direction {
287    /// Returns `true` if this is an incoming connection.
288    pub const fn is_incoming(&self) -> bool {
289        matches!(self, Self::Incoming)
290    }
291
292    /// Returns `true` if this is an outgoing connection.
293    pub const fn is_outgoing(&self) -> bool {
294        matches!(self, Self::Outgoing(_))
295    }
296}
297
298impl std::fmt::Display for Direction {
299    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
300        match self {
301            Self::Incoming => write!(f, "incoming"),
302            Self::Outgoing(_) => write!(f, "outgoing"),
303        }
304    }
305}
306
307/// The status of the network being ran by the local node.
308#[derive(Clone, Debug)]
309#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
310pub struct NetworkStatus {
311    /// The local node client version.
312    pub client_version: String,
313    /// The current ethereum protocol version
314    pub protocol_version: u64,
315    /// Information about the Ethereum Wire Protocol.
316    pub eth_protocol_info: EthProtocolInfo,
317    /// The list of supported capabilities and their versions.
318    pub capabilities: Vec<Capability>,
319}