Skip to main content

reth_discv5/
lib.rs

1//! Wrapper around [`discv5::Discv5`].
2
3#![doc(
4    html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
5    html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
6    issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
7)]
8#![cfg_attr(not(test), warn(unused_crate_dependencies))]
9#![cfg_attr(docsrs, feature(doc_cfg))]
10
11use std::{
12    collections::HashSet,
13    fmt,
14    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
15    sync::Arc,
16    time::Duration,
17};
18
19use alloy_primitives::bytes::Bytes;
20use enr::{discv4_id_to_discv5_id, EnrCombinedKeyWrapper};
21use futures::future::join_all;
22use itertools::Itertools;
23use rand::{Rng, RngCore};
24use reth_ethereum_forks::{EnrForkIdEntry, ForkId};
25use reth_network_peers::{NodeRecord, PeerId};
26use secp256k1::SecretKey;
27use tokio::{sync::mpsc, task};
28use tracing::{debug, error, trace};
29
30pub mod config;
31pub mod enr;
32pub mod error;
33pub mod filter;
34pub mod metrics;
35pub mod network_stack_id;
36
37pub use ::enr::{CombinedKey, Enr, EnrKey, NodeId};
38pub use discv5::{self, IpMode};
39pub use libp2p_identity;
40
41pub use config::{
42    BootNode, Config, ConfigBuilder, DEFAULT_COUNT_BOOTSTRAP_LOOKUPS, DEFAULT_DISCOVERY_V5_ADDR,
43    DEFAULT_DISCOVERY_V5_ADDR_IPV6, DEFAULT_DISCOVERY_V5_LISTEN_CONFIG, DEFAULT_DISCOVERY_V5_PORT,
44    DEFAULT_SECONDS_BOOTSTRAP_LOOKUP_INTERVAL, DEFAULT_SECONDS_LOOKUP_INTERVAL,
45};
46pub use enr::enr_to_discv4_id;
47pub use error::Error;
48pub use filter::{FilterOutcome, MustNotIncludeKeys};
49pub use network_stack_id::NetworkStackId;
50
51use metrics::{DiscoveredPeersMetrics, Discv5Metrics};
52
53/// Max kbucket index is 255.
54///
55/// This is the max log2distance for 32 byte [`NodeId`] - 1. See <https://github.com/sigp/discv5/blob/e9e0d4f93ec35591832a9a8d937b4161127da87b/src/kbucket.rs#L586-L587>.
56pub const MAX_KBUCKET_INDEX: usize = 255;
57
58/// Default lowest kbucket index to attempt filling, in periodic look up query to populate kbuckets.
59///
60/// The peer at the 0th kbucket index is at log2distance 1 from the local node ID. See <https://github.com/sigp/discv5/blob/e9e0d4f93ec35591832a9a8d937b4161127da87b/src/kbucket.rs#L586-L587>.
61///
62/// Default is 0th index.
63pub const DEFAULT_MIN_TARGET_KBUCKET_INDEX: usize = 0;
64
65/// Transparent wrapper around [`discv5::Discv5`].
66#[derive(Clone)]
67pub struct Discv5 {
68    /// sigp/discv5 node.
69    discv5: Arc<discv5::Discv5>,
70    /// [`IpMode`] of the `RLPx` network.
71    rlpx_ip_mode: IpMode,
72    /// Key used in kv-pair to ID chain, e.g. 'opstack' or 'eth'.
73    fork_key: Option<&'static [u8]>,
74    /// Filter applied to a discovered peers before passing it up to app.
75    discovered_peer_filter: MustNotIncludeKeys,
76    /// Metrics for underlying [`discv5::Discv5`] node and filtered discovered peers.
77    metrics: Discv5Metrics,
78    /// Returns the _local_ [`NodeRecord`] this service was started with.
79    // Note: we must track this separately because the `discv5::Discv5` does not necessarily
80    // provide this via its [`local_enr`](discv5::Discv5::local_enr()). This is intended for
81    // obtaining the port this service was launched at
82    local_node_record: NodeRecord,
83}
84
85impl Discv5 {
86    ////////////////////////////////////////////////////////////////////////////////////////////////
87    // Minimal interface with `reth_network::discovery`
88    ////////////////////////////////////////////////////////////////////////////////////////////////
89
90    /// Adds the node to the table, if it is not already present.
91    pub fn add_node(&self, node_record: Enr<SecretKey>) -> Result<(), Error> {
92        let EnrCombinedKeyWrapper(enr) = node_record.try_into().map_err(Error::InvalidEnr)?;
93        self.discv5.add_enr(enr).map_err(Error::AddNodeFailed)
94    }
95
96    /// Sets the pair in the EIP-868 [`Enr`] of the node.
97    ///
98    /// If the key already exists, this will update it.
99    ///
100    /// CAUTION: The value **must** be rlp encoded
101    pub fn set_eip868_in_local_enr(&self, key: Vec<u8>, rlp: Bytes) {
102        let Ok(key_str) = std::str::from_utf8(&key) else {
103            error!(target: "net::discv5",
104                err="key not utf-8",
105                "failed to update local enr"
106            );
107            return
108        };
109        if let Err(err) = self.discv5.enr_insert(key_str, &rlp) {
110            error!(target: "net::discv5",
111                %err,
112                "failed to update local enr"
113            );
114        }
115    }
116
117    /// Sets the pair in the EIP-868 [`Enr`] of the node.
118    ///
119    /// If the key already exists, this will update it.
120    pub fn encode_and_set_eip868_in_local_enr(
121        &self,
122        key: Vec<u8>,
123        value: impl alloy_rlp::Encodable,
124    ) {
125        let mut buf = Vec::new();
126        value.encode(&mut buf);
127        self.set_eip868_in_local_enr(key, buf.into())
128    }
129
130    /// Adds the peer and id to the ban list.
131    ///
132    /// This will prevent any future inclusion in the table
133    pub fn ban(&self, peer_id: PeerId, ip: IpAddr) {
134        self.ban_with(peer_id, ip, None)
135    }
136
137    /// Adds the ip to the ban list.
138    ///
139    /// This will prevent any future inclusion in the table
140    pub fn ban_ip(&self, ip: IpAddr) {
141        self.ban_ip_with(ip, None)
142    }
143
144    /// Adds the peer and ip to the ban list for the given duration, or indefinitely if `None`.
145    ///
146    /// This replaces any existing ban of the peer or ip, including an indefinite one.
147    pub fn ban_with(&self, peer_id: PeerId, ip: IpAddr, duration: Option<Duration>) {
148        match discv4_id_to_discv5_id(peer_id) {
149            Ok(node_id) => {
150                self.discv5.ban_node(&node_id, duration);
151                self.ban_ip_with(ip, duration);
152            }
153            Err(err) => error!(target: "net::discv5",
154                %err,
155                "failed to ban peer"
156            ),
157        }
158    }
159
160    /// Adds the ip to the ban list for the given duration, or indefinitely if `None`.
161    ///
162    /// This replaces any existing ban of the ip, including an indefinite one.
163    pub fn ban_ip_with(&self, ip: IpAddr, duration: Option<Duration>) {
164        self.discv5.ban_ip(ip, duration);
165    }
166
167    /// Returns the [`NodeRecord`] of the local node.
168    ///
169    /// This includes the currently tracked external IP address of the node.
170    ///
171    /// Returns `None` if the local ENR does not contain the required fields.
172    pub fn node_record(&self) -> Option<NodeRecord> {
173        let enr: Enr<_> = EnrCombinedKeyWrapper(self.discv5.local_enr()).into();
174        enr.try_into().ok()
175    }
176
177    /// Returns the local [`Enr`] of the service.
178    pub fn local_enr(&self) -> Enr<CombinedKey> {
179        self.discv5.local_enr()
180    }
181
182    /// The port the discv5 service is listening on.
183    pub const fn local_port(&self) -> u16 {
184        self.local_node_record.udp_port
185    }
186
187    /// Spawns [`discv5::Discv5`]. Returns [`discv5::Discv5`] handle in reth compatible wrapper type
188    /// [`Discv5`], a receiver of [`discv5::Event`]s from the underlying node, and the local
189    /// [`Enr`](discv5::Enr) converted into the reth compatible [`NodeRecord`] type.
190    pub async fn start(
191        sk: &SecretKey,
192        discv5_config: Config,
193    ) -> Result<(Self, mpsc::Receiver<discv5::Event>), Error> {
194        //
195        // 1. make local enr from listen config
196        //
197        let (enr, local_node_record, fork_key, rlpx_ip_mode) = build_local_enr(sk, &discv5_config);
198
199        trace!(target: "net::discv5", ?enr, "local ENR");
200
201        //
202        // 2. start discv5
203        //
204        let Config {
205            discv5_config,
206            bootstrap_nodes,
207            lookup_interval,
208            bootstrap_lookup_interval,
209            bootstrap_lookup_countdown,
210            discovered_peer_filter,
211            ..
212        } = discv5_config;
213
214        let EnrCombinedKeyWrapper(enr) = enr.try_into().map_err(Error::InvalidEnr)?;
215        let sk = CombinedKey::secp256k1_from_bytes(&mut sk.to_secret_bytes()).unwrap();
216        let mut discv5 = match discv5::Discv5::new(enr, sk, discv5_config) {
217            Ok(discv5) => discv5,
218            Err(err) => return Err(Error::InitFailure(err)),
219        };
220        discv5.start().await.map_err(Error::Discv5Error)?;
221
222        // start discv5 updates stream
223        let discv5_updates = discv5.event_stream().await.map_err(Error::Discv5Error)?;
224
225        let discv5 = Arc::new(discv5);
226
227        //
228        // 3. add boot nodes
229        //
230        bootstrap(bootstrap_nodes, &discv5).await?;
231
232        let metrics = Discv5Metrics::default();
233
234        //
235        // 4. start bg kbuckets maintenance
236        //
237        spawn_populate_kbuckets_bg(
238            lookup_interval,
239            bootstrap_lookup_interval,
240            bootstrap_lookup_countdown,
241            metrics.clone(),
242            Arc::downgrade(&discv5),
243        );
244
245        Ok((
246            Self {
247                discv5,
248                rlpx_ip_mode,
249                fork_key,
250                discovered_peer_filter,
251                metrics,
252                local_node_record,
253            },
254            discv5_updates,
255        ))
256    }
257
258    /// Process an event from the underlying [`discv5::Discv5`] node.
259    pub fn on_discv5_update(&self, update: discv5::Event) -> Option<DiscoveredPeer> {
260        #[expect(clippy::match_same_arms)]
261        match update {
262            discv5::Event::SocketUpdated(_) | discv5::Event::TalkRequest(_) |
263            // `Discovered` not unique discovered peers
264            discv5::Event::Discovered(_) |
265            // Unrecognized frames are handled separately by the discovery layer
266            discv5::Event::UnrecognizedFrame(_) => None,
267            discv5::Event::NodeInserted { .. } => {
268
269                // node has been inserted into kbuckets
270
271                // `replaced` partly covers `reth_discv4::DiscoveryUpdate::Removed(_)`
272
273                self.metrics.discovered_peers.increment_kbucket_insertions(1);
274
275                None
276            }
277            discv5::Event::SessionEstablished(enr, remote_socket) => {
278                // this branch is semantically similar to branches of
279                // `reth_discv4::DiscoveryUpdate`: `DiscoveryUpdate::Added(_)` and
280                // `DiscoveryUpdate::DiscoveredAtCapacity(_)
281
282                // peer has been discovered as part of query, or, by incoming session (peer has
283                // discovered us)
284
285                self.metrics.discovered_peers.increment_established_sessions_raw(1);
286
287                self.on_discovered_peer(&enr, remote_socket)
288            }
289            discv5::Event::UnverifiableEnr {
290                enr,
291                socket,
292                node_id: _,
293            } => {
294                // this branch is semantically similar to branches of
295                // `reth_discv4::DiscoveryUpdate`: `DiscoveryUpdate::Added(_)` and
296                // `DiscoveryUpdate::DiscoveredAtCapacity(_)
297
298                // peer has been discovered as part of query, or, by an outgoing session (but peer
299                // is behind NAT and responds from a different socket)
300
301                // NOTE: `discv5::Discv5` won't initiate a session with any peer with an
302                // unverifiable node record, for example one that advertises a reserved LAN IP
303                // address on a WAN network. This is in order to prevent DoS attacks, where some
304                // malicious peers may advertise a victim's socket. We will still try and connect
305                // to them over RLPx, to be compatible with EL discv5 implementations that don't
306                // enforce this security measure.
307
308                trace!(target: "net::discv5",
309                    ?enr,
310                    %socket,
311                    "discovered unverifiable enr, source socket doesn't match socket advertised in ENR"
312                );
313
314                self.metrics.discovered_peers.increment_unverifiable_enrs_raw_total(1);
315
316                self.on_discovered_peer(&enr, socket)
317            }
318            _ => None
319        }
320    }
321
322    /// Processes a discovered peer. Returns `true` if peer is added to
323    pub fn on_discovered_peer(
324        &self,
325        enr: &discv5::Enr,
326        socket: SocketAddr,
327    ) -> Option<DiscoveredPeer> {
328        self.metrics.discovered_peers_advertised_networks.increment_once_by_network_type(enr);
329
330        let node_record = match self.try_into_reachable(enr, socket) {
331            Ok(enr_bc) => enr_bc,
332            Err(err) => {
333                trace!(target: "net::discv5",
334                    %err,
335                    ?enr,
336                    "discovered peer is unreachable"
337                );
338
339                self.metrics.discovered_peers.increment_established_sessions_unreachable_enr(1);
340
341                return None
342            }
343        };
344        if let FilterOutcome::Ignore { reason } = self.filter_discovered_peer(enr) {
345            trace!(target: "net::discv5",
346                ?enr,
347                reason,
348                "filtered out discovered peer"
349            );
350
351            self.metrics.discovered_peers.increment_established_sessions_filtered(1);
352
353            return None
354        }
355
356        let fork_id = self.get_fork_id(enr).ok();
357
358        trace!(target: "net::discv5",
359            ?fork_id,
360            ?enr,
361            "discovered peer"
362        );
363
364        Some(DiscoveredPeer { node_record, fork_id })
365    }
366
367    /// Tries to recover an unreachable [`Enr`](discv5::Enr) received via
368    /// [`discv5::Event::UnverifiableEnr`], into a [`NodeRecord`] usable by `RLPx`.
369    ///
370    /// NOTE: Fallback solution to be compatible with Geth which includes peers into the discv5
371    /// WAN topology which, for example, advertise in their ENR that localhost is their UDP IP
372    /// address. These peers are only discovered if they initiate a connection attempt, and we by
373    /// such means learn their reachable IP address. If we receive their ENR from any other peer
374    /// as part of a lookup query, we won't find a reachable IP address on which to dial them by
375    /// reading their ENR.
376    pub fn try_into_reachable(
377        &self,
378        enr: &discv5::Enr,
379        socket: SocketAddr,
380    ) -> Result<NodeRecord, Error> {
381        // Use the sender's address as received so discovery IP bans match source sockets.
382        let address = socket.ip();
383        let udp_port = socket.port();
384
385        let id = enr_to_discv4_id(enr).ok_or(Error::IncompatibleKeyType)?;
386
387        // The port must pair with the session socket's address, so select the
388        // ENR field by the socket's address family, not by the local node's
389        // RLPx listen family: an IPv4 session dials the `tcp` port, an IPv6
390        // session the `tcp6` port (falling back to `tcp`).
391        // Mapped IPv4 sessions use `tcp`, while the record retains the original socket address.
392        let tcp_port = (match address.to_canonical() {
393            IpAddr::V4(_) => enr.tcp4(),
394            IpAddr::V6(_) => enr.tcp6().or_else(|| enr.tcp4()),
395        })
396        .unwrap_or(
397            // tcp socket is missing from ENR for the session's address family.
398            //
399            // by default geth runs discv5 and discv4 behind the same udp port (the discv4 default
400            // port 30303), so rlpx has a chance of successfully dialing the peer on its discv5
401            // udp port if its running geth's p2p code.
402            udp_port,
403        );
404
405        Ok(NodeRecord { address, tcp_port, udp_port, id })
406    }
407
408    /// Applies filtering rules on an ENR. Returns [`Ok`](FilterOutcome::Ok) if peer should be
409    /// passed up to app, and [`Ignore`](FilterOutcome::Ignore) if peer should instead be dropped.
410    pub fn filter_discovered_peer(&self, enr: &discv5::Enr) -> FilterOutcome {
411        self.discovered_peer_filter.filter(enr)
412    }
413
414    /// Returns the [`ForkId`] of the given [`Enr`](discv5::Enr) w.r.t. the local node's network
415    /// stack, if field is set.
416    pub fn get_fork_id<K: EnrKey>(&self, enr: &Enr<K>) -> Result<ForkId, Error> {
417        let Some(key) = self.fork_key else { return Err(Error::NetworkStackIdNotConfigured) };
418        let fork_id = enr
419            .get_decodable::<EnrForkIdEntry>(key)
420            .or_else(|| {
421                (key != NetworkStackId::ETH)
422                    .then(|| {
423                        // Fallback: trying to get fork id from Enr with 'eth' as network stack id
424                        trace!(target: "net::discv5",
425                            key = %String::from_utf8_lossy(key),
426                            "Fork id not found for key, trying 'eth'..."
427                        );
428                        enr.get_decodable::<EnrForkIdEntry>(NetworkStackId::ETH)
429                    })
430                    .flatten()
431            })
432            .ok_or({
433                trace!(target: "net::discv5", "Fork id not found for 'eth' network stack id");
434                Error::ForkMissing(key)
435            })?
436            .map(Into::into)?;
437
438        Ok(fork_id)
439    }
440
441    ////////////////////////////////////////////////////////////////////////////////////////////////
442    // Interface with sigp/discv5
443    ////////////////////////////////////////////////////////////////////////////////////////////////
444
445    /// Exposes API of [`discv5::Discv5`].
446    pub fn with_discv5<F, R>(&self, f: F) -> R
447    where
448        F: FnOnce(&discv5::Discv5) -> R,
449    {
450        f(&self.discv5)
451    }
452
453    ////////////////////////////////////////////////////////////////////////////////////////////////
454    // Complementary
455    ////////////////////////////////////////////////////////////////////////////////////////////////
456
457    /// Returns the `RLPx` [`IpMode`] of the local node.
458    pub const fn ip_mode(&self) -> IpMode {
459        self.rlpx_ip_mode
460    }
461
462    /// Returns the key to use to identify the [`ForkId`] kv-pair on the [`Enr`](discv5::Enr).
463    pub const fn fork_key(&self) -> Option<&[u8]> {
464        self.fork_key
465    }
466}
467
468impl fmt::Debug for Discv5 {
469    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
470        "{ .. }".fmt(f)
471    }
472}
473
474/// Result of successfully processing a peer discovered by [`discv5::Discv5`].
475#[derive(Debug)]
476pub struct DiscoveredPeer {
477    /// A discovery v4 backwards compatible ENR.
478    pub node_record: NodeRecord,
479    /// [`ForkId`] extracted from ENR w.r.t. configured
480    pub fork_id: Option<ForkId>,
481}
482
483/// Builds the local ENR with the supplied key.
484pub fn build_local_enr(
485    sk: &SecretKey,
486    config: &Config,
487) -> (Enr<SecretKey>, NodeRecord, Option<&'static [u8]>, IpMode) {
488    let mut builder = Enr::builder();
489
490    let Config {
491        discv5_config,
492        fork,
493        tcp_socket,
494        advertised_ipv4,
495        advertised_ipv6,
496        other_enr_kv_pairs,
497        ..
498    } = config;
499
500    let socket = {
501        let v4 = crate::config::ipv4(&discv5_config.listen_config);
502        let v6 = crate::config::ipv6(&discv5_config.listen_config);
503
504        // Prefer an explicit advertised IP for ENR IP fields. Listen sockets still supply UDP
505        // ports and determine which address-family fields are emitted.
506        if let Some(addr) = v4 {
507            if let Some(ip) = advertised_ipv4 {
508                builder.ip4(*ip);
509            } else if *addr.ip() != Ipv4Addr::UNSPECIFIED {
510                builder.ip4(*addr.ip());
511            }
512            builder.udp4(addr.port());
513        }
514        if let Some(addr) = v6 {
515            if let Some(ip) = advertised_ipv6 {
516                builder.ip6(*ip);
517            } else if *addr.ip() != Ipv6Addr::UNSPECIFIED {
518                builder.ip6(*addr.ip());
519            }
520            builder.udp6(addr.port());
521        }
522        // Advertise tcp4 when v4 is configured, else tcp6.
523        if v4.is_some() {
524            builder.tcp4(tcp_socket.port());
525        } else if v6.is_some() {
526            builder.tcp6(tcp_socket.port());
527        }
528
529        // Prefer v6 when both are configured
530        v6.map(SocketAddr::V6)
531            .or_else(|| v4.map(SocketAddr::V4))
532            .unwrap_or_else(|| SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0)))
533    };
534
535    let rlpx_ip_mode = if tcp_socket.is_ipv4() { IpMode::Ip4 } else { IpMode::Ip6 };
536
537    // identifies which network node is on
538    let network_stack_id = fork.as_ref().map(|(network_stack_id, fork_value)| {
539        builder.add_value_rlp(network_stack_id, alloy_rlp::encode(fork_value).into());
540        *network_stack_id
541    });
542
543    // add other data
544    for (key, value) in other_enr_kv_pairs {
545        builder.add_value_rlp(key, value.clone().into());
546    }
547
548    // enr v4 not to get confused with discv4, independent versioning enr and
549    // discovery
550    let enr = builder.build(sk).expect("should build enr v4");
551
552    // backwards compatible enr
553    let bc_enr = NodeRecord::from_secret_key(socket, sk);
554
555    (enr, bc_enr, network_stack_id, rlpx_ip_mode)
556}
557
558/// Bootstraps underlying [`discv5::Discv5`] node with configured peers.
559///
560/// Boot nodes given as an ENR are added to the kbuckets right away. Boot nodes given as an enode
561/// need their ENR requested over the wire first, which is driven in the background: an unreachable
562/// boot node only answers after the discv5 request timeout, and waiting for that would stall node
563/// startup.
564///
565/// Stays `async` because spawning those requests requires a tokio runtime context.
566pub async fn bootstrap(
567    bootstrap_nodes: HashSet<BootNode>,
568    discv5: &Arc<discv5::Discv5>,
569) -> Result<(), Error> {
570    trace!(target: "net::discv5",
571        ?bootstrap_nodes,
572        "adding bootstrap nodes .."
573    );
574
575    let mut enr_requests = vec![];
576    for node in bootstrap_nodes {
577        match node {
578            BootNode::Enr(node) => {
579                if let Err(err) = discv5.add_enr(node) {
580                    return Err(Error::AddNodeFailed(err))
581                }
582            }
583            BootNode::Enode(enode) => {
584                let discv5 = discv5.clone();
585                enr_requests.push(async move {
586                    if let Err(err) = discv5.request_enr(enode.to_string()).await {
587                        debug!(target: "net::discv5",
588                            ?enode,
589                            %err,
590                            "failed adding boot node"
591                        );
592                    }
593                })
594            }
595        }
596    }
597
598    // If a session is established, the ENR is added straight away to discv5 kbuckets
599    if !enr_requests.is_empty() {
600        task::spawn(join_all(enr_requests));
601    }
602
603    Ok(())
604}
605
606/// Backgrounds regular look up queries, in order to keep kbuckets populated.
607pub fn spawn_populate_kbuckets_bg(
608    lookup_interval: u64,
609    bootstrap_lookup_interval: u64,
610    bootstrap_lookup_countdown: u64,
611    metrics: Discv5Metrics,
612    discv5: std::sync::Weak<discv5::Discv5>,
613) {
614    let lookup_interval = Duration::from_secs(lookup_interval);
615    let metrics = metrics.discovered_peers;
616    let mut kbucket_index = MAX_KBUCKET_INDEX;
617    let pulse_lookup_interval = Duration::from_secs(bootstrap_lookup_interval);
618    task::spawn(async move {
619        let Some(discv5_handle) = discv5.upgrade() else {
620            return;
621        };
622        let local_node_id = discv5_handle.local_enr().node_id();
623        drop(discv5_handle);
624
625        // make many fast lookup queries at bootstrap, trying to fill kbuckets at furthest
626        // log2distance from local node
627        for i in (0..bootstrap_lookup_countdown).rev() {
628            let target = NodeId::random();
629
630            trace!(target: "net::discv5",
631                %target,
632                bootstrap_boost_runs_countdown=i,
633                lookup_interval=format!("{:#?}", pulse_lookup_interval),
634                "starting bootstrap boost lookup query"
635            );
636
637            {
638                let Some(discv5_handle) = discv5.upgrade() else {
639                    return;
640                };
641                lookup(target, &discv5_handle, &metrics).await;
642            }
643
644            tokio::time::sleep(pulse_lookup_interval).await;
645        }
646
647        // initiate regular lookups to populate kbuckets
648        loop {
649            // make sure node is connected to each subtree in the network by target
650            // selection (ref kademlia)
651            let target = get_lookup_target(kbucket_index, local_node_id);
652
653            trace!(target: "net::discv5",
654                %target,
655                lookup_interval=format!("{:#?}", lookup_interval),
656                "starting periodic lookup query"
657            );
658
659            {
660                let Some(discv5_handle) = discv5.upgrade() else {
661                    return;
662                };
663                lookup(target, &discv5_handle, &metrics).await;
664            }
665
666            if kbucket_index > DEFAULT_MIN_TARGET_KBUCKET_INDEX {
667                // try to populate bucket one step closer
668                kbucket_index -= 1
669            } else {
670                // start over with bucket furthest away
671                kbucket_index = MAX_KBUCKET_INDEX
672            }
673
674            tokio::time::sleep(lookup_interval).await;
675        }
676    });
677}
678
679/// Gets the next lookup target, based on which bucket is currently being targeted.
680pub fn get_lookup_target(kbucket_index: usize, local_node_id: NodeId) -> NodeId {
681    // init target
682    let mut target = local_node_id.raw();
683
684    // make sure target has a 'log2distance'-long suffix that differs from local node id
685    let bit_offset = MAX_KBUCKET_INDEX.saturating_sub(kbucket_index);
686    let (byte, bit) = (bit_offset / 8, bit_offset % 8);
687    // Flip the target bit.
688    target[byte] ^= 1 << (7 - bit);
689
690    // Randomize the bits after the target.
691    let mut rng = rand::rng();
692    // Randomize remaining bits in the byte we modified.
693    if bit < 7 {
694        // Compute the mask of the bits that need to be randomized.
695        let bits_to_randomize = 0xff >> (bit + 1);
696        // Clear.
697        target[byte] &= !bits_to_randomize;
698        // Randomize.
699        target[byte] |= rng.random::<u8>() & bits_to_randomize;
700    }
701    // Randomize remaining bytes.
702    rng.fill_bytes(&mut target[byte + 1..]);
703
704    target.into()
705}
706
707/// Runs a [`discv5::Discv5`] lookup query.
708pub async fn lookup(target: NodeId, discv5: &discv5::Discv5, metrics: &DiscoveredPeersMetrics) {
709    metrics.set_total_sessions(discv5::Discv5::metrics().active_sessions);
710    metrics.set_total_kbucket_peers(
711        discv5.with_kbuckets(|kbuckets| kbuckets.read().iter_ref().count()),
712    );
713
714    match discv5.find_node(target).await {
715        Err(err) => trace!(target: "net::discv5",
716            %err,
717            "lookup query failed"
718        ),
719        Ok(peers) => trace!(target: "net::discv5",
720            target=format!("{:#?}", target),
721            peers_count=peers.len(),
722            peers=format!("[{:#}]", peers.iter()
723                .map(|enr| enr.node_id()
724            ).format(", ")),
725            "peers returned by lookup query"
726        ),
727    }
728
729    // `Discv5::connected_peers` can be subset of sessions, not all peers make it
730    // into kbuckets, e.g. incoming sessions from peers with
731    // unreachable enrs
732    debug!(target: "net::discv5",
733        connected_peers=discv5.connected_peers(),
734        "connected peers in routing table"
735    );
736}
737
738#[cfg(test)]
739mod test {
740    #![allow(deprecated)]
741    use super::*;
742    use ::enr::{CombinedKey, EnrKey};
743    use discv5::ListenConfig;
744    use rand::rng;
745    use reth_chainspec::MAINNET;
746    use std::{
747        net::UdpSocket,
748        time::{Duration, Instant},
749    };
750    use tracing::trace;
751
752    fn discv5_noop() -> Discv5 {
753        let sk = CombinedKey::generate_secp256k1();
754        Discv5 {
755            discv5: Arc::new(
756                discv5::Discv5::new(
757                    Enr::empty(&sk).unwrap(),
758                    sk,
759                    discv5::ConfigBuilder::new(DEFAULT_DISCOVERY_V5_LISTEN_CONFIG).build(),
760                )
761                .unwrap(),
762            ),
763            rlpx_ip_mode: IpMode::Ip4,
764            fork_key: None,
765            discovered_peer_filter: MustNotIncludeKeys::default(),
766            metrics: Discv5Metrics::default(),
767            local_node_record: NodeRecord::new(
768                (Ipv4Addr::LOCALHOST, 30303).into(),
769                PeerId::random(),
770            ),
771        }
772    }
773
774    async fn start_discovery_node(udp_port_discv5: u16) -> (Discv5, mpsc::Receiver<discv5::Event>) {
775        let secret_key = SecretKey::new(&mut rng());
776
777        let discv5_addr: SocketAddr = format!("127.0.0.1:{udp_port_discv5}").parse().unwrap();
778        let rlpx_addr: SocketAddr = "127.0.0.1:30303".parse().unwrap();
779
780        let discv5_listen_config = ListenConfig::from(discv5_addr);
781        let discv5_config = Config::builder(rlpx_addr)
782            .discv5_config(discv5::ConfigBuilder::new(discv5_listen_config).build())
783            .build();
784
785        Discv5::start(&secret_key, discv5_config).await.expect("should build discv5")
786    }
787
788    async fn start_discovery_node_with_key(
789        secret_key: &SecretKey,
790        udp_port_discv5: u16,
791    ) -> Result<(Discv5, mpsc::Receiver<discv5::Event>), Error> {
792        let discv5_addr: SocketAddr = format!("127.0.0.1:{udp_port_discv5}").parse().unwrap();
793        let rlpx_addr: SocketAddr = "127.0.0.1:30303".parse().unwrap();
794
795        let discv5_listen_config = ListenConfig::from(discv5_addr);
796        let discv5_config = Config::builder(rlpx_addr)
797            .discv5_config(discv5::ConfigBuilder::new(discv5_listen_config).build())
798            .build();
799
800        Discv5::start(secret_key, discv5_config).await
801    }
802
803    fn unused_udp_port() -> u16 {
804        UdpSocket::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
805    }
806
807    async fn wait_for_udp_port_release(port: u16, timeout: Duration) {
808        let deadline = Instant::now() + timeout;
809
810        loop {
811            match UdpSocket::bind(("127.0.0.1", port)) {
812                Ok(socket) => {
813                    drop(socket);
814                    return;
815                }
816                Err(err) if Instant::now() < deadline => {
817                    trace!(target: "net::discv5::test", %port, %err, "waiting for discv5 port release");
818                    tokio::time::sleep(Duration::from_millis(10)).await;
819                }
820                Err(err) => panic!("discv5 did not release port {port} before timeout: {err}"),
821            }
822        }
823    }
824
825    #[tokio::test(flavor = "multi_thread")]
826    async fn discv5_releases_port_on_drop() {
827        reth_tracing::init_test_tracing();
828
829        let secret_key = SecretKey::new(&mut rng());
830        let port = unused_udp_port();
831
832        let (node, updates) =
833            start_discovery_node_with_key(&secret_key, port).await.expect("should start discv5");
834        drop(updates);
835        drop(node);
836
837        wait_for_udp_port_release(port, Duration::from_secs(1)).await;
838
839        let restarted = start_discovery_node_with_key(&secret_key, port).await;
840        assert!(restarted.is_ok(), "discv5 failed to rebind dropped port: {restarted:?}");
841    }
842
843    #[tokio::test(flavor = "multi_thread")]
844    async fn discv5() {
845        reth_tracing::init_test_tracing();
846
847        // rig test
848
849        // rig node_1
850        let (node_1, mut stream_1) = start_discovery_node(30344).await;
851        let node_1_enr = node_1.with_discv5(|discv5| discv5.local_enr());
852
853        // rig node_2
854        let (node_2, mut stream_2) = start_discovery_node(30355).await;
855        let node_2_enr = node_2.with_discv5(|discv5| discv5.local_enr());
856
857        trace!(target: "net::discv5::test",
858            node_1_node_id=format!("{:#}", node_1_enr.node_id()),
859            node_2_node_id=format!("{:#}", node_2_enr.node_id()),
860            "started nodes"
861        );
862
863        // test
864
865        // add node_2 to discovery handle of node_1 (should add node to discv5 kbuckets)
866        let node_2_enr_reth_compatible_ty: Enr<SecretKey> =
867            EnrCombinedKeyWrapper(node_2_enr.clone()).into();
868        node_1.add_node(node_2_enr_reth_compatible_ty).unwrap();
869
870        // verify node_2 is in KBuckets of node_1:discv5
871        assert!(
872            node_1.with_discv5(|discv5| discv5.table_entries_id().contains(&node_2_enr.node_id()))
873        );
874
875        // manually trigger connection from node_1 to node_2
876        node_1.with_discv5(|discv5| discv5.send_ping(node_2_enr.clone())).await.unwrap();
877
878        // verify node_1:discv5 is connected to node_2:discv5 and vv
879        let event_1_v5 = stream_1.recv().await.unwrap();
880
881        assert!(matches!(
882            event_1_v5,
883            discv5::Event::SessionEstablished(node, socket) if node == node_2_enr && socket == node_2_enr.udp4_socket().unwrap().into()
884        ));
885
886        // verify node_1 is in KBuckets of node_2:discv5
887        let event_2_v5 = stream_2.recv().await.unwrap();
888        assert!(matches!(
889            event_2_v5,
890            discv5::Event::NodeInserted { node_id, replaced } if node_id == node_1_enr.node_id() && replaced.is_none()
891        ));
892    }
893
894    #[test]
895    fn discovered_enr_disc_socket_missing() {
896        reth_tracing::init_test_tracing();
897
898        // rig test
899        const REMOTE_RLPX_PORT: u16 = 30303;
900        let remote_socket = "104.28.44.25:9000".parse().unwrap();
901        let remote_key = CombinedKey::generate_secp256k1();
902        let remote_enr = Enr::builder().tcp4(REMOTE_RLPX_PORT).build(&remote_key).unwrap();
903
904        let discv5 = discv5_noop();
905
906        // test
907        let filtered_peer = discv5.on_discovered_peer(&remote_enr, remote_socket);
908
909        assert_eq!(
910            NodeRecord {
911                address: remote_socket.ip(),
912                udp_port: remote_socket.port(),
913                tcp_port: REMOTE_RLPX_PORT,
914                id: enr_to_discv4_id(&remote_enr).unwrap(),
915            },
916            filtered_peer.unwrap().node_record
917        )
918    }
919
920    #[test]
921    fn reachable_tcp_port_follows_session_address_family() {
922        // Regression test for https://github.com/paradigmxyz/reth/issues/27734:
923        // the TCP port paired with the session socket's IP must come from the
924        // ENR field of the *session's* address family, not the local node's
925        // RLPx listen family.
926        const TCP4_PORT: u16 = 30304;
927        const TCP6_PORT: u16 = 30306;
928        let remote_key = CombinedKey::generate_secp256k1();
929        let remote_enr = Enr::builder().tcp4(TCP4_PORT).tcp6(TCP6_PORT).build(&remote_key).unwrap();
930
931        let v4_socket: SocketAddr = "127.0.0.1:30305".parse().unwrap();
932        let v6_socket: SocketAddr = "[::1]:30307".parse().unwrap();
933
934        for local_mode in [IpMode::Ip4, IpMode::Ip6] {
935            let mut discv5 = discv5_noop();
936            discv5.rlpx_ip_mode = local_mode;
937
938            let record = discv5.try_into_reachable(&remote_enr, v4_socket).unwrap();
939            assert_eq!(
940                record.tcp_port, TCP4_PORT,
941                "v4 session with local mode {local_mode:?} must dial the tcp4 port"
942            );
943            assert_eq!(record.address, v4_socket.ip());
944            assert_eq!(record.udp_port, v4_socket.port());
945
946            let record = discv5.try_into_reachable(&remote_enr, v6_socket).unwrap();
947            assert_eq!(
948                record.tcp_port, TCP6_PORT,
949                "v6 session with local mode {local_mode:?} must dial the tcp6 port"
950            );
951            assert_eq!(record.address, v6_socket.ip());
952            assert_eq!(record.udp_port, v6_socket.port());
953        }
954    }
955
956    #[test]
957    fn reachable_ipv4_mapped_session_uses_tcp4() {
958        const TCP4_PORT: u16 = 30304;
959        const TCP6_PORT: u16 = 30306;
960        let remote_key = CombinedKey::generate_secp256k1();
961        let remote_enr = Enr::builder().tcp4(TCP4_PORT).tcp6(TCP6_PORT).build(&remote_key).unwrap();
962        let mapped_socket: SocketAddr = "[::ffff:104.28.44.25]:9000".parse().unwrap();
963
964        for local_mode in [IpMode::Ip4, IpMode::Ip6] {
965            let mut discv5 = discv5_noop();
966            discv5.rlpx_ip_mode = local_mode;
967
968            let record = discv5.try_into_reachable(&remote_enr, mapped_socket).unwrap();
969            assert_eq!(record.tcp_port, TCP4_PORT);
970            assert_eq!(record.address, mapped_socket.ip());
971            assert_eq!(record.udp_port, mapped_socket.port());
972
973            let peer = discv5.on_discovered_peer(&remote_enr, mapped_socket).unwrap();
974            assert_eq!(peer.node_record, record);
975        }
976    }
977
978    #[test]
979    fn reachable_tcp_port_v6_session_falls_back_to_tcp4() {
980        // A v6 session whose ENR carries only a `tcp` (v4) port uses that port
981        // rather than the session's UDP port.
982        const TCP4_PORT: u16 = 30304;
983        let remote_key = CombinedKey::generate_secp256k1();
984        let remote_enr = Enr::builder().tcp4(TCP4_PORT).build(&remote_key).unwrap();
985
986        let v6_socket: SocketAddr = "[::1]:30307".parse().unwrap();
987
988        let mut discv5 = discv5_noop();
989        discv5.rlpx_ip_mode = IpMode::Ip6;
990        let record = discv5.try_into_reachable(&remote_enr, v6_socket).unwrap();
991        assert_eq!(record.tcp_port, TCP4_PORT);
992    }
993
994    #[test]
995    fn reachable_tcp_port_missing_falls_back_to_udp_port() {
996        // No TCP port in the ENR at all: keep the long-standing fallback to
997        // the session's UDP port, for either session family.
998        let remote_key = CombinedKey::generate_secp256k1();
999        let remote_enr = Enr::builder().build(&remote_key).unwrap();
1000
1001        let discv5 = discv5_noop();
1002        let v4_socket: SocketAddr = "127.0.0.1:30305".parse().unwrap();
1003        assert_eq!(discv5.try_into_reachable(&remote_enr, v4_socket).unwrap().tcp_port, 30305);
1004        let v6_socket: SocketAddr = "[::1]:30307".parse().unwrap();
1005        assert_eq!(discv5.try_into_reachable(&remote_enr, v6_socket).unwrap().tcp_port, 30307);
1006    }
1007
1008    // Copied from sigp/discv5 with slight modification (U256 type)
1009    // <https://github.com/sigp/discv5/blob/master/src/kbucket/key.rs#L89-L101>
1010    #[expect(unreachable_pub)]
1011    #[expect(unused)]
1012    mod sigp {
1013        use alloy_primitives::U256;
1014        use enr::NodeId;
1015
1016        /// A `Key` is a cryptographic hash, identifying both the nodes participating in
1017        /// the Kademlia DHT, as well as records stored in the DHT.
1018        ///
1019        /// The set of all `Key`s defines the Kademlia keyspace.
1020        ///
1021        /// `Key`s have an XOR metric as defined in the Kademlia paper, i.e. the bitwise XOR of
1022        /// the hash digests, interpreted as an integer. See [`Key::distance`].
1023        ///
1024        /// A `Key` preserves the preimage of type `T` of the hash function. See [`Key::preimage`].
1025        #[derive(Clone, Debug)]
1026        pub struct Key<T> {
1027            preimage: T,
1028            hash: [u8; 32],
1029        }
1030
1031        impl<T> PartialEq for Key<T> {
1032            fn eq(&self, other: &Self) -> bool {
1033                self.hash == other.hash
1034            }
1035        }
1036
1037        impl<T> Eq for Key<T> {}
1038
1039        impl<TPeerId> AsRef<Self> for Key<TPeerId> {
1040            fn as_ref(&self) -> &Self {
1041                self
1042            }
1043        }
1044
1045        impl<T> Key<T> {
1046            /// Construct a new `Key` by providing the raw 32 byte hash.
1047            pub const fn new_raw(preimage: T, hash: [u8; 32]) -> Self {
1048                Self { preimage, hash }
1049            }
1050
1051            /// Borrows the preimage of the key.
1052            pub const fn preimage(&self) -> &T {
1053                &self.preimage
1054            }
1055
1056            /// Converts the key into its preimage.
1057            pub fn into_preimage(self) -> T {
1058                self.preimage
1059            }
1060
1061            /// Computes the distance of the keys according to the XOR metric.
1062            pub fn distance<U>(&self, other: &Key<U>) -> Distance {
1063                let a = U256::from_be_slice(self.hash.as_slice());
1064                let b = U256::from_be_slice(other.hash.as_slice());
1065                Distance(a ^ b)
1066            }
1067
1068            // Used in the FINDNODE query outside of the k-bucket implementation.
1069            /// Computes the integer log-2 distance between two keys, assuming a 256-bit
1070            /// key. The output returns None if the key's are identical. The range is 1-256.
1071            pub fn log2_distance<U>(&self, other: &Key<U>) -> Option<u64> {
1072                let xor_dist = self.distance(other);
1073                let log_dist = (256 - xor_dist.0.leading_zeros() as u64);
1074                (log_dist != 0).then_some(log_dist)
1075            }
1076        }
1077
1078        impl From<NodeId> for Key<NodeId> {
1079            fn from(node_id: NodeId) -> Self {
1080                Self { preimage: node_id, hash: node_id.raw() }
1081            }
1082        }
1083
1084        /// A distance between two `Key`s.
1085        #[derive(Copy, Clone, PartialEq, Eq, Default, PartialOrd, Ord, Debug)]
1086        pub struct Distance(pub(super) U256);
1087    }
1088
1089    #[test]
1090    fn select_lookup_target() {
1091        for bucket_index in 0..=MAX_KBUCKET_INDEX {
1092            let sk = CombinedKey::generate_secp256k1();
1093            let local_node_id = NodeId::from(sk.public());
1094            let target = get_lookup_target(bucket_index, local_node_id);
1095
1096            let local_node_id = sigp::Key::from(local_node_id);
1097            let target = sigp::Key::from(target);
1098
1099            assert_eq!(local_node_id.log2_distance(&target), Some(bucket_index as u64 + 1));
1100        }
1101    }
1102
1103    #[test]
1104    fn build_enr_from_config() {
1105        const TCP_PORT: u16 = 30303;
1106        let fork_id = MAINNET.latest_fork_id();
1107
1108        let config = Config::builder((Ipv4Addr::UNSPECIFIED, TCP_PORT).into())
1109            .fork(NetworkStackId::ETH, fork_id)
1110            .build();
1111
1112        let sk = SecretKey::new(&mut rng());
1113        let (enr, _, _, _) = build_local_enr(&sk, &config);
1114
1115        let decoded_fork_id = enr
1116            .get_decodable::<EnrForkIdEntry>(NetworkStackId::ETH)
1117            .unwrap()
1118            .map(Into::into)
1119            .unwrap();
1120
1121        assert_eq!(fork_id, decoded_fork_id);
1122        assert_eq!(TCP_PORT, enr.tcp4().unwrap()); // listen config is defaulting to ip mode ipv4
1123    }
1124
1125    #[test]
1126    fn get_fork_id_with_different_network_stack_ids() {
1127        let fork_id = MAINNET.latest_fork_id();
1128        let sk = SecretKey::new(&mut rng());
1129
1130        // Test 1: ENR with OPEL fork ID, Discv5 configured for OPEL
1131        let enr_with_opel = Enr::builder()
1132            .add_value_rlp(
1133                NetworkStackId::OPEL,
1134                alloy_rlp::encode(EnrForkIdEntry::from(fork_id)).into(),
1135            )
1136            .build(&sk)
1137            .unwrap();
1138
1139        let mut discv5 = discv5_noop();
1140        discv5.fork_key = Some(NetworkStackId::OPEL);
1141        assert_eq!(discv5.get_fork_id(&enr_with_opel).unwrap(), fork_id);
1142
1143        // Test 2: ENR with ETH fork ID, Discv5 configured for OPEL (fallback to ETH)
1144        let enr_with_eth = Enr::builder()
1145            .add_value_rlp(
1146                NetworkStackId::ETH,
1147                alloy_rlp::encode(EnrForkIdEntry::from(fork_id)).into(),
1148            )
1149            .build(&sk)
1150            .unwrap();
1151
1152        discv5.fork_key = Some(NetworkStackId::OPEL);
1153        assert_eq!(discv5.get_fork_id(&enr_with_eth).unwrap(), fork_id);
1154
1155        // Test 3: ENR with neither OPEL nor ETH fork ID (should fail)
1156        let enr_without_network_stack_id = Enr::empty(&sk).unwrap();
1157        discv5.fork_key = Some(NetworkStackId::OPEL);
1158        assert!(matches!(
1159            discv5.get_fork_id(&enr_without_network_stack_id),
1160            Err(Error::ForkMissing(NetworkStackId::OPEL))
1161        ));
1162
1163        // Test 4: discv5 without network stack id configured (should fail)
1164        let discv5 = discv5_noop();
1165        assert!(matches!(
1166            discv5.get_fork_id(&enr_without_network_stack_id),
1167            Err(Error::NetworkStackIdNotConfigured)
1168        ));
1169    }
1170}