Skip to main content

reth_discv4/
lib.rs

1//! Discovery v4 implementation: <https://github.com/ethereum/devp2p/blob/master/discv4.md>
2//!
3//! Discv4 employs a kademlia-like routing table to store and manage discovered peers and topics.
4//! The protocol allows for external IP discovery in NAT environments through regular PING/PONG's
5//! with discovered nodes. Nodes return the external IP address that they have received and a simple
6//! majority is chosen as our external IP address. If an external IP address is updated, this is
7//! produced as an event to notify the swarm (if one is used for this behaviour).
8//!
9//! This implementation consists of a [`Discv4`] and [`Discv4Service`] pair. The service manages the
10//! state and drives the UDP socket. The (optional) [`Discv4`] serves as the frontend to interact
11//! with the service via a channel. Whenever the underlying table changes service produces a
12//! [`DiscoveryUpdate`] that listeners will receive.
13//!
14//! ## Feature Flags
15//!
16//! - `serde` (default): Enable serde support
17//! - `test-utils`: Export utilities for testing
18
19#![doc(
20    html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
21    html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
22    issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
23)]
24#![cfg_attr(not(test), warn(unused_crate_dependencies))]
25#![cfg_attr(docsrs, feature(doc_cfg))]
26
27use crate::{
28    error::{DecodePacketError, Discv4Error},
29    proto::{FindNode, Message, Neighbours, NodeEndpoint, Packet, Ping, Pong},
30};
31use alloy_primitives::{bytes::Bytes, hex, B256};
32use discv5::{
33    kbucket,
34    kbucket::{
35        BucketInsertResult, Distance, Entry as BucketEntry, InsertResult, KBucketsTable,
36        NodeStatus, MAX_NODES_PER_BUCKET,
37    },
38    ConnectionDirection, ConnectionState,
39};
40use enr::Enr;
41use itertools::Itertools;
42use parking_lot::Mutex;
43use proto::{EnrRequest, EnrResponse};
44use reth_ethereum_forks::ForkId;
45use reth_network_peers::{pk2id, PeerId};
46use secp256k1::SecretKey;
47use std::{
48    cell::RefCell,
49    collections::{btree_map, hash_map::Entry, BTreeMap, HashMap, VecDeque},
50    fmt, io,
51    net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4},
52    pin::Pin,
53    rc::Rc,
54    sync::Arc,
55    task::{ready, Context, Poll},
56    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
57};
58use tokio::{
59    net::UdpSocket,
60    sync::{mpsc, mpsc::error::TrySendError, oneshot, oneshot::Sender as OneshotSender},
61    task::{JoinHandle, JoinSet},
62    time::Interval,
63};
64use tokio_stream::{wrappers::ReceiverStream, Stream, StreamExt};
65use tracing::{debug, trace};
66
67pub mod error;
68pub mod proto;
69
70mod config;
71pub use config::{Discv4Config, Discv4ConfigBuilder};
72
73mod node;
74use node::{kad_key, NodeKey};
75
76mod table;
77
78// reexport NodeRecord primitive
79pub use reth_network_peers::NodeRecord;
80
81#[cfg(any(test, feature = "test-utils"))]
82pub mod test_utils;
83
84use crate::table::PongTable;
85use reth_net_nat::ResolveNatInterval;
86/// reexport to get public ip.
87pub use reth_net_nat::{external_ip, NatResolver};
88
89/// The default address for discv4 via UDP
90///
91/// Note: the default TCP address is the same.
92pub const DEFAULT_DISCOVERY_ADDR: IpAddr = IpAddr::V4(Ipv4Addr::UNSPECIFIED);
93
94/// The default port for discv4 via UDP
95///
96/// Note: the default TCP port is the same.
97pub const DEFAULT_DISCOVERY_PORT: u16 = 30303;
98
99/// The default address for discv4 via UDP: "0.0.0.0:30303"
100///
101/// Note: The default TCP address is the same.
102pub const DEFAULT_DISCOVERY_ADDRESS: SocketAddr =
103    SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, DEFAULT_DISCOVERY_PORT));
104
105/// The maximum size of any packet is 1280 bytes.
106const MAX_PACKET_SIZE: usize = 1280;
107
108/// Length of the UDP datagram packet-header: Hash(32b) + Signature(65b) + Packet Type(1b)
109const MIN_PACKET_SIZE: usize = 32 + 65 + 1;
110
111/// Concurrency factor for `FindNode` requests to pick `ALPHA` closest nodes, <https://github.com/ethereum/devp2p/blob/master/discv4.md#recursive-lookup>
112const ALPHA: usize = 3;
113
114/// Maximum number of nodes to ping at concurrently.
115///
116/// This corresponds to 2 full `Neighbours` responses with 16 _new_ nodes. This will apply some
117/// backpressure in recursive lookups.
118const MAX_NODES_PING: usize = 2 * MAX_NODES_PER_BUCKET;
119
120// Number of `MAX_NODES_PING` slots reserved for lookups and pings to proven endpoints, so unproven
121// nodes that never answer our ping can't block lookups or bond renewals.
122const RESERVED_PINGS: usize = MAX_NODES_PER_BUCKET / 2;
123
124/// Maximum number of pings to keep queued.
125///
126/// If we are currently sending too many pings, any new pings will be queued. To prevent unbounded
127/// growth of the queue, the queue has a maximum capacity, after which any additional pings will be
128/// discarded.
129///
130/// This corresponds to 2 full `Neighbours` responses with 16 new nodes.
131const MAX_QUEUED_PINGS: usize = 2 * MAX_NODES_PER_BUCKET;
132
133/// The size of the datagram is limited [`MAX_PACKET_SIZE`], 16 nodes, as the discv4 specifies don't
134/// fit in one datagram. The safe number of nodes that always fit in a datagram is 12, with worst
135/// case all of them being IPv6 nodes. This is calculated by `(MAX_PACKET_SIZE - (header + expire +
136/// rlp overhead) / size(rlp(Node_IPv6))`
137/// Even in the best case where all nodes are IPv4, only 14 nodes fit into one packet.
138const SAFE_MAX_DATAGRAM_NEIGHBOUR_RECORDS: usize = (MAX_PACKET_SIZE - 109) / 91;
139
140/// The timeout used to identify expired nodes, 24h
141///
142/// Mirrors geth's `bondExpiration` of 24h
143const ENDPOINT_PROOF_EXPIRATION: Duration = Duration::from_secs(24 * 60 * 60);
144
145/// Duration used to expire nodes from the routing table 1hr
146const EXPIRE_DURATION: Duration = Duration::from_secs(60 * 60);
147
148// Restricts how many udp messages can be processed in a single [Discv4Service::poll] call.
149//
150// This will act as a manual yield point when draining the socket messages where the most CPU
151// expensive part is handling outgoing messages: encoding and hashing the packet
152const UDP_MESSAGE_POLL_LOOP_BUDGET: i32 = 4;
153
154type EgressSender = mpsc::Sender<(Bytes, SocketAddr)>;
155type EgressReceiver = mpsc::Receiver<(Bytes, SocketAddr)>;
156
157pub(crate) type IngressSender = mpsc::Sender<IngressEvent>;
158pub(crate) type IngressReceiver = mpsc::Receiver<IngressEvent>;
159
160type NodeRecordSender = OneshotSender<Vec<NodeRecord>>;
161
162/// The Discv4 frontend.
163///
164/// This is a cloneable type that communicates with the [`Discv4Service`] by sending commands over a
165/// shared channel.
166///
167/// See also [`Discv4::spawn`]
168#[derive(Debug, Clone)]
169pub struct Discv4 {
170    /// The address of the udp socket
171    local_addr: SocketAddr,
172    /// channel to send commands over to the service
173    to_service: mpsc::UnboundedSender<Discv4Command>,
174    /// Tracks the local node record.
175    ///
176    /// This includes the currently tracked external IP address of the node.
177    node_record: Arc<Mutex<NodeRecord>>,
178}
179
180impl Discv4 {
181    /// Same as [`Self::bind`] but also spawns the service onto a new task.
182    ///
183    /// See also: [`Discv4Service::spawn()`]
184    pub async fn spawn(
185        local_address: SocketAddr,
186        local_enr: NodeRecord,
187        secret_key: SecretKey,
188        config: Discv4Config,
189    ) -> io::Result<Self> {
190        let (discv4, service) = Self::bind(local_address, local_enr, secret_key, config).await?;
191
192        service.spawn();
193
194        Ok(discv4)
195    }
196
197    /// Returns a new instance with the given channel directly
198    ///
199    /// NOTE: this is only intended for test setups.
200    #[cfg(feature = "test-utils")]
201    pub fn noop() -> Self {
202        let (to_service, _rx) = mpsc::unbounded_channel();
203        let local_addr =
204            (IpAddr::from(std::net::Ipv4Addr::UNSPECIFIED), DEFAULT_DISCOVERY_PORT).into();
205        Self {
206            local_addr,
207            to_service,
208            node_record: Arc::new(Mutex::new(NodeRecord::new(
209                "127.0.0.1:3030".parse().unwrap(),
210                PeerId::random(),
211            ))),
212        }
213    }
214
215    /// Binds a new `UdpSocket` and creates the service
216    ///
217    /// ```
218    /// use reth_discv4::{Discv4, Discv4Config};
219    /// use reth_network_peers::{pk2id, NodeRecord, PeerId};
220    /// use std::{net::SocketAddr, str::FromStr};
221    /// # async fn t() -> std:: io::Result<()> {
222    ///
223    /// // generate a (random) keypair
224    /// let (secret_key, pk) = secp256k1::generate_keypair(&mut rand::rng());
225    /// let id = pk2id(&pk);
226    ///
227    /// let socket = SocketAddr::from_str("0.0.0.0:0").unwrap();
228    /// let local_enr =
229    ///     NodeRecord { address: socket.ip(), tcp_port: socket.port(), udp_port: socket.port(), id };
230    /// let config = Discv4Config::default();
231    ///
232    /// let (discv4, mut service) = Discv4::bind(socket, local_enr, secret_key, config).await.unwrap();
233    ///
234    /// // get an update strea
235    /// let updates = service.update_stream();
236    ///
237    /// let _handle = service.spawn();
238    ///
239    /// // lookup the local node in the DHT
240    /// let _discovered = discv4.lookup_self().await.unwrap();
241    ///
242    /// # Ok(())
243    /// # }
244    /// ```
245    pub async fn bind(
246        local_address: SocketAddr,
247        local_node_record: NodeRecord,
248        secret_key: SecretKey,
249        config: Discv4Config,
250    ) -> io::Result<(Self, Discv4Service)> {
251        let socket = Arc::new(UdpSocket::bind(local_address).await?);
252        trace!(target: "discv4", local_addr=?socket.local_addr(), "opened UDP socket");
253        let (tx, rx) = mpsc::channel(config.udp_ingress_message_buffer);
254
255        Self::bind_with_socket(socket, None, Some(tx), rx, local_node_record, secret_key, config)
256    }
257
258    /// Creates a new `Discv4` instance using a pre-bound shared socket. No receive loop is
259    /// spawned; instead returns an [`IngressHandler`] that should be used to forward raw packets
260    /// received by the socket owner (e.g. discv5 unrecognized frames).
261    ///
262    /// An optional secondary socket of the opposite IP family (e.g. discv5's dual-stack sibling
263    /// socket) makes the service answer peers of that family too: outgoing packets are routed to
264    /// the socket matching the destination family, while ingress for both arrives via the
265    /// returned [`IngressHandler`].
266    pub fn bind_shared(
267        socket: Arc<UdpSocket>,
268        secondary_socket: Option<Arc<UdpSocket>>,
269        local_node_record: NodeRecord,
270        secret_key: SecretKey,
271        config: Discv4Config,
272    ) -> io::Result<(Self, Discv4Service, IngressHandler)> {
273        let (tx, rx) = mpsc::channel(config.udp_ingress_message_buffer);
274        let local_id = local_node_record.id;
275        let (discv4, service) = Self::bind_with_socket(
276            socket,
277            secondary_socket,
278            None,
279            rx,
280            local_node_record,
281            secret_key,
282            config,
283        )?;
284
285        let handler = IngressHandler::new(tx, local_id);
286
287        Ok((discv4, service, handler))
288    }
289
290    fn bind_with_socket(
291        socket: Arc<UdpSocket>,
292        secondary_socket: Option<Arc<UdpSocket>>,
293        ingress_tx: Option<IngressSender>,
294        ingress_rx: IngressReceiver,
295        mut local_node_record: NodeRecord,
296        secret_key: SecretKey,
297        config: Discv4Config,
298    ) -> io::Result<(Self, Discv4Service)> {
299        let local_addr = socket.local_addr()?;
300        local_node_record.udp_port = local_addr.port();
301
302        let mut service = Discv4Service::new(
303            socket,
304            secondary_socket,
305            ingress_tx,
306            ingress_rx,
307            local_addr,
308            local_node_record,
309            secret_key,
310            config,
311        );
312
313        // resolve the external address immediately
314        service.resolve_external_ip();
315
316        let discv4 = service.handle();
317        Ok((discv4, service))
318    }
319
320    /// Returns the address of the UDP socket.
321    pub const fn local_addr(&self) -> SocketAddr {
322        self.local_addr
323    }
324
325    /// Returns the [`NodeRecord`] of the local node.
326    ///
327    /// This includes the currently tracked external IP address of the node.
328    pub fn node_record(&self) -> NodeRecord {
329        *self.node_record.lock()
330    }
331
332    /// Returns the currently tracked external IP of the node.
333    pub fn external_ip(&self) -> IpAddr {
334        self.node_record.lock().address
335    }
336
337    /// Sets the [Interval] used for periodically looking up targets over the network
338    pub fn set_lookup_interval(&self, duration: Duration) {
339        self.send_to_service(Discv4Command::SetLookupInterval(duration))
340    }
341
342    /// Starts a `FindNode` recursive lookup that locates the closest nodes to the given node id. See also: <https://github.com/ethereum/devp2p/blob/master/discv4.md#recursive-lookup>
343    ///
344    /// The lookup initiator starts by picking α closest nodes to the target it knows of. The
345    /// initiator then sends concurrent `FindNode` packets to those nodes. α is a system-wide
346    /// concurrency parameter, such as 3. In the recursive step, the initiator resends `FindNode` to
347    /// nodes it has learned about from previous queries. Of the k nodes the initiator has heard of
348    /// closest to the target, it picks α that it has not yet queried and resends `FindNode` to
349    /// them. Nodes that fail to respond quickly are removed from consideration until and unless
350    /// they do respond.
351    //
352    // If a round of FindNode queries fails to return a node any closer than the closest already
353    // seen, the initiator resends the find node to all of the k closest nodes it has not already
354    // queried. The lookup terminates when the initiator has queried and gotten responses from the k
355    // closest nodes it has seen.
356    pub async fn lookup_self(&self) -> Result<Vec<NodeRecord>, Discv4Error> {
357        self.lookup_node(None).await
358    }
359
360    /// Looks up the given node id.
361    ///
362    /// Returning the closest nodes to the given node id.
363    pub async fn lookup(&self, node_id: PeerId) -> Result<Vec<NodeRecord>, Discv4Error> {
364        self.lookup_node(Some(node_id)).await
365    }
366
367    /// Performs a random lookup for node records.
368    pub async fn lookup_random(&self) -> Result<Vec<NodeRecord>, Discv4Error> {
369        let target = PeerId::random();
370        self.lookup_node(Some(target)).await
371    }
372
373    /// Sends a message to the service to lookup the closest nodes
374    pub fn send_lookup(&self, node_id: PeerId) {
375        let cmd = Discv4Command::Lookup { node_id: Some(node_id), tx: None };
376        self.send_to_service(cmd);
377    }
378
379    async fn lookup_node(&self, node_id: Option<PeerId>) -> Result<Vec<NodeRecord>, Discv4Error> {
380        let (tx, rx) = oneshot::channel();
381        let cmd = Discv4Command::Lookup { node_id, tx: Some(tx) };
382        self.to_service.send(cmd)?;
383        Ok(rx.await?)
384    }
385
386    /// Triggers a new self lookup without expecting a response
387    pub fn send_lookup_self(&self) {
388        let cmd = Discv4Command::Lookup { node_id: None, tx: None };
389        self.send_to_service(cmd);
390    }
391
392    /// Removes the peer from the table, if it exists.
393    pub fn remove_peer(&self, node_id: PeerId) {
394        let cmd = Discv4Command::Remove(node_id);
395        self.send_to_service(cmd);
396    }
397
398    /// Adds the node to the table, if it is not already present.
399    pub fn add_node(&self, node_record: NodeRecord) {
400        let cmd = Discv4Command::Add(node_record);
401        self.send_to_service(cmd);
402    }
403
404    /// Adds the node as a bootnode.
405    ///
406    /// This registers the node in the configured bootstrap set and inserts it into the routing
407    /// table, pinging it to establish the endpoint proof, same as the nodes provided at startup.
408    pub fn add_boot_node(&self, node_record: NodeRecord) {
409        let cmd = Discv4Command::AddBootNode(node_record);
410        self.send_to_service(cmd);
411    }
412
413    /// Adds the peer and id to the ban list.
414    ///
415    /// This will prevent any future inclusion in the table
416    pub fn ban(&self, node_id: PeerId, ip: IpAddr) {
417        let cmd = Discv4Command::Ban(node_id, ip, None);
418        self.send_to_service(cmd);
419    }
420
421    /// Adds the ip to the ban list.
422    ///
423    /// This will prevent any future inclusion in the table
424    pub fn ban_ip(&self, ip: IpAddr) {
425        let cmd = Discv4Command::BanIp(ip, None);
426        self.send_to_service(cmd);
427    }
428
429    /// Adds the peer and ip to the ban list until the given timestamp.
430    ///
431    /// An existing ban is only extended. Expired bans are evicted periodically, so they may outlast
432    /// `until` by up to an hour.
433    pub fn ban_until(&self, node_id: PeerId, ip: IpAddr, until: Instant) {
434        let cmd = Discv4Command::Ban(node_id, ip, Some(until));
435        self.send_to_service(cmd);
436    }
437
438    /// Adds the ip to the ban list until the given timestamp.
439    ///
440    /// An existing ban is only extended. Expired bans are evicted periodically, so they may outlast
441    /// `until` by up to an hour.
442    pub fn ban_ip_until(&self, ip: IpAddr, until: Instant) {
443        let cmd = Discv4Command::BanIp(ip, Some(until));
444        self.send_to_service(cmd);
445    }
446
447    /// Adds the peer to the ban list.
448    ///
449    /// This will prevent any future inclusion in the table
450    pub fn ban_node(&self, node_id: PeerId) {
451        let cmd = Discv4Command::BanPeer(node_id);
452        self.send_to_service(cmd);
453    }
454
455    /// Sets the tcp port
456    ///
457    /// This will update our [`NodeRecord`]'s tcp port.
458    pub fn set_tcp_port(&self, port: u16) {
459        let cmd = Discv4Command::SetTcpPort(port);
460        self.send_to_service(cmd);
461    }
462
463    /// Sets the pair in the EIP-868 [`Enr`] of the node.
464    ///
465    /// If the key already exists, this will update it.
466    ///
467    /// CAUTION: The value **must** be rlp encoded
468    pub fn set_eip868_rlp_pair(&self, key: Vec<u8>, rlp: Bytes) {
469        let cmd = Discv4Command::SetEIP868RLPPair { key, rlp };
470        self.send_to_service(cmd);
471    }
472
473    /// Sets the pair in the EIP-868 [`Enr`] of the node.
474    ///
475    /// If the key already exists, this will update it.
476    pub fn set_eip868_rlp(&self, key: Vec<u8>, value: impl alloy_rlp::Encodable) {
477        self.set_eip868_rlp_pair(key, Bytes::from(alloy_rlp::encode(&value)))
478    }
479
480    #[inline]
481    fn send_to_service(&self, cmd: Discv4Command) {
482        let _ = self.to_service.send(cmd).map_err(|err| {
483            debug!(
484                target: "discv4",
485                %err,
486                "channel capacity reached, dropping command",
487            )
488        });
489    }
490
491    /// Returns the receiver half of new listener channel that streams [`DiscoveryUpdate`]s.
492    pub async fn update_stream(&self) -> Result<ReceiverStream<DiscoveryUpdate>, Discv4Error> {
493        let (tx, rx) = oneshot::channel();
494        let cmd = Discv4Command::Updates(tx);
495        self.to_service.send(cmd)?;
496        Ok(rx.await?)
497    }
498
499    /// Terminates the spawned [`Discv4Service`].
500    pub fn terminate(&self) {
501        self.send_to_service(Discv4Command::Terminated);
502    }
503}
504
505/// Manages discv4 peer discovery over UDP.
506///
507/// This is a [Stream] to handles incoming and outgoing discv4 messages and emits updates via:
508/// [`Discv4Service::update_stream`].
509///
510/// This type maintains the discv Kademlia routing table and is responsible for performing lookups.
511///
512/// ## Lookups
513///
514/// See also [Recursive Lookups](https://github.com/ethereum/devp2p/blob/master/discv4.md#recursive-lookup).
515/// Lookups are either triggered periodically or performaned on demand: [`Discv4::lookup`]
516/// Newly discovered nodes are emitted as [`DiscoveryUpdate::Added`] event to all subscribers:
517/// [`Discv4Service::update_stream`].
518#[must_use = "Stream does nothing unless polled"]
519pub struct Discv4Service {
520    /// Local address of the UDP socket.
521    local_address: SocketAddr,
522    /// The local ENR for EIP-868 <https://eips.ethereum.org/EIPS/eip-868>
523    local_eip_868_enr: Enr<SecretKey>,
524    /// Local ENR of the server.
525    local_node_record: NodeRecord,
526    /// Keeps track of the node record of the local node.
527    shared_node_record: Arc<Mutex<NodeRecord>>,
528    /// The secret key used to sign payloads
529    secret_key: SecretKey,
530    /// The UDP socket for sending and receiving messages.
531    _socket: Arc<UdpSocket>,
532    /// The spawned UDP tasks.
533    ///
534    /// Note: If dropped, the spawned send+receive tasks are aborted.
535    _tasks: JoinSet<()>,
536    /// The routing table.
537    kbuckets: KBucketsTable<NodeKey, NodeEntry>,
538    /// Receiver for incoming messages
539    ///
540    /// Receives incoming messages from the UDP task.
541    ingress: IngressReceiver,
542    /// Sender for sending outgoing messages
543    ///
544    /// Sends outgoing messages to the UDP task.
545    egress: EgressSender,
546    /// Buffered pending pings to apply backpressure.
547    ///
548    /// Lookups behave like bursts of requests: Endpoint proof followed by `FindNode` request. [Recursive lookups](https://github.com/ethereum/devp2p/blob/master/discv4.md#recursive-lookup) can trigger multiple followup Pings+FindNode requests.
549    /// A cap on concurrent `Ping` prevents escalation where: A large number of new nodes
550    /// discovered via `FindNode` in a recursive lookup triggers a large number of `Ping`s, and
551    /// followup `FindNode` requests.... Buffering them effectively prevents high `Ping` peaks.
552    queued_pings: VecDeque<(NodeRecord, PingReason)>,
553    /// Currently active pings to specific nodes.
554    pending_pings: HashMap<PeerId, PingRequest>,
555    /// Currently active endpoint proof verification lookups to specific nodes.
556    ///
557    /// Entries here means we've proven the peer's endpoint but haven't completed our end of the
558    /// endpoint proof
559    pending_lookup: HashMap<PeerId, (Instant, LookupContext)>,
560    /// Currently active `FindNode` requests
561    pending_find_nodes: HashMap<PeerId, FindNodeRequest>,
562    /// Currently active ENR requests
563    pending_enr_requests: HashMap<PeerId, EnrRequestState>,
564    /// Copy of the sender half of the commands channel for [Discv4]
565    to_service: mpsc::UnboundedSender<Discv4Command>,
566    /// Receiver half of the commands channel for [Discv4]
567    commands_rx: mpsc::UnboundedReceiver<Discv4Command>,
568    /// All subscribers for table updates
569    update_listeners: Vec<mpsc::Sender<DiscoveryUpdate>>,
570    /// The interval when to trigger random lookups
571    lookup_interval: Interval,
572    /// Used to rotate targets to lookup
573    lookup_rotator: LookupTargetRotator,
574    /// Whether we still need to reset the lookup interval on the first bootnode pong.
575    pending_lookup_reset: bool,
576    /// Interval when to recheck active requests
577    evict_expired_requests_interval: Interval,
578    /// Interval when to resend pings.
579    ping_interval: Interval,
580    /// The interval at which to attempt resolving external IP again.
581    resolve_external_ip_interval: Option<ResolveNatInterval>,
582    /// How this services is configured
583    config: Discv4Config,
584    /// Buffered events populated during poll.
585    queued_events: VecDeque<Discv4Event>,
586    /// Keeps track of nodes from which we have received a `Pong` message.
587    received_pongs: PongTable,
588    /// Interval used to expire additionally tracked nodes
589    expire_interval: Interval,
590    /// Cached signed `FindNode` packet to avoid redundant ECDSA signing during lookups.
591    cached_find_node: Option<CachedFindNode>,
592}
593
594impl Discv4Service {
595    /// Create a new instance for a bound [`UdpSocket`].
596    ///
597    /// If `ingress_tx` is `Some`, the receive loop is spawned to read from the socket. If `None`,
598    /// the caller feeds packets into `ingress_rx` externally (shared socket mode).
599    #[expect(clippy::too_many_arguments)]
600    pub(crate) fn new(
601        socket: Arc<UdpSocket>,
602        secondary_socket: Option<Arc<UdpSocket>>,
603        ingress_tx: Option<IngressSender>,
604        ingress_rx: IngressReceiver,
605        local_address: SocketAddr,
606        local_node_record: NodeRecord,
607        secret_key: SecretKey,
608        mut config: Discv4Config,
609    ) -> Self {
610        // normalize once: only an opposite-family secondary socket can serve the advertisement
611        config.secondary_advertised_ip = config.secondary_advertised_ip.filter(|ip| {
612            secondary_socket.is_some() &&
613                !ip.is_unspecified() &&
614                ip.is_ipv4() != local_node_record.address.is_ipv4()
615        });
616
617        let (egress_tx, egress_rx) = mpsc::channel(config.udp_egress_message_buffer);
618        let mut tasks = JoinSet::<()>::new();
619
620        if let Some(ingress_tx) = ingress_tx {
621            let udp = Arc::clone(&socket);
622            tasks.spawn(receive_loop(udp, ingress_tx, local_node_record.id));
623        }
624
625        let udp = Arc::clone(&socket);
626        tasks.spawn(send_loop(udp, secondary_socket, local_address.is_ipv4(), egress_rx));
627
628        let kbuckets = KBucketsTable::new(
629            NodeKey::from(&local_node_record).into(),
630            Duration::from_secs(60),
631            MAX_NODES_PER_BUCKET,
632            None,
633            None,
634        );
635
636        let self_lookup_interval = tokio::time::interval(config.lookup_interval);
637
638        // Wait `ping_interval` and then start pinging every `ping_interval` because we want to wait
639        // for
640        let ping_interval = tokio::time::interval_at(
641            tokio::time::Instant::now() + config.ping_interval,
642            config.ping_interval,
643        );
644
645        let evict_expired_requests_interval = tokio::time::interval_at(
646            tokio::time::Instant::now() + config.request_timeout,
647            config.request_timeout,
648        );
649
650        let lookup_rotator = if config.enable_dht_random_walk {
651            LookupTargetRotator::default()
652        } else {
653            LookupTargetRotator::local_only()
654        };
655
656        // for EIP-868 construct an ENR
657        let local_eip_868_enr = {
658            let mut builder = Enr::builder();
659            for ip in
660                std::iter::once(local_node_record.address).chain(config.secondary_advertised_ip)
661            {
662                // Keep port keys for NAT resolution, but omit unspecified IP addresses.
663                if !ip.is_unspecified() {
664                    builder.ip(ip);
665                }
666                if ip.is_ipv4() {
667                    builder.udp4(local_node_record.udp_port);
668                    builder.tcp4(local_node_record.tcp_port);
669                } else {
670                    builder.udp6(local_node_record.udp_port);
671                    builder.tcp6(local_node_record.tcp_port);
672                }
673            }
674
675            for (key, val) in &config.additional_eip868_rlp_pairs {
676                builder.add_value_rlp(key, val.clone());
677            }
678            builder.build(&secret_key).expect("v4 is set")
679        };
680
681        let (to_service, commands_rx) = mpsc::unbounded_channel();
682
683        let shared_node_record = Arc::new(Mutex::new(local_node_record));
684
685        Self {
686            local_address,
687            local_eip_868_enr,
688            local_node_record,
689            shared_node_record,
690            _socket: socket,
691            kbuckets,
692            secret_key,
693            _tasks: tasks,
694            ingress: ingress_rx,
695            egress: egress_tx,
696            queued_pings: VecDeque::with_capacity(MAX_QUEUED_PINGS),
697            pending_pings: Default::default(),
698            pending_lookup: Default::default(),
699            pending_find_nodes: Default::default(),
700            pending_enr_requests: Default::default(),
701            commands_rx,
702            to_service,
703            update_listeners: Vec::with_capacity(1),
704            lookup_interval: self_lookup_interval,
705            ping_interval,
706            evict_expired_requests_interval,
707            lookup_rotator,
708            pending_lookup_reset: config.enable_lookup,
709            resolve_external_ip_interval: config.resolve_external_ip_interval(),
710            config,
711            queued_events: Default::default(),
712            received_pongs: Default::default(),
713            expire_interval: tokio::time::interval(EXPIRE_DURATION),
714            cached_find_node: None,
715        }
716    }
717
718    /// Returns the frontend handle that can communicate with the service via commands.
719    pub fn handle(&self) -> Discv4 {
720        Discv4 {
721            local_addr: self.local_address,
722            to_service: self.to_service.clone(),
723            node_record: self.shared_node_record.clone(),
724        }
725    }
726
727    /// Returns the current enr sequence of the local record.
728    fn enr_seq(&self) -> Option<u64> {
729        self.config.enable_eip868.then(|| self.local_eip_868_enr.seq())
730    }
731
732    /// Sets the [Interval] used for periodically looking up targets over the network
733    pub fn set_lookup_interval(&mut self, duration: Duration) {
734        self.lookup_interval = tokio::time::interval(duration);
735    }
736
737    /// Sets the external Ip to the configured external IP if [`NatResolver::ExternalIp`] or
738    /// [`NatResolver::ExternalAddr`]. In the case of [`NatResolver::ExternalAddr`], it will return
739    /// the first IP address found for the domain associated with the discv4 UDP port.
740    fn resolve_external_ip(&mut self) {
741        if let Some(r) = &self.resolve_external_ip_interval &&
742            let Some(external_ip) =
743                r.resolver().clone().as_external_ip(self.local_node_record.udp_port)
744        {
745            self.set_external_ip_addr(external_ip);
746        }
747    }
748
749    /// Sets the given ip address as the node's external IP in the node record announced in
750    /// discovery
751    pub fn set_external_ip_addr(&mut self, external_ip: IpAddr) {
752        // an opposite-family resolution would overwrite the secondary ENR key and flip the
753        // record's family, so a secondary advertisement pins the record's family
754        if self.config.secondary_advertised_ip.is_some() &&
755            external_ip.is_ipv4() != self.local_node_record.address.is_ipv4()
756        {
757            debug!(target: "discv4", ?external_ip, "Ignoring opposite-family external ip");
758            return
759        }
760        if self.local_node_record.address != external_ip {
761            debug!(target: "discv4", ?external_ip, "Updating external ip");
762            self.local_node_record.address = external_ip;
763            let _ = self.local_eip_868_enr.set_ip(external_ip, &self.secret_key);
764            let mut lock = self.shared_node_record.lock();
765            *lock = self.local_node_record;
766            debug!(target: "discv4", enr=?self.local_eip_868_enr, "Updated local ENR");
767        }
768    }
769
770    /// Returns the [`PeerId`] that identifies this node
771    pub const fn local_peer_id(&self) -> &PeerId {
772        &self.local_node_record.id
773    }
774
775    /// Returns the address of the UDP socket
776    pub const fn local_addr(&self) -> SocketAddr {
777        self.local_address
778    }
779
780    /// Returns the ENR of this service.
781    ///
782    /// Note: this will include the external address if resolved.
783    pub const fn local_enr(&self) -> NodeRecord {
784        self.local_node_record
785    }
786
787    /// Returns mutable reference to ENR for testing.
788    #[cfg(test)]
789    pub const fn local_enr_mut(&mut self) -> &mut NodeRecord {
790        &mut self.local_node_record
791    }
792
793    /// Returns true if the given `PeerId` is currently in the bucket
794    pub fn contains_node(&self, id: PeerId) -> bool {
795        let key = kad_key(id);
796        self.kbuckets.get_index(&key).is_some()
797    }
798
799    /// Bootstraps the local node to join the DHT.
800    ///
801    /// Bootstrapping is a multi-step operation that starts with a lookup of the local node's
802    /// own ID in the DHT. This introduces the local node to the other nodes
803    /// in the DHT and populates its routing table with the closest proven neighbours.
804    ///
805    /// This inserts the configured bootnodes into the routing table and pings them. Once the
806    /// endpoint proof succeeds (pong received), a [`DiscoveryUpdate::Added`] event is emitted,
807    /// same as with [`Self::add_node`].
808    ///
809    /// **Note:** This is a noop if there are no bootnodes.
810    pub fn bootstrap(&mut self) {
811        for record in self.config.bootstrap_nodes.clone() {
812            debug!(target: "discv4", ?record, "pinging boot node");
813            let key = kad_key(record.id);
814            let entry = NodeEntry::new(record);
815
816            // insert the boot node in the table
817            match self.kbuckets.insert_or_update(
818                &key,
819                entry,
820                NodeStatus {
821                    state: ConnectionState::Disconnected,
822                    direction: ConnectionDirection::Outgoing,
823                },
824            ) {
825                InsertResult::Failed(_) => {}
826                _ => {
827                    self.try_ping(record, PingReason::InitialInsert);
828                }
829            }
830        }
831    }
832
833    /// Adds the node to the bootstrap set and to the routing table.
834    ///
835    /// Behaves like [`Self::add_node`] but also registers the node in the configured bootstrap
836    /// set so it is used for subsequent bootstrap attempts.
837    pub fn add_boot_node(&mut self, record: NodeRecord) -> bool {
838        self.config.bootstrap_nodes.insert(record);
839        self.add_node(record)
840    }
841
842    /// Spawns this services onto a new task
843    ///
844    /// Note: requires a running tokio runtime
845    pub fn spawn(mut self) -> JoinHandle<()> {
846        tokio::task::spawn(async move {
847            self.bootstrap();
848
849            while let Some(event) = self.next().await {
850                trace!(target: "discv4", ?event, "processed");
851            }
852            trace!(target: "discv4", "service terminated");
853        })
854    }
855
856    /// Creates a new bounded channel for [`DiscoveryUpdate`]s.
857    pub fn update_stream(&mut self) -> ReceiverStream<DiscoveryUpdate> {
858        let (tx, rx) = mpsc::channel(512);
859        self.update_listeners.push(tx);
860        ReceiverStream::new(rx)
861    }
862
863    /// Looks up the local node in the DHT.
864    pub fn lookup_self(&mut self) {
865        self.lookup(self.local_node_record.id)
866    }
867
868    /// Looks up the given node in the DHT
869    ///
870    /// A `FindNode` packet requests information about nodes close to target. The target is a
871    /// 64-byte secp256k1 public key. When `FindNode` is received, the recipient should reply
872    /// with Neighbors packets containing the closest 16 nodes to target found in its local
873    /// table.
874    //
875    // To guard against traffic amplification attacks, Neighbors replies should only be sent if the
876    // sender of FindNode has been verified by the endpoint proof procedure.
877    pub fn lookup(&mut self, target: PeerId) {
878        self.lookup_with(target, None)
879    }
880
881    /// Starts the recursive lookup process for the given target, <https://github.com/ethereum/devp2p/blob/master/discv4.md#recursive-lookup>.
882    ///
883    /// At first the `ALPHA` (==3, defined concurrency factor) nodes that are closest to the target
884    /// in the underlying DHT are selected to seed the lookup via `FindNode` requests. In the
885    /// recursive step, the initiator resends `FindNode` to nodes it has learned about from previous
886    /// queries.
887    ///
888    /// This takes an optional Sender through which all successfully discovered nodes are sent once
889    /// the request has finished.
890    fn lookup_with(&mut self, target: PeerId, tx: Option<NodeRecordSender>) {
891        trace!(target: "discv4", ?target, "Starting lookup");
892        let target_key = kad_key(target);
893
894        // Start a lookup context with the 16 (MAX_NODES_PER_BUCKET) closest nodes to which we have
895        // a valid endpoint proof
896        let ctx = LookupContext::new(
897            target_key.clone(),
898            self.kbuckets
899                .closest_values(&target_key)
900                .filter(|node| {
901                    node.value.has_endpoint_proof &&
902                        !self.pending_find_nodes.contains_key(&node.key.preimage().0)
903                })
904                .take(MAX_NODES_PER_BUCKET)
905                .map(|n| (target_key.distance(&n.key), n.value.record)),
906            tx,
907        );
908
909        // From those 16, pick the 3 closest to start the concurrent lookup.
910        let closest = ctx.closest(ALPHA);
911
912        if closest.is_empty() && self.pending_find_nodes.is_empty() {
913            // no closest nodes, and no lookup in progress: table is empty.
914            // This could happen if all records were deleted from the table due to missed pongs
915            // (e.g. connectivity problems over a long period of time, or issues during initial
916            // bootstrapping) so we attempt to bootstrap again
917            self.bootstrap();
918            return
919        }
920
921        trace!(target: "discv4", ?target, num = closest.len(), "Start lookup closest nodes");
922
923        for node in closest {
924            // here we still want to check against previous request failures and if necessary
925            // re-establish a new endpoint proof because it can be the case that the other node lost
926            // our entry and no longer has an endpoint proof on their end
927            self.find_node_checked(&node, ctx.clone());
928        }
929    }
930
931    /// Sends a new `FindNode` packet to the node with `target` as the lookup target.
932    ///
933    /// CAUTION: This expects there's a valid Endpoint proof to the given `node`.
934    fn find_node(&mut self, node: &NodeRecord, ctx: LookupContext) {
935        trace!(target: "discv4", ?node, lookup=?ctx.target(), "Sending FindNode");
936        ctx.mark_queried(node.id);
937        let (payload, hash) = self.find_node_packet(ctx.target());
938        let to = node.udp_addr();
939        trace!(target: "discv4", ?to, ?hash, "sending FindNode packet");
940        let _ = self.egress.try_send((payload, to)).map_err(|err| {
941            debug!(target: "discv4", %err, "dropped outgoing packet");
942        });
943        self.pending_find_nodes.insert(node.id, FindNodeRequest::new(ctx, to.ip()));
944    }
945
946    /// Sends a new `FindNode` packet to the node with `target` as the lookup target but checks
947    /// whether we should send a new ping first to renew the endpoint proof by checking the
948    /// previously failed findNode requests. It could be that the node is no longer reachable or
949    /// lost our entry.
950    fn find_node_checked(&mut self, node: &NodeRecord, ctx: LookupContext) {
951        let max_failures = self.config.max_find_node_failures;
952        let needs_ping = self
953            .on_entry(node.id, |entry| entry.exceeds_find_node_failures(max_failures))
954            .unwrap_or(true);
955        if needs_ping {
956            self.try_ping(*node, PingReason::Lookup(*node, ctx))
957        } else {
958            self.find_node(node, ctx)
959        }
960    }
961
962    /// Notifies all listeners.
963    ///
964    /// Removes all listeners that are closed.
965    fn notify(&mut self, update: DiscoveryUpdate) {
966        self.update_listeners.retain_mut(|listener| match listener.try_send(update.clone()) {
967            Ok(()) => true,
968            Err(err) => match err {
969                TrySendError::Full(_) => true,
970                TrySendError::Closed(_) => false,
971            },
972        });
973    }
974
975    /// Adds the ip to the ban list indefinitely
976    pub fn ban_ip(&mut self, ip: IpAddr) {
977        self.config.ban_list.ban_ip(ip);
978    }
979
980    /// Adds the peer to the ban list indefinitely.
981    pub fn ban_node(&mut self, node_id: PeerId) {
982        self.remove_node(node_id);
983        self.config.ban_list.ban_peer(node_id);
984    }
985
986    /// Adds the ip to the ban list until the given timestamp.
987    pub fn ban_ip_until(&mut self, ip: IpAddr, until: Instant) {
988        self.config.ban_list.ban_ip_until(ip, until);
989    }
990
991    /// Adds the peer to the ban list and bans it until the given timestamp
992    pub fn ban_node_until(&mut self, node_id: PeerId, until: Instant) {
993        self.remove_node(node_id);
994        self.config.ban_list.ban_peer_until(node_id, until);
995    }
996
997    /// Removes a `node_id` from the routing table.
998    ///
999    /// This allows applications, for whatever reason, to remove nodes from the local routing
1000    /// table. Returns `true` if the node was in the table and `false` otherwise.
1001    pub fn remove_node(&mut self, node_id: PeerId) -> bool {
1002        let key = kad_key(node_id);
1003        self.remove_key(node_id, key)
1004    }
1005
1006    /// Removes a `node_id` from the routing table but only if there are enough other nodes in the
1007    /// bucket (bucket must be at least half full)
1008    ///
1009    /// Returns `true` if the node was removed
1010    pub fn soft_remove_node(&mut self, node_id: PeerId) -> bool {
1011        let key = kad_key(node_id);
1012        let Some(bucket) = self.kbuckets.get_bucket(&key) else { return false };
1013        if bucket.num_entries() < MAX_NODES_PER_BUCKET / 2 {
1014            // skip half empty bucket
1015            return false
1016        }
1017        self.remove_key(node_id, key)
1018    }
1019
1020    fn remove_key(&mut self, node_id: PeerId, key: discv5::Key<NodeKey>) -> bool {
1021        let removed = self.kbuckets.remove(&key);
1022        if removed {
1023            trace!(target: "discv4", ?node_id, "removed node");
1024            self.notify(DiscoveryUpdate::Removed(node_id));
1025        }
1026        removed
1027    }
1028
1029    /// Gets the number of entries that are considered connected.
1030    pub fn num_connected(&self) -> usize {
1031        self.kbuckets.buckets_iter().fold(0, |count, bucket| count + bucket.num_connected())
1032    }
1033
1034    /// Check if the peer has an active bond.
1035    fn has_bond(&self, remote_id: PeerId, remote_ip: IpAddr) -> bool {
1036        if let Some(timestamp) = self.received_pongs.last_pong(remote_id, remote_ip) &&
1037            timestamp.elapsed() < self.config.bond_expiration
1038        {
1039            return true
1040        }
1041        false
1042    }
1043
1044    /// Applies a closure on the pending or present [`NodeEntry`].
1045    fn on_entry<F, R>(&mut self, peer_id: PeerId, f: F) -> Option<R>
1046    where
1047        F: FnOnce(&NodeEntry) -> R,
1048    {
1049        let key = kad_key(peer_id);
1050        match self.kbuckets.entry(&key) {
1051            BucketEntry::Present(entry, _) => Some(f(entry.value())),
1052            BucketEntry::Pending(entry, _) => Some(f(entry.value())),
1053            _ => None,
1054        }
1055    }
1056
1057    /// Update the entry on RE-ping.
1058    ///
1059    /// Invoked when we received the Pong to our [`PingReason::RePing`] ping.
1060    ///
1061    /// On re-ping we check for a changed `enr_seq` if eip868 is enabled and when it changed we sent
1062    /// a followup request to retrieve the updated ENR
1063    fn update_on_reping(&mut self, record: NodeRecord, mut last_enr_seq: Option<u64>) {
1064        if record.id == self.local_node_record.id {
1065            return
1066        }
1067
1068        // If EIP868 extension is disabled then we want to ignore this
1069        if !self.config.enable_eip868 {
1070            last_enr_seq = None;
1071        }
1072
1073        let key = kad_key(record.id);
1074        let old_enr = match self.kbuckets.entry(&key) {
1075            kbucket::Entry::Present(mut entry, _) => {
1076                entry.value_mut().update_with_enr(last_enr_seq)
1077            }
1078            kbucket::Entry::Pending(mut entry, _) => {
1079                entry.value_mut().update_with_enr(last_enr_seq)
1080            }
1081            _ => return,
1082        };
1083
1084        // Check if ENR was updated
1085        match (last_enr_seq, old_enr) {
1086            (Some(new), Some(old)) if new > old => {
1087                self.send_enr_request(record);
1088            }
1089            (Some(_), None) => {
1090                // got an ENR
1091                self.send_enr_request(record);
1092            }
1093            _ => {}
1094        };
1095    }
1096
1097    /// Callback invoked when we receive a pong from the peer.
1098    fn update_on_pong(&mut self, record: NodeRecord, mut last_enr_seq: Option<u64>) {
1099        if record.id == *self.local_peer_id() {
1100            return
1101        }
1102
1103        // If EIP868 extension is disabled then we want to ignore this
1104        if !self.config.enable_eip868 {
1105            last_enr_seq = None;
1106        }
1107
1108        // if the peer included a enr seq in the pong then we can try to request the ENR of that
1109        // node
1110        let has_enr_seq = last_enr_seq.is_some();
1111
1112        let key = kad_key(record.id);
1113        match self.kbuckets.entry(&key) {
1114            kbucket::Entry::Present(mut entry, old_status) => {
1115                // endpoint is now proven
1116                entry.value_mut().establish_proof();
1117                entry.value_mut().update_with_enr(last_enr_seq);
1118
1119                if !old_status.is_connected() {
1120                    let _ = entry.update(ConnectionState::Connected, Some(old_status.direction));
1121                    trace!(target: "discv4", ?record, "added after successful endpoint proof");
1122                    self.notify(DiscoveryUpdate::Added(record));
1123
1124                    if has_enr_seq {
1125                        // request the ENR of the node
1126                        self.send_enr_request(record);
1127                    }
1128                }
1129            }
1130            kbucket::Entry::Pending(mut entry, mut status) => {
1131                // endpoint is now proven
1132                entry.value_mut().establish_proof();
1133                entry.value_mut().update_with_enr(last_enr_seq);
1134
1135                if !status.is_connected() {
1136                    status.state = ConnectionState::Connected;
1137                    let _ = entry.update(status);
1138                    trace!(target: "discv4", ?record, "added after successful endpoint proof");
1139                    self.notify(DiscoveryUpdate::Added(record));
1140
1141                    if has_enr_seq {
1142                        // request the ENR of the node
1143                        self.send_enr_request(record);
1144                    }
1145                }
1146            }
1147            _ => {}
1148        };
1149    }
1150
1151    // Announces a full-bucket node once its endpoint is proven, pinging it first unless it is
1152    // already bonded at the record's IP.
1153    fn on_discovered_at_capacity(&mut self, record: NodeRecord) {
1154        if self.has_bond(record.id, record.address) {
1155            trace!(target: "discv4", ?record, "discovered proven record but bucket is full");
1156            self.notify(DiscoveryUpdate::DiscoveredAtCapacity(record));
1157        } else {
1158            self.try_ping(record, PingReason::AtCapacity);
1159        }
1160    }
1161
1162    /// Adds all nodes
1163    ///
1164    /// See [`Self::add_node`]
1165    pub fn add_all_nodes(&mut self, records: impl IntoIterator<Item = NodeRecord>) {
1166        for record in records {
1167            self.add_node(record);
1168        }
1169    }
1170
1171    /// If the node's not in the table yet, this will add it to the table and start the endpoint
1172    /// proof by sending a ping to the node.
1173    ///
1174    /// Returns `true` if the record was added successfully, and `false` if the node is either
1175    /// already in the table or the record's bucket is full.
1176    pub fn add_node(&mut self, record: NodeRecord) -> bool {
1177        let key = kad_key(record.id);
1178        match self.kbuckets.entry(&key) {
1179            kbucket::Entry::Absent(entry) => {
1180                let node = NodeEntry::new(record);
1181                match entry.insert(
1182                    node,
1183                    NodeStatus {
1184                        direction: ConnectionDirection::Outgoing,
1185                        state: ConnectionState::Disconnected,
1186                    },
1187                ) {
1188                    BucketInsertResult::Inserted | BucketInsertResult::Pending { .. } => {
1189                        trace!(target: "discv4", ?record, "inserted new record");
1190                    }
1191                    _ => return false,
1192                }
1193            }
1194            _ => return false,
1195        }
1196
1197        // send the initial ping to the _new_ node
1198        self.try_ping(record, PingReason::InitialInsert);
1199        true
1200    }
1201
1202    /// Encodes the packet, sends it and returns the hash.
1203    pub(crate) fn send_packet(&self, msg: Message, to: SocketAddr) -> B256 {
1204        let (payload, hash) = msg.encode(&self.secret_key);
1205        trace!(target: "discv4", r#type=?msg.msg_type(), ?to, ?hash, "sending packet");
1206        let _ = self.egress.try_send((payload, to)).map_err(|err| {
1207            debug!(
1208                target: "discv4",
1209                %err,
1210                "dropped outgoing packet",
1211            );
1212        });
1213        hash
1214    }
1215
1216    /// Returns a signed `FindNode` packet for `target`, reusing a cached payload when possible.
1217    fn find_node_packet(&mut self, target: PeerId) -> (Bytes, B256) {
1218        let expire = self.find_node_expiration();
1219        let cache_ttl = self.config.request_timeout / 4;
1220        CachedFindNode::get_or_sign(
1221            &mut self.cached_find_node,
1222            target,
1223            cache_ttl,
1224            &self.secret_key,
1225            expire,
1226        )
1227    }
1228
1229    /// Message handler for an incoming `Ping`
1230    fn on_ping(&mut self, ping: Ping, remote_addr: SocketAddr, remote_id: PeerId, hash: B256) {
1231        if self.is_expired(ping.expire) {
1232            // ping's expiration timestamp is in the past
1233            return
1234        }
1235
1236        // create the record
1237        let record = NodeRecord {
1238            address: remote_addr.ip(),
1239            udp_port: remote_addr.port(),
1240            tcp_port: ping.from.tcp_port,
1241            id: remote_id,
1242        }
1243        .into_ipv4_mapped();
1244
1245        let key = kad_key(record.id);
1246
1247        // See also <https://github.com/ethereum/devp2p/blob/master/discv4.md#ping-packet-0x01>:
1248        // > If no communication with the sender of this ping has occurred within the last 12h, a
1249        // > ping should be sent in addition to pong in order to receive an endpoint proof.
1250        //
1251        let mut is_new_insert = false;
1252        let mut is_at_capacity = false;
1253        let mut needs_bond = !self.has_bond(record.id, record.address);
1254        let mut is_proven = false;
1255
1256        let old_enr = match self.kbuckets.entry(&key) {
1257            kbucket::Entry::Present(mut entry, _) => {
1258                if entry.value().is_expired() {
1259                    // If no communication with the sender has occurred within the last 12h, a ping
1260                    // should be sent in addition to pong in order to receive an endpoint proof.
1261                    needs_bond = true;
1262                } else {
1263                    is_proven = entry.value().has_endpoint_proof;
1264                }
1265                entry.value_mut().update_with_enr(ping.enr_sq)
1266            }
1267            kbucket::Entry::Pending(mut entry, _) => {
1268                if entry.value().is_expired() {
1269                    // If no communication with the sender has occurred within the last 12h, a ping
1270                    // should be sent in addition to pong in order to receive an endpoint proof.
1271                    needs_bond = true;
1272                } else {
1273                    is_proven = entry.value().has_endpoint_proof;
1274                }
1275                entry.value_mut().update_with_enr(ping.enr_sq)
1276            }
1277            kbucket::Entry::Absent(entry) => {
1278                let mut node = NodeEntry::new(record);
1279                node.last_enr_seq = ping.enr_sq;
1280
1281                match entry.insert(
1282                    node,
1283                    NodeStatus {
1284                        direction: ConnectionDirection::Incoming,
1285                        // mark as disconnected until endpoint proof established on pong
1286                        state: ConnectionState::Disconnected,
1287                    },
1288                ) {
1289                    BucketInsertResult::Inserted | BucketInsertResult::Pending { .. } => {
1290                        // mark as new insert if insert was successful
1291                        is_new_insert = true;
1292                    }
1293                    BucketInsertResult::Full => {
1294                        // we received a ping but the corresponding bucket for the peer is already
1295                        // full, we can't add any additional peers to that bucket, but we still want
1296                        // to emit an event that we discovered the node
1297                        is_at_capacity = true;
1298                        needs_bond = true;
1299                    }
1300                    BucketInsertResult::TooManyIncoming | BucketInsertResult::NodeExists => {
1301                        needs_bond = true;
1302                        // insert unsuccessful but we still want to send the pong
1303                    }
1304                    BucketInsertResult::FailedFilter => return,
1305                }
1306
1307                None
1308            }
1309            kbucket::Entry::SelfEntry => return,
1310        };
1311
1312        // Send the pong before any ping: a peer that pinged us for a lookup sends its FindNode
1313        // on our ping, but only once it has our pong.
1314        let pong = Message::Pong(Pong {
1315            // we use the actual address of the peer
1316            to: record.into(),
1317            echo: hash,
1318            expire: ping.expire,
1319            enr_sq: self.enr_seq(),
1320        });
1321        self.send_packet(pong, remote_addr);
1322
1323        if is_at_capacity {
1324            self.on_discovered_at_capacity(record);
1325        }
1326
1327        // if node was absent also send a ping to establish the endpoint proof from our end
1328        if is_new_insert {
1329            self.try_ping(record, PingReason::InitialInsert);
1330        } else if needs_bond {
1331            self.try_ping(record, PingReason::EstablishBond);
1332        } else {
1333            // if node has been proven, this means we've received a pong and verified its endpoint
1334            // proof. We've also sent a pong above to verify our endpoint proof, so we can now
1335            // send our find_nodes request if PingReason::Lookup
1336            if is_proven && let Some((_, ctx)) = self.pending_lookup.remove(&record.id) {
1337                if self.pending_find_nodes.contains_key(&record.id) {
1338                    // there's already another pending request, unmark it so the next round can
1339                    // try to send it
1340                    ctx.unmark_queried(record.id);
1341                } else {
1342                    // we just received a ping from that peer so we can send a find node request
1343                    // directly
1344                    self.find_node(&record, ctx);
1345                }
1346            }
1347
1348            // Request ENR if included in the ping
1349            match (ping.enr_sq, old_enr) {
1350                (Some(new), Some(old)) if new > old => {
1351                    self.send_enr_request(record);
1352                }
1353                (Some(_), None) => {
1354                    self.send_enr_request(record);
1355                }
1356                _ => {}
1357            };
1358        }
1359    }
1360
1361    // Guarding function for [`Self::send_ping`] that applies pre-checks
1362    fn try_ping(&mut self, node: NodeRecord, reason: PingReason) {
1363        if node.id == *self.local_peer_id() {
1364            // don't ping ourselves
1365            return
1366        }
1367
1368        if self.pending_pings.get(&node.id).is_some_and(|ping| ping.node.address == node.address) {
1369            return
1370        }
1371
1372        if let Some(idx) = self.queued_pings.iter().position(|(queued, _)| {
1373            queued.id == node.id && queued.address.to_canonical() == node.address.to_canonical()
1374        }) {
1375            let (queued, queued_reason) = &self.queued_pings[idx];
1376            // Prefer the proven port when two bond pings compete for the same peer and IP.
1377            if matches!(reason, PingReason::EstablishBond) &&
1378                matches!(queued_reason, PingReason::EstablishBond) &&
1379                queued.udp_port != node.udp_port &&
1380                self.is_proven_endpoint(&node)
1381            {
1382                self.queued_pings.remove(idx);
1383            } else {
1384                return
1385            }
1386        }
1387
1388        if self.pending_pings.contains_key(&node.id) ||
1389            self.pending_find_nodes.contains_key(&node.id)
1390        {
1391            if matches!(reason, PingReason::EstablishBond) &&
1392                self.queued_pings.len() < MAX_QUEUED_PINGS
1393            {
1394                self.queued_pings.push_back((node, reason));
1395            }
1396            return
1397        }
1398
1399        if self.pending_pings.len() < self.max_pending_pings(&node, &reason) {
1400            self.send_ping(node, reason);
1401        } else if self.queued_pings.len() < MAX_QUEUED_PINGS {
1402            self.queued_pings.push_back((node, reason));
1403        }
1404    }
1405
1406    // Returns how many pings may be in flight before a ping to `node` has to wait. Lookups and
1407    // pings to an endpoint the node already proved may also use the `RESERVED_PINGS` slots.
1408    fn max_pending_pings(&mut self, node: &NodeRecord, reason: &PingReason) -> usize {
1409        if matches!(reason, PingReason::Lookup(..)) || self.is_proven_endpoint(node) {
1410            MAX_NODES_PING
1411        } else {
1412            MAX_NODES_PING - RESERVED_PINGS
1413        }
1414    }
1415
1416    // Whether the routing table has an endpoint proof for this node at its current UDP socket.
1417    fn is_proven_endpoint(&mut self, node: &NodeRecord) -> bool {
1418        self.on_entry(node.id, |entry| {
1419            entry.has_endpoint_proof &&
1420                entry.record.address.to_canonical() == node.address.to_canonical() &&
1421                entry.record.udp_port == node.udp_port
1422        })
1423        .unwrap_or_default()
1424    }
1425
1426    /// Sends a ping message to the node's UDP address.
1427    ///
1428    /// Returns the echo hash of the ping message.
1429    pub(crate) fn send_ping(&mut self, node: NodeRecord, reason: PingReason) -> B256 {
1430        let remote_addr = node.udp_addr();
1431        let id = node.id;
1432        let mut from: NodeEndpoint = self.local_node_record.into();
1433        from.tcp_port = if node.address.is_ipv4() {
1434            self.local_eip_868_enr.tcp4()
1435        } else {
1436            self.local_eip_868_enr.tcp6()
1437        }
1438        .unwrap_or_default();
1439        let ping =
1440            Ping { from, to: node.into(), expire: self.ping_expiration(), enr_sq: self.enr_seq() };
1441        trace!(target: "discv4", ?ping, "sending ping");
1442        let echo_hash = self.send_packet(Message::Ping(ping), remote_addr);
1443
1444        self.pending_pings
1445            .insert(id, PingRequest { sent_at: Instant::now(), node, echo_hash, reason });
1446        echo_hash
1447    }
1448
1449    /// Sends an enr request message to the node's UDP address.
1450    ///
1451    /// Returns the echo hash of the ping message.
1452    pub(crate) fn send_enr_request(&mut self, node: NodeRecord) {
1453        if !self.config.enable_eip868 {
1454            return
1455        }
1456        let remote_addr = node.udp_addr();
1457        let enr_request = EnrRequest { expire: self.enr_request_expiration() };
1458
1459        trace!(target: "discv4", ?enr_request, "sending enr request");
1460        let echo_hash = self.send_packet(Message::EnrRequest(enr_request), remote_addr);
1461
1462        self.pending_enr_requests
1463            .insert(node.id, EnrRequestState { sent_at: Instant::now(), echo_hash });
1464    }
1465
1466    /// Message handler for an incoming `Pong`.
1467    fn on_pong(&mut self, pong: Pong, remote_addr: SocketAddr, remote_id: PeerId) {
1468        if self.is_expired(pong.expire) {
1469            return
1470        }
1471
1472        let PingRequest { node, reason, .. } = match self.pending_pings.entry(remote_id) {
1473            Entry::Occupied(entry) => {
1474                {
1475                    let request = entry.get();
1476                    if request.echo_hash != pong.echo {
1477                        trace!(target: "discv4", from=?remote_addr, expected=?request.echo_hash, echo_hash=?pong.echo,"Got unexpected Pong");
1478                        return
1479                    }
1480                    // The echo only proves reachability at the IP the ping was sent to.
1481                    if request.node.udp_addr().ip().to_canonical() !=
1482                        remote_addr.ip().to_canonical()
1483                    {
1484                        trace!(target: "discv4", from=?remote_addr, expected=?request.node.udp_addr(), "Ignoring Pong from unexpected IP");
1485                        return
1486                    }
1487                }
1488                entry.remove()
1489            }
1490            Entry::Vacant(_) => return,
1491        };
1492
1493        // keep track of the pong
1494        self.received_pongs.on_pong(remote_id, remote_addr.ip());
1495
1496        match reason {
1497            PingReason::InitialInsert => {
1498                self.update_on_pong(node, pong.enr_sq);
1499                // Reset the lookup interval so the next poll_tick fires immediately,
1500                // rather than waiting the full ~20s for the first lookup.
1501                if self.pending_lookup_reset && self.config.bootstrap_nodes.contains(&node) {
1502                    self.pending_lookup_reset = false;
1503                    self.lookup_interval.reset();
1504                }
1505            }
1506            PingReason::EstablishBond => {
1507                // no initial lookup needed here since the node was already in the table.
1508                self.update_on_pong(node, pong.enr_sq);
1509            }
1510            PingReason::RePing => {
1511                self.update_on_reping(node, pong.enr_sq);
1512            }
1513            PingReason::Lookup(node, ctx) => {
1514                self.update_on_pong(node, pong.enr_sq);
1515                // insert node and assoc. lookup_context into the pending_lookup table to complete
1516                // our side of the endpoint proof verification.
1517                // Start the lookup timer here - and evict accordingly. Note that this is a separate
1518                // timer than the ping_request timer.
1519                self.pending_lookup.insert(node.id, (Instant::now(), ctx));
1520            }
1521            PingReason::AtCapacity => match self.on_entry(node.id, |entry| entry.record) {
1522                // Inserted while the ping was pending, so this pong is its endpoint proof.
1523                // The stored record carries the TCP port the node advertised itself.
1524                Some(stored) if stored.udp_addr() == node.udp_addr() => {
1525                    self.update_on_pong(stored, pong.enr_sq)
1526                }
1527                // Inserted at another endpoint, whose own proof ping this ping displaced.
1528                Some(stored) => self.try_ping(stored, PingReason::InitialInsert),
1529                None => {
1530                    trace!(target: "discv4", ?node, "discovered proven record but bucket is full");
1531                    self.notify(DiscoveryUpdate::DiscoveredAtCapacity(node));
1532                }
1533            },
1534        }
1535    }
1536
1537    /// Handler for an incoming `FindNode` message
1538    fn on_find_node(&mut self, msg: FindNode, remote_addr: SocketAddr, node_id: PeerId) {
1539        if self.is_expired(msg.expire) {
1540            // expiration timestamp is in the past
1541            return
1542        }
1543        if node_id == *self.local_peer_id() {
1544            // ignore find node requests to ourselves
1545            return
1546        }
1547
1548        if self.has_bond(node_id, remote_addr.ip()) {
1549            self.respond_closest(msg.id, remote_addr)
1550        }
1551    }
1552
1553    /// Handler for incoming `EnrResponse` message
1554    fn on_enr_response(&mut self, msg: EnrResponse, remote_addr: SocketAddr, id: PeerId) {
1555        trace!(target: "discv4", ?remote_addr, ?msg, "received ENR response");
1556        let Entry::Occupied(request) = self.pending_enr_requests.entry(id) else { return };
1557
1558        // A delayed response to an earlier request must not consume its replacement.
1559        // Also ensure the ENR's public key matches the expected node id.
1560        if request.get().echo_hash != msg.request_hash || id != pk2id(&msg.enr.public_key()) {
1561            return
1562        }
1563        request.remove();
1564
1565        let key = kad_key(id);
1566        let fork_id = msg.eth_fork_id();
1567        let (record, old_fork_id) = match self.kbuckets.entry(&key) {
1568            kbucket::Entry::Present(mut entry, _) => {
1569                let id = entry.value_mut().update_with_fork_id(fork_id);
1570                (entry.value().record, id)
1571            }
1572            kbucket::Entry::Pending(mut entry, _) => {
1573                let id = entry.value_mut().update_with_fork_id(fork_id);
1574                (entry.value().record, id)
1575            }
1576            _ => return,
1577        };
1578        match (fork_id, old_fork_id) {
1579            (Some(new), Some(old)) if new != old => {
1580                self.notify(DiscoveryUpdate::EnrForkId(record, new))
1581            }
1582            (Some(new), None) => self.notify(DiscoveryUpdate::EnrForkId(record, new)),
1583            _ => {}
1584        }
1585    }
1586
1587    /// Handler for incoming `EnrRequest` message
1588    fn on_enr_request(
1589        &self,
1590        msg: EnrRequest,
1591        remote_addr: SocketAddr,
1592        id: PeerId,
1593        request_hash: B256,
1594    ) {
1595        if !self.config.enable_eip868 || self.is_expired(msg.expire) {
1596            return
1597        }
1598
1599        if self.has_bond(id, remote_addr.ip()) {
1600            self.send_packet(
1601                Message::EnrResponse(EnrResponse {
1602                    request_hash,
1603                    enr: self.local_eip_868_enr.clone(),
1604                }),
1605                remote_addr,
1606            );
1607        }
1608    }
1609
1610    /// Handler for incoming `Neighbours` messages that are handled if they're responses to
1611    /// `FindNode` requests.
1612    fn on_neighbours(&mut self, msg: Neighbours, remote_addr: SocketAddr, node_id: PeerId) {
1613        if self.is_expired(msg.expire) {
1614            // response is expired
1615            return
1616        }
1617        // check if this request was expected
1618        let ctx = match self.pending_find_nodes.entry(node_id) {
1619            Entry::Occupied(mut entry) => {
1620                {
1621                    let request = entry.get_mut();
1622                    // `Neighbours` packets carry no request binding, so a validly signed packet
1623                    // from the queried node could be replayed from another address. Ignore it and
1624                    // keep the request armed for the genuine reply.
1625                    if !request.is_from_destination(remote_addr.ip()) {
1626                        trace!(target: "discv4", from=?remote_addr, expected=?request.destination, "Ignoring Neighbours from unexpected IP");
1627                        return
1628                    }
1629                    // Mark the request as answered
1630                    request.answered = true;
1631                    let total = request.response_count + msg.nodes.len();
1632
1633                    // Neighbours response is exactly 1 bucket (16 entries).
1634                    if total <= MAX_NODES_PER_BUCKET {
1635                        request.response_count = total;
1636                    } else {
1637                        trace!(target: "discv4", total, from=?remote_addr, "Received neighbors packet entries exceeds max nodes per bucket");
1638                        return
1639                    }
1640                };
1641
1642                if entry.get().response_count == MAX_NODES_PER_BUCKET {
1643                    // node responding with a full bucket of records
1644                    let ctx = entry.remove().lookup_context;
1645                    ctx.mark_responded(node_id);
1646                    ctx
1647                } else {
1648                    entry.get().lookup_context.clone()
1649                }
1650            }
1651            Entry::Vacant(_) => {
1652                // received neighbours response without requesting it
1653                trace!(target: "discv4", from=?remote_addr, "Received unsolicited Neighbours");
1654                return
1655            }
1656        };
1657
1658        // log the peers we discovered
1659        trace!(target: "discv4",
1660            target=format!("{:#?}", node_id),
1661            peers_count=msg.nodes.len(),
1662            peers=format!("[{:#}]", msg.nodes.iter()
1663                .map(|node_rec| node_rec.id
1664            ).format(", ")),
1665            "Received peers from Neighbours packet"
1666        );
1667
1668        // This is the recursive lookup step where we initiate new FindNode requests for new nodes
1669        // that were discovered.
1670        for node in msg.nodes.into_iter().map(NodeRecord::into_ipv4_mapped) {
1671            // prevent banned peers from being added to the context
1672            if self.config.ban_list.is_banned(&node.id, &node.address) {
1673                trace!(target: "discv4", peer_id=?node.id, ip=?node.address, "ignoring banned record");
1674                continue
1675            }
1676
1677            ctx.add_node(node);
1678        }
1679
1680        // get the next closest nodes, not yet queried nodes and start over.
1681        let closest =
1682            ctx.filter_closest(ALPHA, |node| !self.pending_find_nodes.contains_key(&node.id));
1683
1684        for closest in closest {
1685            let key = kad_key(closest.id);
1686            match self.kbuckets.entry(&key) {
1687                BucketEntry::Absent(entry) => {
1688                    // the node's endpoint is not proven yet, so we need to ping it first, on
1689                    // success, we will add the node to the pending_lookup table, and wait to send
1690                    // back a Pong before initiating a FindNode request.
1691                    // In order to prevent that this node is selected again on subsequent responses,
1692                    // while the ping is still active, we always mark it as queried.
1693                    ctx.mark_queried(closest.id);
1694                    let node = NodeEntry::new(closest);
1695                    match entry.insert(
1696                        node,
1697                        NodeStatus {
1698                            direction: ConnectionDirection::Outgoing,
1699                            state: ConnectionState::Disconnected,
1700                        },
1701                    ) {
1702                        BucketInsertResult::Inserted | BucketInsertResult::Pending { .. } => {
1703                            // only ping if the node was added to the table
1704                            self.try_ping(closest, PingReason::Lookup(closest, ctx.clone()))
1705                        }
1706                        BucketInsertResult::Full => {
1707                            // new node but the node's bucket is already full
1708                            self.on_discovered_at_capacity(closest)
1709                        }
1710                        _ => {}
1711                    }
1712                }
1713                BucketEntry::SelfEntry => {
1714                    // we received our own node entry
1715                }
1716                BucketEntry::Present(entry, _) => {
1717                    if entry.value().has_endpoint_proof {
1718                        if entry
1719                            .value()
1720                            .exceeds_find_node_failures(self.config.max_find_node_failures)
1721                        {
1722                            self.try_ping(closest, PingReason::Lookup(closest, ctx.clone()))
1723                        } else {
1724                            self.find_node(&closest, ctx.clone());
1725                        }
1726                    }
1727                }
1728                BucketEntry::Pending(entry, _) => {
1729                    if entry.value().has_endpoint_proof {
1730                        if entry
1731                            .value()
1732                            .exceeds_find_node_failures(self.config.max_find_node_failures)
1733                        {
1734                            self.try_ping(closest, PingReason::Lookup(closest, ctx.clone()))
1735                        } else {
1736                            self.find_node(&closest, ctx.clone());
1737                        }
1738                    }
1739                }
1740            }
1741        }
1742    }
1743
1744    /// Sends a Neighbours packet for `target` to the given addr
1745    fn respond_closest(&mut self, target: PeerId, to: SocketAddr) {
1746        let key = kad_key(target);
1747        let expire = self.send_neighbours_expiration();
1748
1749        let enforce_eip868 = self.config.enable_eip868 && self.config.enforce_eip868_neighbours;
1750
1751        // get the MAX_NODES_PER_BUCKET closest nodes to the target that completed the endpoint
1752        // proof, optionally filtering out entries that have no EIP-868 fork ID
1753        let closest_nodes = self
1754            .kbuckets
1755            .closest_values(&key)
1756            .filter(|entry| entry.value.has_endpoint_proof)
1757            .filter(|entry| !enforce_eip868 || entry.value.fork_id.is_some())
1758            .take(MAX_NODES_PER_BUCKET)
1759            .collect::<Vec<_>>();
1760
1761        if closest_nodes.is_empty() {
1762            // always respond so the requester does not treat this as a timeout
1763            let msg = Message::Neighbours(Neighbours { nodes: Vec::new(), expire });
1764            self.send_packet(msg, to);
1765            return;
1766        }
1767
1768        for nodes in closest_nodes.chunks(SAFE_MAX_DATAGRAM_NEIGHBOUR_RECORDS) {
1769            let nodes = nodes.iter().map(|node| node.value.record).collect::<Vec<NodeRecord>>();
1770            trace!(target: "discv4", len = nodes.len(), to=?to,"Sent neighbours packet");
1771            let msg = Message::Neighbours(Neighbours { nodes, expire });
1772            self.send_packet(msg, to);
1773        }
1774    }
1775
1776    fn evict_expired_requests(&mut self, now: Instant) {
1777        let mut failed_enr_requests = Vec::new();
1778        self.pending_enr_requests.retain(|node_id, enr_request| {
1779            if now.duration_since(enr_request.sent_at) < self.config.enr_expiration {
1780                return true
1781            }
1782            failed_enr_requests.push(*node_id);
1783            false
1784        });
1785
1786        // forget the announced enr seq, so the next ping or pong requests the ENR again.
1787        for node_id in failed_enr_requests {
1788            match self.kbuckets.entry(&kad_key(node_id)) {
1789                kbucket::Entry::Present(mut entry, _) => entry.value_mut().last_enr_seq = None,
1790                kbucket::Entry::Pending(mut entry, _) => entry.value_mut().last_enr_seq = None,
1791                _ => {}
1792            }
1793        }
1794
1795        let mut failed_pings = Vec::new();
1796        self.pending_pings.retain(|node_id, ping_request| {
1797            if now.duration_since(ping_request.sent_at) > self.config.ping_expiration {
1798                // An at-capacity ping was sent before the node had an entry, so it evicts nothing.
1799                if !matches!(ping_request.reason, PingReason::AtCapacity) {
1800                    failed_pings.push((*node_id, ping_request.node.udp_addr()));
1801                }
1802                return false
1803            }
1804            true
1805        });
1806
1807        if !failed_pings.is_empty() {
1808            // remove nodes that failed to pong
1809            trace!(target: "discv4", num=%failed_pings.len(), "evicting nodes due to failed pong");
1810            for (node_id, pinged) in failed_pings {
1811                // A proven node is only evicted when its stored endpoint failed to pong. A failed
1812                // ping to any other endpoint revalidates the stored one instead.
1813                let proven_elsewhere = self
1814                    .on_entry(node_id, |entry| entry.has_endpoint_proof.then_some(entry.record))
1815                    .flatten()
1816                    .filter(|record| record.udp_addr() != pinged);
1817                if let Some(record) = proven_elsewhere {
1818                    self.try_ping(record, PingReason::RePing);
1819                } else {
1820                    self.remove_node(node_id);
1821                }
1822            }
1823        }
1824
1825        let mut failed_lookups = Vec::new();
1826        self.pending_lookup.retain(|node_id, (lookup_sent_at, _)| {
1827            if now.duration_since(*lookup_sent_at) > self.config.request_timeout {
1828                failed_lookups.push(*node_id);
1829                return false
1830            }
1831            true
1832        });
1833
1834        if !failed_lookups.is_empty() {
1835            // remove nodes that failed the e2e lookup process, so we can restart it
1836            trace!(target: "discv4", num=%failed_lookups.len(), "evicting nodes due to failed lookup");
1837            for node_id in failed_lookups {
1838                self.remove_node(node_id);
1839            }
1840        }
1841
1842        self.evict_failed_find_nodes(now);
1843    }
1844
1845    /// Handles failed responses to `FindNode`
1846    fn evict_failed_find_nodes(&mut self, now: Instant) {
1847        let mut failed_find_nodes = Vec::new();
1848        self.pending_find_nodes.retain(|node_id, find_node_request| {
1849            if now.duration_since(find_node_request.sent_at) > self.config.neighbours_expiration {
1850                if !find_node_request.answered {
1851                    // node actually responded but with fewer entries than expected, but we don't
1852                    // treat this as an hard error since it responded.
1853                    failed_find_nodes.push((*node_id, find_node_request.destination));
1854                }
1855                return false
1856            }
1857            true
1858        });
1859
1860        if failed_find_nodes.is_empty() {
1861            return
1862        }
1863
1864        trace!(target: "discv4", num=%failed_find_nodes.len(), "processing failed find nodes");
1865
1866        for (node_id, destination) in failed_find_nodes {
1867            let key = kad_key(node_id);
1868            let failures = match self.kbuckets.entry(&key) {
1869                kbucket::Entry::Present(mut entry, _)
1870                    if entry.value().record.address.to_canonical() == destination =>
1871                {
1872                    entry.value_mut().inc_failed_request();
1873                    entry.value().find_node_failures
1874                }
1875                kbucket::Entry::Pending(mut entry, _)
1876                    if entry.value().record.address.to_canonical() == destination =>
1877                {
1878                    entry.value_mut().inc_failed_request();
1879                    entry.value().find_node_failures
1880                }
1881                // A request sent to another address is not the node's failure.
1882                _ => continue,
1883            };
1884
1885            // if the node failed to respond anything useful multiple times, remove the node from
1886            // the table, but only if there are enough other nodes in the bucket (bucket must be at
1887            // least half full)
1888            if failures > self.config.max_find_node_failures {
1889                self.soft_remove_node(node_id);
1890            }
1891        }
1892    }
1893
1894    /// Re-pings all nodes which endpoint proofs are considered expired: [`NodeEntry::is_expired`]
1895    ///
1896    /// This will send a `Ping` to the nodes, if a node fails to respond with a `Pong` to renew the
1897    /// endpoint proof it will be removed from the table.
1898    fn re_ping_oldest(&mut self) {
1899        let mut nodes = self
1900            .kbuckets
1901            .iter_ref()
1902            .filter(|entry| entry.node.value.is_expired())
1903            .map(|n| n.node.value)
1904            .collect::<Vec<_>>();
1905        nodes.sort_unstable_by_key(|a| a.last_seen);
1906        let to_ping = nodes.into_iter().map(|n| n.record).take(MAX_NODES_PING).collect::<Vec<_>>();
1907        for node in to_ping {
1908            self.try_ping(node, PingReason::RePing)
1909        }
1910    }
1911
1912    /// Returns true if the expiration timestamp is in the past.
1913    fn is_expired(&self, expiration: u64) -> bool {
1914        self.ensure_not_expired(expiration).is_err()
1915    }
1916
1917    /// Validate that given timestamp is not expired.
1918    ///
1919    /// Note: this accepts the timestamp as u64 because this is used by the wire protocol, but the
1920    /// UNIX timestamp (number of non-leap seconds since January 1, 1970 0:00:00 UTC) is supposed to
1921    /// be an i64.
1922    ///
1923    /// Returns an error if:
1924    ///  - invalid UNIX timestamp (larger than `i64::MAX`)
1925    ///  - timestamp is expired (lower than current local UNIX timestamp)
1926    fn ensure_not_expired(&self, timestamp: u64) -> Result<(), ()> {
1927        // ensure the timestamp is a valid UNIX timestamp
1928        let _ = i64::try_from(timestamp).map_err(drop)?;
1929
1930        let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
1931        if self.config.enforce_expiration_timestamps && timestamp < now {
1932            trace!(target: "discv4", "Expired packet");
1933            return Err(())
1934        }
1935        Ok(())
1936    }
1937
1938    /// Pops buffered ping requests and sends them.
1939    ///
1940    /// While only reserved slots are free, pings that can't use them stay queued in place.
1941    fn ping_buffered(&mut self) {
1942        let mut idx = 0;
1943        for _ in 0..self.queued_pings.len() {
1944            if self.pending_pings.len() >= MAX_NODES_PING {
1945                break
1946            }
1947            let Some((node, reason)) = self.queued_pings.remove(idx) else { break };
1948            if self.pending_pings.len() < self.max_pending_pings(&node, &reason) {
1949                self.try_ping(node, reason);
1950            } else {
1951                self.queued_pings.insert(idx, (node, reason));
1952                idx += 1;
1953            }
1954        }
1955    }
1956
1957    fn ping_expiration(&self) -> u64 {
1958        (SystemTime::now().duration_since(UNIX_EPOCH).unwrap() + self.config.ping_expiration)
1959            .as_secs()
1960    }
1961
1962    fn find_node_expiration(&self) -> u64 {
1963        (SystemTime::now().duration_since(UNIX_EPOCH).unwrap() + self.config.request_timeout)
1964            .as_secs()
1965    }
1966
1967    fn enr_request_expiration(&self) -> u64 {
1968        (SystemTime::now().duration_since(UNIX_EPOCH).unwrap() + self.config.enr_expiration)
1969            .as_secs()
1970    }
1971
1972    fn send_neighbours_expiration(&self) -> u64 {
1973        (SystemTime::now().duration_since(UNIX_EPOCH).unwrap() + self.config.neighbours_expiration)
1974            .as_secs()
1975    }
1976
1977    /// Polls the socket and advances the state.
1978    ///
1979    /// To prevent traffic amplification attacks, implementations must verify that the sender of a
1980    /// query participates in the discovery protocol. The sender of a packet is considered verified
1981    /// if it has sent a valid Pong response with matching ping hash within the last 12 hours.
1982    pub(crate) fn poll(&mut self, cx: &mut Context<'_>) -> Poll<Discv4Event> {
1983        loop {
1984            // drain buffered events first
1985            if let Some(event) = self.queued_events.pop_front() {
1986                return Poll::Ready(event)
1987            }
1988
1989            // trigger self lookup
1990            if self.config.enable_lookup {
1991                while self.lookup_interval.poll_tick(cx).is_ready() {
1992                    let target = self.lookup_rotator.next(&self.local_node_record.id);
1993                    self.lookup_with(target, None);
1994                }
1995            }
1996
1997            // re-ping some peers
1998            while self.ping_interval.poll_tick(cx).is_ready() {
1999                self.re_ping_oldest();
2000            }
2001
2002            if let Some(Poll::Ready(Some(ip))) =
2003                self.resolve_external_ip_interval.as_mut().map(|r| r.poll_tick(cx))
2004            {
2005                self.set_external_ip_addr(ip);
2006            }
2007
2008            // drain all incoming `Discv4` commands, this channel can never close
2009            while let Poll::Ready(Some(cmd)) = self.commands_rx.poll_recv(cx) {
2010                match cmd {
2011                    Discv4Command::Add(enr) => {
2012                        self.add_node(enr);
2013                    }
2014                    Discv4Command::AddBootNode(record) => {
2015                        self.add_boot_node(record);
2016                    }
2017                    Discv4Command::Lookup { node_id, tx } => {
2018                        let node_id = node_id.unwrap_or(self.local_node_record.id);
2019                        self.lookup_with(node_id, tx);
2020                    }
2021                    Discv4Command::SetLookupInterval(duration) => {
2022                        self.set_lookup_interval(duration);
2023                    }
2024                    Discv4Command::Updates(tx) => {
2025                        let rx = self.update_stream();
2026                        let _ = tx.send(rx);
2027                    }
2028                    Discv4Command::BanPeer(node_id) => self.ban_node(node_id),
2029                    Discv4Command::Remove(node_id) => {
2030                        self.remove_node(node_id);
2031                    }
2032                    Discv4Command::Ban(node_id, ip, until) => {
2033                        self.remove_node(node_id);
2034                        self.config.ban_list.ban_peer_with(node_id, until);
2035                        self.config.ban_list.ban_ip_with(ip, until);
2036                    }
2037                    Discv4Command::BanIp(ip, until) => {
2038                        self.config.ban_list.ban_ip_with(ip, until);
2039                    }
2040                    Discv4Command::SetEIP868RLPPair { key, rlp } => {
2041                        debug!(target: "discv4", key=%String::from_utf8_lossy(&key), "Update EIP-868 extension pair");
2042
2043                        let _ = self.local_eip_868_enr.insert_raw_rlp(key, rlp, &self.secret_key);
2044                    }
2045                    Discv4Command::SetTcpPort(port) => {
2046                        debug!(target: "discv4", %port, "Update tcp port");
2047                        self.local_node_record.tcp_port = port;
2048                        if self.local_node_record.address.is_ipv4() {
2049                            let _ = self.local_eip_868_enr.set_tcp4(port, &self.secret_key);
2050                        } else {
2051                            let _ = self.local_eip_868_enr.set_tcp6(port, &self.secret_key);
2052                        }
2053                        if let Some(ip) = self.config.secondary_advertised_ip {
2054                            if ip.is_ipv4() {
2055                                let _ = self.local_eip_868_enr.set_tcp4(port, &self.secret_key);
2056                            } else {
2057                                let _ = self.local_eip_868_enr.set_tcp6(port, &self.secret_key);
2058                            }
2059                        }
2060                    }
2061
2062                    Discv4Command::Terminated => {
2063                        // terminate the service
2064                        self.queued_events.push_back(Discv4Event::Terminated);
2065                    }
2066                }
2067            }
2068
2069            // restricts how many messages we process in a single poll before yielding back control
2070            let mut udp_message_budget = UDP_MESSAGE_POLL_LOOP_BUDGET;
2071
2072            // process all incoming datagrams
2073            while let Poll::Ready(Some(event)) = self.ingress.poll_recv(cx) {
2074                match event {
2075                    IngressEvent::RecvError(err) => {
2076                        debug!(target: "discv4", %err, "failed to read datagram");
2077                    }
2078                    IngressEvent::BadPacket(from, err, data) => {
2079                        trace!(target: "discv4", ?from, %err, packet=?hex::encode(&data), "bad packet");
2080                    }
2081                    IngressEvent::Packet(remote_addr, Packet { msg, node_id, hash }) => {
2082                        trace!(target: "discv4", r#type=?msg.msg_type(), from=?remote_addr,"received packet");
2083                        let event = match msg {
2084                            Message::Ping(ping) => {
2085                                self.on_ping(ping, remote_addr, node_id, hash);
2086                                Discv4Event::Ping
2087                            }
2088                            Message::Pong(pong) => {
2089                                self.on_pong(pong, remote_addr, node_id);
2090                                Discv4Event::Pong
2091                            }
2092                            Message::FindNode(msg) => {
2093                                self.on_find_node(msg, remote_addr, node_id);
2094                                Discv4Event::FindNode
2095                            }
2096                            Message::Neighbours(msg) => {
2097                                self.on_neighbours(msg, remote_addr, node_id);
2098                                Discv4Event::Neighbours
2099                            }
2100                            Message::EnrRequest(msg) => {
2101                                self.on_enr_request(msg, remote_addr, node_id, hash);
2102                                Discv4Event::EnrRequest
2103                            }
2104                            Message::EnrResponse(msg) => {
2105                                self.on_enr_response(msg, remote_addr, node_id);
2106                                Discv4Event::EnrResponse
2107                            }
2108                        };
2109
2110                        self.queued_events.push_back(event);
2111                    }
2112                }
2113
2114                udp_message_budget -= 1;
2115                if udp_message_budget < 0 {
2116                    trace!(target: "discv4", budget=UDP_MESSAGE_POLL_LOOP_BUDGET, "exhausted message poll budget");
2117                    if self.queued_events.is_empty() {
2118                        // we've exceeded the message budget and have no events to process
2119                        // this will make sure we're woken up again
2120                        cx.waker().wake_by_ref();
2121                    }
2122                    break
2123                }
2124            }
2125
2126            // try resending buffered pings
2127            self.ping_buffered();
2128
2129            // evict expired requests
2130            while self.evict_expired_requests_interval.poll_tick(cx).is_ready() {
2131                self.evict_expired_requests(Instant::now());
2132            }
2133
2134            // evict expired nodes and bans
2135            while self.expire_interval.poll_tick(cx).is_ready() {
2136                let now = Instant::now();
2137                self.received_pongs.evict_expired(now, EXPIRE_DURATION);
2138                self.config.ban_list.evict(now);
2139            }
2140
2141            if self.queued_events.is_empty() {
2142                return Poll::Pending
2143            }
2144        }
2145    }
2146}
2147
2148/// Endless future impl
2149impl Stream for Discv4Service {
2150    type Item = Discv4Event;
2151
2152    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2153        // Poll the internal poll method
2154        match ready!(self.get_mut().poll(cx)) {
2155            // if the service is terminated, return None to terminate the stream
2156            Discv4Event::Terminated => Poll::Ready(None),
2157            // For any other event, return Poll::Ready(Some(event))
2158            ev => Poll::Ready(Some(ev)),
2159        }
2160    }
2161}
2162
2163impl fmt::Debug for Discv4Service {
2164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2165        f.debug_struct("Discv4Service")
2166            .field("local_address", &self.local_address)
2167            .field("local_peer_id", &self.local_peer_id())
2168            .field("local_node_record", &self.local_node_record)
2169            .field("queued_pings", &self.queued_pings)
2170            .field("pending_lookup", &self.pending_lookup)
2171            .field("pending_find_nodes", &self.pending_find_nodes)
2172            .field("lookup_interval", &self.lookup_interval)
2173            .finish_non_exhaustive()
2174    }
2175}
2176
2177/// The Event type the Service stream produces.
2178///
2179/// This is mainly used for testing purposes and represents messages the service processed
2180#[derive(Debug, Eq, PartialEq)]
2181pub enum Discv4Event {
2182    /// A `Ping` message was handled.
2183    Ping,
2184    /// A `Pong` message was handled.
2185    Pong,
2186    /// A `FindNode` message was handled.
2187    FindNode,
2188    /// A `Neighbours` message was handled.
2189    Neighbours,
2190    /// A `EnrRequest` message was handled.
2191    EnrRequest,
2192    /// A `EnrResponse` message was handled.
2193    EnrResponse,
2194    /// Service is being terminated
2195    Terminated,
2196}
2197
2198/// Continuously reads new messages from the channel and writes them to the socket
2199pub(crate) async fn send_loop(
2200    udp: Arc<UdpSocket>,
2201    secondary_udp: Option<Arc<UdpSocket>>,
2202    primary_is_ipv4: bool,
2203    rx: EgressReceiver,
2204) {
2205    let mut stream = ReceiverStream::new(rx);
2206    while let Some((payload, to)) = stream.next().await {
2207        // a destination with no matching-family socket falls through to the primary, failing
2208        // in `send_to` like any other unreachable destination
2209        let socket = if to.is_ipv4() == primary_is_ipv4 {
2210            &udp
2211        } else {
2212            secondary_udp.as_ref().unwrap_or(&udp)
2213        };
2214        match socket.send_to(&payload, to).await {
2215            Ok(size) => {
2216                trace!(target: "discv4", ?to, ?size,"sent payload");
2217            }
2218            Err(err) => {
2219                debug!(target: "discv4", ?to, %err,"Failed to send datagram.");
2220            }
2221        }
2222    }
2223}
2224
2225/// Rate limits the number of incoming packets from individual IPs to 1 packet/second
2226const MAX_INCOMING_PACKETS_PER_MINUTE_BY_IP: usize = 60usize;
2227
2228/// Maximum number of IPs with a packet counter at the same time.
2229///
2230/// The UDP source address of a packet can be spoofed, so the counters must not grow with the
2231/// number of distinct IPs. At the limit, the counter of the least recently seen IP is dropped.
2232const MAX_TRACKED_INCOMING_IPS: u32 = 16_384;
2233
2234/// Continuously awaits new incoming messages and sends them back through the channel.
2235///
2236/// The receive loop enforces primitive rate limiting for IPs to prevent message spams from
2237/// individual IPs.
2238pub(crate) async fn receive_loop(udp: Arc<UdpSocket>, tx: IngressSender, local_id: PeerId) {
2239    let mut handler = IngressHandler::new(tx, local_id);
2240    let mut buf = [0; MAX_PACKET_SIZE];
2241    loop {
2242        let res = udp.recv_from(&mut buf).await;
2243        match res {
2244            Err(err) => {
2245                debug!(target: "discv4", %err, "Failed to read datagram.");
2246                handler.send(IngressEvent::RecvError(err)).await;
2247            }
2248            Ok((read, remote_addr)) => {
2249                handler.handle_packet(&buf[..read], remote_addr).await;
2250            }
2251        }
2252    }
2253}
2254
2255/// Handles decoding, rate-limiting, and deduplication of incoming discv4 packets.
2256///
2257/// Used by both the standalone receive loop and the shared-port mode via
2258/// [`Discv4::bind_shared`].
2259#[derive(Debug)]
2260pub struct IngressHandler {
2261    tx: IngressSender,
2262    local_id: PeerId,
2263    tick: usize,
2264    tick_interval: Duration,
2265    cache: ReceiveCache,
2266    last_tick: Instant,
2267}
2268
2269impl IngressHandler {
2270    fn new(tx: IngressSender, local_id: PeerId) -> Self {
2271        let tick = MAX_INCOMING_PACKETS_PER_MINUTE_BY_IP / 2;
2272        Self {
2273            tx,
2274            local_id,
2275            tick,
2276            tick_interval: Duration::from_secs(tick as u64),
2277            cache: ReceiveCache::default(),
2278            last_tick: Instant::now(),
2279        }
2280    }
2281
2282    async fn send(&self, event: IngressEvent) {
2283        let _ = self.tx.send(event).await.map_err(|err| {
2284            debug!(target: "discv4", %err, "failed send incoming packet");
2285        });
2286    }
2287
2288    /// Handles an incoming raw packet: decodes, rate-limits, deduplicates, and forwards to the
2289    /// discv4 service. Used in shared-port mode to process unrecognized frames from discv5.
2290    pub async fn handle_packet(&mut self, data: &[u8], src: SocketAddr) {
2291        if self.last_tick.elapsed() >= self.tick_interval {
2292            self.cache.tick_ips(self.tick);
2293            self.last_tick = Instant::now();
2294        }
2295
2296        // rate limit incoming packets by IP
2297        if self.cache.inc_ip(src.ip()) > MAX_INCOMING_PACKETS_PER_MINUTE_BY_IP {
2298            trace!(target: "discv4", ?src, "Too many incoming packets from IP.");
2299            return
2300        }
2301
2302        // A packet starts with the hash of everything that follows it, and `Message::decode`
2303        // rejects any packet whose contents do not hash to it. A repeat of a packet we already
2304        // accepted from the same IP can therefore be recognised from those 32 bytes alone,
2305        // without decoding.
2306        // Decoding runs an ECDSA recovery, so checking here keeps a replayed packet from costing
2307        // a signature verification.
2308        if data.len() >= MIN_PACKET_SIZE &&
2309            self.cache.contains_packet(B256::from_slice(&data[..32]), src.ip())
2310        {
2311            trace!(target: "discv4", ?src, "Received duplicate packet.");
2312            return
2313        }
2314
2315        let event = match Message::decode(data) {
2316            Ok(packet) => {
2317                if packet.node_id == self.local_id {
2318                    debug!(target: "discv4", ?src, "Received own packet.");
2319                    return
2320                }
2321
2322                // Only packets that decoded are remembered, so a peer cannot suppress a packet we
2323                // have not seen yet by guessing its hash.
2324                self.cache.insert_packet(packet.hash, src.ip());
2325
2326                IngressEvent::Packet(src, packet)
2327            }
2328            Err(err) => {
2329                trace!(target: "discv4", %err, "Failed to decode packet");
2330                IngressEvent::BadPacket(src, err, data.to_vec())
2331            }
2332        };
2333
2334        self.send(event).await;
2335    }
2336}
2337
2338/// A cache for received packets and their source address.
2339///
2340/// This is used to discard duplicated packets and rate limit messages from the same source.
2341#[derive(Debug)]
2342struct ReceiveCache {
2343    /// keeps track of how many messages we've received from a given IP address since the last
2344    /// tick.
2345    ///
2346    /// This is used to count the number of messages received from a given IP address within an
2347    /// interval.
2348    ip_messages: reth_lru::LruMap<IpAddr, usize>,
2349    /// Valid packet hashes paired with their canonical source IP.
2350    ///
2351    /// A replay from another IP must not suppress the genuine packet from the expected source.
2352    unique_packets: reth_lru::LruMap<(B256, IpAddr), ()>,
2353}
2354
2355impl ReceiveCache {
2356    /// Updates the counter for each IP address and removes IPs that have exceeded the limit.
2357    ///
2358    /// This will decrement the counter for each IP address and remove IPs that have reached 0.
2359    fn tick_ips(&mut self, tick: usize) {
2360        self.ip_messages.retain(|_, count| {
2361            if let Some(reset) = count.checked_sub(tick) {
2362                *count = reset;
2363                true
2364            } else {
2365                false
2366            }
2367        });
2368    }
2369
2370    /// Increases the counter for the given IP address and returns the new count.
2371    fn inc_ip(&mut self, ip: IpAddr) -> usize {
2372        // `get_or_insert` returns `None` only for a map without capacity, which counts nothing.
2373        self.ip_messages.get_or_insert(ip, usize::default).map_or(1, |ctn| {
2374            *ctn = ctn.saturating_add(1);
2375            *ctn
2376        })
2377    }
2378
2379    /// Returns true if we previously received the packet from this IP.
2380    ///
2381    /// A hit refreshes the entry so that a packet being replayed repeatedly stays cached.
2382    fn contains_packet(&mut self, hash: B256, ip: IpAddr) -> bool {
2383        self.unique_packets.get(&(hash, ip.to_canonical())).is_some()
2384    }
2385
2386    /// Remembers a packet we accepted.
2387    fn insert_packet(&mut self, hash: B256, ip: IpAddr) {
2388        self.unique_packets.insert((hash, ip.to_canonical()), ());
2389    }
2390}
2391
2392impl Default for ReceiveCache {
2393    fn default() -> Self {
2394        Self {
2395            ip_messages: reth_lru::LruMap::new(MAX_TRACKED_INCOMING_IPS),
2396            unique_packets: reth_lru::LruMap::new(32),
2397        }
2398    }
2399}
2400
2401/// The commands sent from the frontend [Discv4] to the service [`Discv4Service`].
2402enum Discv4Command {
2403    Add(NodeRecord),
2404    AddBootNode(NodeRecord),
2405    SetTcpPort(u16),
2406    SetEIP868RLPPair { key: Vec<u8>, rlp: Bytes },
2407    Ban(PeerId, IpAddr, Option<Instant>),
2408    BanPeer(PeerId),
2409    BanIp(IpAddr, Option<Instant>),
2410    Remove(PeerId),
2411    Lookup { node_id: Option<PeerId>, tx: Option<NodeRecordSender> },
2412    SetLookupInterval(Duration),
2413    Updates(OneshotSender<ReceiverStream<DiscoveryUpdate>>),
2414    Terminated,
2415}
2416
2417/// Event type receiver produces
2418#[derive(Debug)]
2419pub(crate) enum IngressEvent {
2420    /// Encountered an error when reading a datagram message.
2421    RecvError(io::Error),
2422    /// Received a bad message
2423    BadPacket(SocketAddr, DecodePacketError, Vec<u8>),
2424    /// Received a datagram from an address.
2425    Packet(SocketAddr, Packet),
2426}
2427
2428/// Tracks a sent ping
2429#[derive(Debug)]
2430struct PingRequest {
2431    // Timestamp when the request was sent.
2432    sent_at: Instant,
2433    // Node to which the request was sent.
2434    node: NodeRecord,
2435    // Hash sent in the Ping request
2436    echo_hash: B256,
2437    /// Why this ping was sent.
2438    reason: PingReason,
2439}
2440
2441/// Rotates the `PeerId` that is periodically looked up.
2442///
2443/// By selecting different targets, the lookups will be seeded with different ALPHA seed nodes.
2444#[derive(Debug)]
2445struct LookupTargetRotator {
2446    interval: usize,
2447    counter: usize,
2448}
2449
2450// === impl LookupTargetRotator ===
2451
2452impl LookupTargetRotator {
2453    /// Returns a rotator that always returns the local target.
2454    const fn local_only() -> Self {
2455        Self { interval: 1, counter: 0 }
2456    }
2457}
2458
2459impl Default for LookupTargetRotator {
2460    fn default() -> Self {
2461        Self {
2462            // every 4th lookup is our own node
2463            interval: 4,
2464            counter: 3,
2465        }
2466    }
2467}
2468
2469impl LookupTargetRotator {
2470    /// This will return the next node id to lookup
2471    fn next(&mut self, local: &PeerId) -> PeerId {
2472        self.counter += 1;
2473        self.counter %= self.interval;
2474        if self.counter == 0 {
2475            return *local
2476        }
2477        PeerId::random()
2478    }
2479}
2480
2481/// Tracks lookups across multiple `FindNode` requests.
2482///
2483/// If this type is dropped by all Clones, it will send all the discovered nodes to the listener, if
2484/// one is present.
2485#[derive(Clone, Debug)]
2486struct LookupContext {
2487    inner: Rc<LookupContextInner>,
2488}
2489
2490impl LookupContext {
2491    /// Create new context for a recursive lookup
2492    fn new(
2493        target: discv5::Key<NodeKey>,
2494        nearest_nodes: impl IntoIterator<Item = (Distance, NodeRecord)>,
2495        listener: Option<NodeRecordSender>,
2496    ) -> Self {
2497        let closest_nodes = nearest_nodes
2498            .into_iter()
2499            .map(|(distance, record)| {
2500                (distance, QueryNode { record, queried: false, responded: false })
2501            })
2502            .collect();
2503
2504        let inner = Rc::new(LookupContextInner {
2505            target,
2506            closest_nodes: RefCell::new(closest_nodes),
2507            listener,
2508        });
2509        Self { inner }
2510    }
2511
2512    /// Returns the target of this lookup
2513    fn target(&self) -> PeerId {
2514        self.inner.target.preimage().0
2515    }
2516
2517    fn closest(&self, num: usize) -> Vec<NodeRecord> {
2518        self.inner
2519            .closest_nodes
2520            .borrow()
2521            .iter()
2522            .filter(|(_, node)| !node.queried)
2523            .map(|(_, n)| n.record)
2524            .take(num)
2525            .collect()
2526    }
2527
2528    /// Returns the closest nodes that have not been queried yet.
2529    fn filter_closest<P>(&self, num: usize, filter: P) -> Vec<NodeRecord>
2530    where
2531        P: FnMut(&NodeRecord) -> bool,
2532    {
2533        self.inner
2534            .closest_nodes
2535            .borrow()
2536            .iter()
2537            .filter(|(_, node)| !node.queried)
2538            .map(|(_, n)| n.record)
2539            .filter(filter)
2540            .take(num)
2541            .collect()
2542    }
2543
2544    /// Inserts the node if it's missing
2545    fn add_node(&self, record: NodeRecord) {
2546        let distance = self.inner.target.distance(&kad_key(record.id));
2547        let mut closest = self.inner.closest_nodes.borrow_mut();
2548        if let btree_map::Entry::Vacant(entry) = closest.entry(distance) {
2549            entry.insert(QueryNode { record, queried: false, responded: false });
2550        }
2551    }
2552
2553    fn set_queried(&self, id: PeerId, val: bool) {
2554        if let Some((_, node)) =
2555            self.inner.closest_nodes.borrow_mut().iter_mut().find(|(_, node)| node.record.id == id)
2556        {
2557            node.queried = val;
2558        }
2559    }
2560
2561    /// Marks the node as queried
2562    fn mark_queried(&self, id: PeerId) {
2563        self.set_queried(id, true)
2564    }
2565
2566    /// Marks the node as not queried
2567    fn unmark_queried(&self, id: PeerId) {
2568        self.set_queried(id, false)
2569    }
2570
2571    /// Marks the node as responded
2572    fn mark_responded(&self, id: PeerId) {
2573        if let Some((_, node)) =
2574            self.inner.closest_nodes.borrow_mut().iter_mut().find(|(_, node)| node.record.id == id)
2575        {
2576            node.responded = true;
2577        }
2578    }
2579}
2580
2581// SAFETY: The [`Discv4Service`] is intended to be spawned as task which requires `Send`.
2582// The `LookupContext` is shared by all active `FindNode` requests that are part of the lookup step.
2583// Which can modify the context. The shared context is only ever accessed mutably when a `Neighbour`
2584// response is processed and all Clones are stored inside [`Discv4Service`], in other words it is
2585// guaranteed that there's only 1 owner ([`Discv4Service`]) of all possible [`Rc`] clones of
2586// [`LookupContext`].
2587unsafe impl Send for LookupContext {}
2588#[derive(Debug)]
2589struct LookupContextInner {
2590    /// The target to lookup.
2591    target: discv5::Key<NodeKey>,
2592    /// The closest nodes
2593    closest_nodes: RefCell<BTreeMap<Distance, QueryNode>>,
2594    /// A listener for all the nodes retrieved in this lookup
2595    ///
2596    /// This is present if the lookup was triggered manually via [Discv4] and we want to return all
2597    /// the nodes once the lookup finishes.
2598    listener: Option<NodeRecordSender>,
2599}
2600
2601impl Drop for LookupContextInner {
2602    fn drop(&mut self) {
2603        if let Some(tx) = self.listener.take() {
2604            // there's only 1 instance shared across `FindNode` requests, if this is dropped then
2605            // all requests finished, and we can send all results back
2606            let nodes = self
2607                .closest_nodes
2608                .take()
2609                .into_values()
2610                .filter(|node| node.responded)
2611                .map(|node| node.record)
2612                .collect();
2613            let _ = tx.send(nodes);
2614        }
2615    }
2616}
2617
2618/// Tracks the state of a recursive lookup step
2619#[derive(Debug, Clone, Copy)]
2620struct QueryNode {
2621    record: NodeRecord,
2622    queried: bool,
2623    responded: bool,
2624}
2625
2626#[derive(Debug)]
2627struct FindNodeRequest {
2628    // Timestamp when the request was sent.
2629    sent_at: Instant,
2630    // Number of items sent by the node
2631    response_count: usize,
2632    // Whether the request has been answered yet.
2633    answered: bool,
2634    /// Response buffer
2635    lookup_context: LookupContext,
2636    /// IP address the request was sent to, in canonical form.
2637    destination: IpAddr,
2638}
2639
2640// === impl FindNodeRequest ===
2641
2642impl FindNodeRequest {
2643    fn new(resp: LookupContext, destination: IpAddr) -> Self {
2644        Self {
2645            sent_at: Instant::now(),
2646            response_count: 0,
2647            answered: false,
2648            lookup_context: resp,
2649            destination: destination.to_canonical(),
2650        }
2651    }
2652
2653    /// Returns `true` if `ip` is the address this request was sent to.
2654    ///
2655    /// Only the IP is compared, not the port, and IPv4-mapped IPv6 addresses are treated as their
2656    /// IPv4 counterparts because a dual-stack socket reports IPv4 peers as mapped addresses.
2657    fn is_from_destination(&self, ip: IpAddr) -> bool {
2658        self.destination == ip.to_canonical()
2659    }
2660}
2661
2662/// Cached signed `FindNode` packet to avoid redundant ECDSA signing during Kademlia lookups.
2663#[derive(Debug)]
2664struct CachedFindNode {
2665    target: PeerId,
2666    payload: Bytes,
2667    hash: B256,
2668    cached_at: Instant,
2669}
2670
2671impl CachedFindNode {
2672    /// Returns the cached `(payload, hash)` if the target matches and the cache is still fresh,
2673    /// or signs a new packet, updates the cache, and returns it.
2674    fn get_or_sign(
2675        cache: &mut Option<Self>,
2676        target: PeerId,
2677        ttl: Duration,
2678        secret_key: &secp256k1::SecretKey,
2679        expire: u64,
2680    ) -> (Bytes, B256) {
2681        if let Some(c) = cache.as_ref() &&
2682            c.target == target &&
2683            c.cached_at.elapsed() < ttl
2684        {
2685            return (c.payload.clone(), c.hash);
2686        }
2687
2688        let msg = Message::FindNode(FindNode { id: target, expire });
2689        let (payload, hash) = msg.encode(secret_key);
2690
2691        *cache = Some(Self { target, payload: payload.clone(), hash, cached_at: Instant::now() });
2692
2693        (payload, hash)
2694    }
2695}
2696
2697#[derive(Debug)]
2698struct EnrRequestState {
2699    // Timestamp when the request was sent.
2700    sent_at: Instant,
2701    // Hash sent in the Ping request
2702    echo_hash: B256,
2703}
2704
2705/// Stored node info.
2706#[derive(Debug, Clone, Eq, PartialEq)]
2707struct NodeEntry {
2708    /// Node record info.
2709    record: NodeRecord,
2710    /// Timestamp of last pong.
2711    last_seen: Instant,
2712    /// Last enr seq we retrieved via a ENR request.
2713    last_enr_seq: Option<u64>,
2714    /// `ForkId` if retrieved via ENR requests.
2715    fork_id: Option<ForkId>,
2716    /// Counter for failed _consecutive_ findNode requests.
2717    find_node_failures: u8,
2718    /// Whether the endpoint of the peer is proven.
2719    has_endpoint_proof: bool,
2720}
2721
2722// === impl NodeEntry ===
2723
2724impl NodeEntry {
2725    /// Creates a new, unpopulated entry
2726    fn new(record: NodeRecord) -> Self {
2727        Self {
2728            record,
2729            last_seen: Instant::now(),
2730            last_enr_seq: None,
2731            fork_id: None,
2732            find_node_failures: 0,
2733            has_endpoint_proof: false,
2734        }
2735    }
2736
2737    #[cfg(test)]
2738    fn new_proven(record: NodeRecord) -> Self {
2739        let mut node = Self::new(record);
2740        node.has_endpoint_proof = true;
2741        node
2742    }
2743
2744    /// Marks the entry with an established proof and resets the consecutive failure counter.
2745    const fn establish_proof(&mut self) {
2746        self.has_endpoint_proof = true;
2747        self.find_node_failures = 0;
2748    }
2749
2750    /// Returns true if the tracked find node failures exceed the max amount
2751    const fn exceeds_find_node_failures(&self, max_failures: u8) -> bool {
2752        self.find_node_failures >= max_failures
2753    }
2754
2755    /// Updates the last timestamp and sets the enr seq
2756    fn update_with_enr(&mut self, last_enr_seq: Option<u64>) -> Option<u64> {
2757        self.update_now(|s| std::mem::replace(&mut s.last_enr_seq, last_enr_seq))
2758    }
2759
2760    /// Increases the failed request counter
2761    const fn inc_failed_request(&mut self) {
2762        self.find_node_failures += 1;
2763    }
2764
2765    /// Updates the last timestamp and sets the enr seq
2766    fn update_with_fork_id(&mut self, fork_id: Option<ForkId>) -> Option<ForkId> {
2767        self.update_now(|s| std::mem::replace(&mut s.fork_id, fork_id))
2768    }
2769
2770    /// Updates the `last_seen` timestamp and calls the closure
2771    fn update_now<F, R>(&mut self, f: F) -> R
2772    where
2773        F: FnOnce(&mut Self) -> R,
2774    {
2775        self.last_seen = Instant::now();
2776        f(self)
2777    }
2778}
2779
2780// === impl NodeEntry ===
2781
2782impl NodeEntry {
2783    /// Returns true if the node should be re-pinged.
2784    fn is_expired(&self) -> bool {
2785        self.last_seen.elapsed() > (ENDPOINT_PROOF_EXPIRATION / 2)
2786    }
2787}
2788
2789/// Represents why a ping is issued
2790#[derive(Debug)]
2791enum PingReason {
2792    /// Initial ping to a previously unknown peer that was inserted into the table.
2793    InitialInsert,
2794    /// A ping to a peer to establish a bond (endpoint proof).
2795    EstablishBond,
2796    /// Re-ping a peer.
2797    RePing,
2798    /// Part of a lookup to ensure endpoint is proven before we can send a `FindNode` request.
2799    Lookup(NodeRecord, LookupContext),
2800    /// Ping to a new peer whose bucket is full, announced as
2801    /// [`DiscoveryUpdate::DiscoveredAtCapacity`] once the pong proves its endpoint.
2802    AtCapacity,
2803}
2804
2805/// Represents node related updates state changes in the underlying node table
2806#[derive(Debug, Clone)]
2807pub enum DiscoveryUpdate {
2808    /// A new node was discovered _and_ added to the table.
2809    Added(NodeRecord),
2810    /// A new node with a proven endpoint was discovered but _not_ added to the table because it
2811    /// is currently full.
2812    DiscoveredAtCapacity(NodeRecord),
2813    /// Received a [`ForkId`] via EIP-868 for the given [`NodeRecord`].
2814    EnrForkId(NodeRecord, ForkId),
2815    /// Node that was removed from the table
2816    Removed(PeerId),
2817    /// A series of updates
2818    Batch(Vec<Self>),
2819}
2820
2821#[cfg(test)]
2822mod tests {
2823    use super::*;
2824    use crate::test_utils::{create_discv4, create_discv4_with_config, rng_endpoint, rng_record};
2825    use alloy_primitives::hex;
2826    use alloy_rlp::{Decodable, Encodable};
2827    use rand::Rng;
2828    use reth_ethereum_forks::{EnrForkIdEntry, ForkHash};
2829    use reth_net_banlist::BanList;
2830    use reth_network_peers::mainnet_nodes;
2831    use std::{future::poll_fn, net::Ipv6Addr};
2832
2833    /// Fills the farthest bucket, which half of all ids map to, and returns a new id in it.
2834    fn full_bucket_peer(service: &mut Discv4Service) -> PeerId {
2835        loop {
2836            let id = PeerId::random();
2837            let key = kad_key(id);
2838            if service.kbuckets.get_index(&key) != Some(u8::MAX as usize) {
2839                continue
2840            }
2841            if service.kbuckets.get_bucket(&key).unwrap().num_entries() == MAX_NODES_PER_BUCKET {
2842                return id
2843            }
2844            insert_proven_node(service, NodeRecord::new("10.2.0.1:30303".parse().unwrap(), id));
2845        }
2846    }
2847
2848    /// Removes a node from the farthest bucket, so that bucket has room for one more.
2849    fn free_farthest_bucket_slot(service: &mut Discv4Service) {
2850        let id = service
2851            .kbuckets
2852            .iter_ref()
2853            .map(|entry| entry.node.value.record.id)
2854            .find(|id| service.kbuckets.get_index(&kad_key(*id)) == Some(u8::MAX as usize))
2855            .unwrap();
2856        assert!(service.remove_node(id));
2857    }
2858
2859    // Fills `pending` ping slots and the queue, first with a bond ping to another port of `proven`.
2860    fn queue_wrong_port_bond(service: &mut Discv4Service, proven: NodeRecord, pending: usize) {
2861        insert_proven_node(service, proven);
2862        for _ in 0..pending {
2863            insert_initial_ping(service, NodeRecord { id: PeerId::random(), ..proven });
2864        }
2865        service.try_ping(proven.with_udp_port(30304), PingReason::EstablishBond);
2866        for _ in 1..MAX_QUEUED_PINGS {
2867            service
2868                .try_ping(NodeRecord { id: PeerId::random(), ..proven }, PingReason::InitialInsert);
2869        }
2870        assert_eq!(service.queued_pings.len(), MAX_QUEUED_PINGS);
2871    }
2872
2873    // Fills the ping slots that are not reserved for lookups and proven endpoints.
2874    fn fill_unreserved_pings(service: &mut Discv4Service) {
2875        for _ in 0..MAX_NODES_PING - RESERVED_PINGS {
2876            insert_initial_ping(service, rng_record(&mut rand::rng()));
2877        }
2878    }
2879
2880    #[tokio::test]
2881    async fn test_duplicate_packet_rejected_without_decoding() {
2882        let secret_key = SecretKey::new(&mut rand::rng());
2883        let local_id = pk2id(&secret_key.public_key());
2884        let (tx, mut rx) = mpsc::channel(16);
2885        let mut handler = IngressHandler::new(tx, local_id);
2886
2887        let remote_key = SecretKey::new(&mut rand::rng());
2888        let msg = Message::Ping(Ping {
2889            from: rng_endpoint(&mut rand::rng()),
2890            to: rng_endpoint(&mut rand::rng()),
2891            expire: u64::MAX,
2892            enr_sq: None,
2893        });
2894        let (packet, hash) = msg.encode(&remote_key);
2895        let src = SocketAddr::from((Ipv4Addr::new(10, 0, 0, 1).to_ipv6_mapped(), 30303));
2896
2897        handler.handle_packet(&packet, src).await;
2898        assert!(matches!(rx.try_recv(), Ok(IngressEvent::Packet(_, _))));
2899
2900        // Replays from the same IP are dropped regardless of address representation or port.
2901        for duplicate_src in [src, SocketAddr::from(([10, 0, 0, 1], 40404))] {
2902            handler.handle_packet(&packet, duplicate_src).await;
2903            assert_matches::assert_matches!(rx.try_recv(), Err(mpsc::error::TryRecvError::Empty));
2904        }
2905        assert!(handler.cache.contains_packet(hash, src.ip()));
2906    }
2907
2908    #[tokio::test]
2909    async fn test_undecodable_packet_does_not_poison_cache() {
2910        let secret_key = SecretKey::new(&mut rand::rng());
2911        let local_id = pk2id(&secret_key.public_key());
2912        let (tx, mut rx) = mpsc::channel(16);
2913        let mut handler = IngressHandler::new(tx, local_id);
2914
2915        let remote_key = SecretKey::new(&mut rand::rng());
2916        let msg = Message::Ping(Ping {
2917            from: rng_endpoint(&mut rand::rng()),
2918            to: rng_endpoint(&mut rand::rng()),
2919            expire: u64::MAX,
2920            enr_sq: None,
2921        });
2922        let (packet, hash) = msg.encode(&remote_key);
2923        let src = "10.0.0.1:30303".parse().unwrap();
2924
2925        // a packet carrying the right hash prefix but a corrupt body must not be remembered,
2926        // otherwise it could be used to suppress the real packet
2927        let mut forged = packet.to_vec();
2928        let last = forged.len() - 1;
2929        forged[last] ^= 0xff;
2930        handler.handle_packet(&forged, src).await;
2931        assert!(matches!(rx.try_recv(), Ok(IngressEvent::BadPacket(..))));
2932        assert!(!handler.cache.contains_packet(hash, src.ip()));
2933
2934        // so the genuine packet still gets through
2935        handler.handle_packet(&packet, src).await;
2936        assert!(matches!(rx.try_recv(), Ok(IngressEvent::Packet(_, _))));
2937    }
2938
2939    #[test]
2940    fn test_ip_counters_are_bounded() {
2941        let mut cache = ReceiveCache::default();
2942        let tick = MAX_INCOMING_PACKETS_PER_MINUTE_BY_IP / 2;
2943        let limit = MAX_TRACKED_INCOMING_IPS;
2944        let ip = |i: u32| IpAddr::from(Ipv4Addr::from(i));
2945
2946        // one IP goes over the rate limit
2947        let busy = ip(0);
2948        for _ in 0..=MAX_INCOMING_PACKETS_PER_MINUTE_BY_IP {
2949            cache.inc_ip(busy);
2950        }
2951
2952        // distinct IPs fill the cache up to the limit
2953        for i in 1..limit {
2954            assert_eq!(cache.inc_ip(ip(i)), 1);
2955        }
2956        assert_eq!(cache.ip_messages.len(), limit as usize);
2957
2958        // a packet from the busy IP makes it the most recently seen one, so further distinct IPs
2959        // drop the counters of the oldest IPs and not the counter of the busy IP
2960        let busy_count = MAX_INCOMING_PACKETS_PER_MINUTE_BY_IP + 2;
2961        assert_eq!(cache.inc_ip(busy), busy_count);
2962        for i in limit..limit + 2 {
2963            assert_eq!(cache.inc_ip(ip(i)), 1);
2964        }
2965        assert_eq!(cache.ip_messages.len(), limit as usize);
2966        assert_eq!(cache.ip_messages.peek(&ip(1)), None);
2967        assert_eq!(cache.ip_messages.peek(&ip(2)), None);
2968        assert_eq!(cache.ip_messages.peek(&busy), Some(&busy_count));
2969
2970        // a tick lowers the counters and forgets the IPs that sent less than a tick
2971        cache.tick_ips(tick);
2972        assert_eq!(cache.ip_messages.len(), 1);
2973        assert_eq!(cache.ip_messages.peek(&busy), Some(&(busy_count - tick)));
2974
2975        // a tick keeps the order of the IPs that stay
2976        let other = ip(1);
2977        for _ in 0..tick {
2978            cache.inc_ip(other);
2979        }
2980        cache.inc_ip(busy);
2981        cache.tick_ips(tick);
2982        assert_eq!(cache.ip_messages.peek_oldest(), Some((&other, &0)));
2983        assert_eq!(cache.ip_messages.peek_newest(), Some((&busy, &(busy_count + 1 - 2 * tick))));
2984    }
2985
2986    #[tokio::test]
2987    async fn test_configured_enr_forkid_entry() {
2988        let fork: ForkId = ForkId { hash: ForkHash([220, 233, 108, 45]), next: 0u64 };
2989        let mut disc_conf = Discv4Config::default();
2990        disc_conf.add_eip868_pair("eth", EnrForkIdEntry::from(fork));
2991        let (_discv4, service) = create_discv4_with_config(disc_conf).await;
2992        let eth = service.local_eip_868_enr.get_raw_rlp(b"eth").unwrap();
2993        let fork_entry_id = EnrForkIdEntry::decode(&mut &eth[..]).unwrap();
2994
2995        let raw: [u8; 8] = [0xc7, 0xc6, 0x84, 0xdc, 0xe9, 0x6c, 0x2d, 0x80];
2996        let decoded = EnrForkIdEntry::decode(&mut &raw[..]).unwrap();
2997        let expected = EnrForkIdEntry {
2998            fork_id: ForkId { hash: ForkHash([0xdc, 0xe9, 0x6c, 0x2d]), next: 0 },
2999        };
3000        assert_eq!(expected, fork_entry_id);
3001        assert_eq!(expected, decoded);
3002    }
3003
3004    #[tokio::test]
3005    async fn test_secondary_advertised_ip_in_enr() {
3006        let (Ok(secondary), Ok(secondary2)) =
3007            (UdpSocket::bind("[::1]:0").await, UdpSocket::bind("[::1]:0").await)
3008        else {
3009            // no IPv6 loopback on this host
3010            return;
3011        };
3012        let mut rng = rand::rng();
3013        let (secret_key, pk) = secp256k1::generate_keypair(&mut rng);
3014        let local_enr = NodeRecord {
3015            address: Ipv4Addr::LOCALHOST.into(),
3016            tcp_port: 30303,
3017            udp_port: 30303,
3018            id: pk2id(&pk),
3019        };
3020
3021        let ip6: Ipv6Addr = "2001:db8::1".parse().unwrap();
3022        let config = Discv4Config::builder().secondary_advertised_ip(ip6.into()).build();
3023        let socket = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
3024        let (_discv4, service, _ingress) =
3025            Discv4::bind_shared(socket, Some(Arc::new(secondary)), local_enr, secret_key, config)
3026                .unwrap();
3027
3028        let enr = &service.local_eip_868_enr;
3029        assert_eq!(enr.ip6(), Some(ip6));
3030        assert_eq!(enr.udp6(), Some(service.local_node_record.udp_port));
3031        assert_eq!(enr.tcp6(), Some(service.local_node_record.tcp_port));
3032
3033        // an unspecified secondary is normalized away even with a secondary socket
3034        let config =
3035            Discv4Config::builder().secondary_advertised_ip(Ipv6Addr::UNSPECIFIED.into()).build();
3036        let socket = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
3037        let (_discv4, service, _ingress) =
3038            Discv4::bind_shared(socket, Some(Arc::new(secondary2)), local_enr, secret_key, config)
3039                .unwrap();
3040
3041        let enr = &service.local_eip_868_enr;
3042        assert_eq!(enr.ip6(), None);
3043        assert_eq!(enr.udp6(), None);
3044        assert_eq!(enr.tcp6(), None);
3045    }
3046
3047    #[tokio::test]
3048    async fn test_secondary_advertised_ip_requires_secondary_socket() {
3049        let ip6: Ipv6Addr = "2001:db8::1".parse().unwrap();
3050        let config = Discv4Config::builder().secondary_advertised_ip(ip6.into()).build();
3051        let (_discv4, service) = create_discv4_with_config(config).await;
3052
3053        let enr = &service.local_eip_868_enr;
3054        assert_eq!(enr.ip6(), None);
3055        assert_eq!(enr.udp6(), None);
3056        assert_eq!(enr.tcp6(), None);
3057    }
3058
3059    #[tokio::test]
3060    async fn test_external_ip_completes_unspecified_enr_endpoint() {
3061        let mut rng = rand::rng();
3062        let socket: SocketAddr = "127.0.0.1:0".parse().unwrap();
3063        let (secret_key, pk) = secp256k1::generate_keypair(&mut rng);
3064        let local_enr = NodeRecord {
3065            address: Ipv4Addr::UNSPECIFIED.into(),
3066            tcp_port: 30303,
3067            udp_port: 30303,
3068            id: pk2id(&pk),
3069        };
3070        let (_discv4, mut service) =
3071            Discv4::bind(socket, local_enr, secret_key, Default::default()).await.unwrap();
3072
3073        let udp_port = service.local_node_record.udp_port;
3074        let enr = &service.local_eip_868_enr;
3075        assert_eq!(enr.ip4(), None);
3076        assert_eq!(enr.udp4(), Some(udp_port));
3077        assert_eq!(enr.tcp4(), Some(30303));
3078
3079        let external_ip: Ipv4Addr = "1.2.3.4".parse().unwrap();
3080        service.set_external_ip_addr(external_ip.into());
3081
3082        let enr = &service.local_eip_868_enr;
3083        assert_eq!(enr.ip4(), Some(external_ip));
3084        assert_eq!(enr.udp4(), Some(udp_port));
3085        assert_eq!(enr.tcp4(), Some(30303));
3086    }
3087
3088    #[tokio::test]
3089    async fn test_send_loop_routes_by_destination_family() {
3090        let (Ok(secondary), Ok(sink6)) =
3091            (UdpSocket::bind("[::1]:0").await, UdpSocket::bind("[::1]:0").await)
3092        else {
3093            // no IPv6 loopback on this host
3094            return;
3095        };
3096        let primary = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
3097        let sink4 = UdpSocket::bind("127.0.0.1:0").await.unwrap();
3098
3099        let (tx, rx) = mpsc::channel(8);
3100        tokio::spawn(send_loop(primary, Some(Arc::new(secondary)), true, rx));
3101
3102        tx.send((Bytes::from_static(b"v4"), sink4.local_addr().unwrap())).await.unwrap();
3103        tx.send((Bytes::from_static(b"v6"), sink6.local_addr().unwrap())).await.unwrap();
3104
3105        let mut buf = [0u8; 2];
3106        let (read, _) = tokio::time::timeout(Duration::from_secs(5), sink4.recv_from(&mut buf))
3107            .await
3108            .unwrap()
3109            .unwrap();
3110        assert_eq!(&buf[..read], b"v4");
3111        let (read, _) = tokio::time::timeout(Duration::from_secs(5), sink6.recv_from(&mut buf))
3112            .await
3113            .unwrap()
3114            .unwrap();
3115        assert_eq!(&buf[..read], b"v6");
3116    }
3117
3118    #[test]
3119    fn test_enr_forkid_entry_decode() {
3120        let raw: [u8; 8] = [0xc7, 0xc6, 0x84, 0xdc, 0xe9, 0x6c, 0x2d, 0x80];
3121        let decoded = EnrForkIdEntry::decode(&mut &raw[..]).unwrap();
3122        let expected = EnrForkIdEntry {
3123            fork_id: ForkId { hash: ForkHash([0xdc, 0xe9, 0x6c, 0x2d]), next: 0 },
3124        };
3125        assert_eq!(expected, decoded);
3126    }
3127
3128    #[test]
3129    fn test_enr_forkid_entry_encode() {
3130        let original = EnrForkIdEntry {
3131            fork_id: ForkId { hash: ForkHash([0xdc, 0xe9, 0x6c, 0x2d]), next: 0 },
3132        };
3133        let expected: [u8; 8] = [0xc7, 0xc6, 0x84, 0xdc, 0xe9, 0x6c, 0x2d, 0x80];
3134        let mut encoded = Vec::with_capacity(expected.len());
3135        original.encode(&mut encoded);
3136        assert_eq!(&expected[..], encoded.as_slice());
3137    }
3138
3139    #[tokio::test]
3140    async fn test_request_enr_of_proven_node() {
3141        reth_tracing::init_test_tracing();
3142        let mut rng = rand::rng();
3143        let (_discv4, mut service) = create_discv4().await;
3144
3145        let id = PeerId::random();
3146        let addr: SocketAddr = (Ipv4Addr::new(10, 0, 0, 1), DEFAULT_DISCOVERY_PORT).into();
3147        let mut entry = NodeEntry::new_proven(NodeRecord::new(addr, id));
3148        entry.last_enr_seq = Some(1);
3149        let _ = service.kbuckets.insert_or_update(
3150            &kad_key(id),
3151            entry,
3152            NodeStatus {
3153                direction: ConnectionDirection::Outgoing,
3154                state: ConnectionState::Connected,
3155            },
3156        );
3157        service.received_pongs.on_pong(id, addr.ip());
3158        let ping = |service: &Discv4Service, rng: &mut rand::rngs::ThreadRng| Ping {
3159            from: rng_endpoint(rng),
3160            to: rng_endpoint(rng),
3161            expire: service.ping_expiration(),
3162            enr_sq: Some(2),
3163        };
3164
3165        // the node announces a newer record.
3166        service.on_ping(ping(&service, &mut rng), addr, id, B256::random());
3167        assert!(service.pending_enr_requests.contains_key(&id));
3168
3169        // the request goes unanswered, so the next ping has to ask again.
3170        service.evict_expired_requests(Instant::now() + service.config.enr_expiration * 2);
3171        assert!(!service.pending_enr_requests.contains_key(&id));
3172        service.on_ping(ping(&service, &mut rng), addr, id, B256::random());
3173        assert!(service.pending_enr_requests.contains_key(&id));
3174    }
3175
3176    #[test]
3177    fn test_local_rotator() {
3178        let id = PeerId::random();
3179        let mut rotator = LookupTargetRotator::local_only();
3180        assert_eq!(rotator.next(&id), id);
3181        assert_eq!(rotator.next(&id), id);
3182    }
3183
3184    #[test]
3185    fn test_rotator() {
3186        let id = PeerId::random();
3187        let mut rotator = LookupTargetRotator::default();
3188        assert_eq!(rotator.next(&id), id);
3189        assert_ne!(rotator.next(&id), id);
3190        assert_ne!(rotator.next(&id), id);
3191        assert_ne!(rotator.next(&id), id);
3192        assert_eq!(rotator.next(&id), id);
3193    }
3194
3195    #[tokio::test]
3196    async fn test_ping_establishes_bond_per_ip() {
3197        for (primary, secondary) in
3198            [("127.0.0.1:30303", "[::1]:30303"), ("[::1]:30303", "127.0.0.1:30303")]
3199        {
3200            for initial_ping_pending in [false, true] {
3201                let (_, mut service) = create_discv4().await;
3202                let (egress, mut packets) = mpsc::channel(16);
3203                service.egress = egress;
3204                let primary = NodeRecord::new(primary.parse().unwrap(), PeerId::random());
3205                let secondary = NodeRecord::new(secondary.parse().unwrap(), primary.id);
3206                service.add_node(primary);
3207                let pong = Pong {
3208                    to: service.local_node_record.into(),
3209                    echo: service.pending_pings[&primary.id].echo_hash,
3210                    expire: service.ping_expiration(),
3211                    enr_sq: None,
3212                };
3213                if !initial_ping_pending {
3214                    service.on_pong(pong.clone(), primary.udp_addr(), primary.id);
3215                }
3216
3217                let ping = Ping {
3218                    from: secondary.into(),
3219                    to: service.local_node_record.into(),
3220                    expire: service.ping_expiration(),
3221                    enr_sq: None,
3222                };
3223                service.on_ping(ping.clone(), secondary.udp_addr(), secondary.id, B256::random());
3224                if initial_ping_pending {
3225                    assert_eq!(service.queued_pings.len(), 1);
3226                    service.ping_buffered();
3227                    assert_eq!(service.queued_pings.len(), 1);
3228                    service.on_pong(pong, primary.udp_addr(), primary.id);
3229                    service.ping_buffered();
3230                }
3231
3232                assert!(service.has_bond(primary.id, primary.address));
3233                assert!(!service.has_bond(secondary.id, secondary.address));
3234                let request = &service.pending_pings[&secondary.id];
3235                assert_eq!(request.node.address, secondary.address);
3236                assert!(matches!(request.reason, PingReason::EstablishBond));
3237                let pong = Pong {
3238                    to: service.local_node_record.into(),
3239                    echo: request.echo_hash,
3240                    expire: service.ping_expiration(),
3241                    enr_sq: None,
3242                };
3243                while packets.try_recv().is_ok() {}
3244                let find_node =
3245                    FindNode { id: PeerId::random(), expire: service.ping_expiration() };
3246                service.on_find_node(find_node, secondary.udp_addr(), secondary.id);
3247                assert!(packets.try_recv().is_err());
3248
3249                service.on_pong(pong, secondary.udp_addr(), secondary.id);
3250                assert!(service.has_bond(primary.id, primary.address));
3251                assert!(service.has_bond(secondary.id, secondary.address));
3252                service.on_find_node(find_node, secondary.udp_addr(), secondary.id);
3253                let (packet, to) = packets.try_recv().unwrap();
3254                assert_eq!(to, secondary.udp_addr());
3255                assert!(matches!(Message::decode(&packet).unwrap().msg, Message::Neighbours(_)));
3256
3257                service.on_ping(ping, secondary.udp_addr(), secondary.id, B256::random());
3258                assert!(service.pending_pings.is_empty());
3259                assert!(service.queued_pings.is_empty());
3260            }
3261        }
3262    }
3263
3264    #[tokio::test]
3265    async fn test_neighbours_exclude_unproven_nodes() {
3266        let (_, mut service) = create_discv4().await;
3267        let (egress, mut packets) = mpsc::channel(16);
3268        service.egress = egress;
3269        let proven = NodeRecord::new("127.0.0.1:30303".parse().unwrap(), PeerId::random());
3270        insert_proven_node(&mut service, proven);
3271
3272        // An incoming ping inserts its sender before the endpoint proof completes.
3273        let unproven = NodeRecord::new("127.0.0.2:30303".parse().unwrap(), PeerId::random());
3274        let ping = Ping {
3275            from: unproven.into(),
3276            to: service.local_node_record.into(),
3277            expire: service.ping_expiration(),
3278            enr_sq: None,
3279        };
3280        service.on_ping(ping, unproven.udp_addr(), unproven.id, B256::random());
3281        assert_eq!(service.on_entry(unproven.id, |entry| entry.has_endpoint_proof), Some(false));
3282        while packets.try_recv().is_ok() {}
3283
3284        let find_node = FindNode { id: unproven.id, expire: service.ping_expiration() };
3285        service.on_find_node(find_node, proven.udp_addr(), proven.id);
3286        let (packet, to) = packets.try_recv().unwrap();
3287        assert_eq!(to, proven.udp_addr());
3288        let Message::Neighbours(neighbours) = Message::decode(&packet).unwrap().msg else {
3289            panic!("expected a neighbours packet")
3290        };
3291        assert_eq!(neighbours.nodes, vec![proven]);
3292    }
3293
3294    #[tokio::test]
3295    async fn test_ping_advertises_tcp_port_per_family() {
3296        let (_, mut service) = create_discv4().await;
3297        let (egress, mut packets) = mpsc::channel(16);
3298        service.egress = egress;
3299        service.local_node_record.tcp_port = 30303;
3300        service.local_eip_868_enr.set_tcp4(30303, &service.secret_key).unwrap();
3301
3302        for (tcp6, expected_tcp6) in [(None, 0), (Some(30304), 30304), (Some(0), 0)] {
3303            if let Some(port) = tcp6 {
3304                service.local_eip_868_enr.set_tcp6(port, &service.secret_key).unwrap();
3305            }
3306            for (addr, expected) in [("127.0.0.1:30303", 30303), ("[::1]:30303", expected_tcp6)] {
3307                let record = NodeRecord::new(addr.parse().unwrap(), PeerId::random());
3308                service.send_ping(record, PingReason::InitialInsert);
3309                let (packet, to) = packets.try_recv().unwrap();
3310                assert_eq!(to, record.udp_addr());
3311                let Message::Ping(ping) = Message::decode(&packet).unwrap().msg else {
3312                    panic!("expected ping");
3313                };
3314                assert_eq!(ping.from.tcp_port, expected);
3315            }
3316        }
3317    }
3318
3319    #[tokio::test]
3320    async fn proven_renewal_supersedes_queued_wrong_port() {
3321        let (_, mut service) = create_discv4().await;
3322        let proven = NodeRecord::new("127.0.0.1:30303".parse().unwrap(), PeerId::random());
3323        queue_wrong_port_bond(&mut service, proven, MAX_NODES_PING - RESERVED_PINGS);
3324
3325        // The renewal takes a reserved slot and drops the queued wrong-port ping.
3326        service.try_ping(proven, PingReason::EstablishBond);
3327        assert_eq!(service.pending_pings[&proven.id].node, proven);
3328        assert_eq!(service.queued_pings.len(), MAX_QUEUED_PINGS - 1);
3329        assert!(service.queued_pings.iter().all(|(node, _)| node.id != proven.id));
3330    }
3331
3332    #[tokio::test]
3333    async fn queued_proven_renewal_supersedes_wrong_port() {
3334        let (_, mut service) = create_discv4().await;
3335        let proven = NodeRecord::new("127.0.0.1:30303".parse().unwrap(), PeerId::random());
3336        queue_wrong_port_bond(&mut service, proven, MAX_NODES_PING);
3337
3338        // Another port and a repeated renewal must leave the proven endpoint queued once.
3339        service.try_ping(proven, PingReason::EstablishBond);
3340        service.try_ping(proven.with_udp_port(30304), PingReason::EstablishBond);
3341        service.try_ping(proven, PingReason::EstablishBond);
3342        assert_eq!(service.queued_pings.len(), MAX_QUEUED_PINGS);
3343
3344        let completed = *service.pending_pings.keys().next().unwrap();
3345        service.pending_pings.remove(&completed);
3346        service.ping_buffered();
3347        assert_eq!(service.pending_pings[&proven.id].node, proven);
3348        assert_eq!(service.queued_pings.len(), MAX_QUEUED_PINGS - 1);
3349        assert!(service.queued_pings.iter().all(|(node, _)| node.id != proven.id));
3350    }
3351
3352    #[tokio::test]
3353    async fn test_pending_ping() {
3354        let (_, mut service) = create_discv4().await;
3355
3356        let local_addr = service.local_addr();
3357
3358        let mut num_inserted = 0;
3359        loop {
3360            let node = NodeRecord::new(local_addr, PeerId::random());
3361            if service.add_node(node) {
3362                num_inserted += 1;
3363                assert!(service.pending_pings.contains_key(&node.id));
3364                assert_eq!(service.pending_pings.len(), num_inserted);
3365                if num_inserted == MAX_NODES_PING - RESERVED_PINGS {
3366                    break
3367                }
3368            }
3369        }
3370
3371        // Unreserved slots are full, insert into `queued_pings`.
3372        num_inserted = 0;
3373        for _ in 0..MAX_NODES_PING {
3374            let node = NodeRecord::new(local_addr, PeerId::random());
3375            if service.add_node(node) {
3376                num_inserted += 1;
3377                assert!(!service.pending_pings.contains_key(&node.id));
3378                assert_eq!(service.pending_pings.len(), MAX_NODES_PING - RESERVED_PINGS);
3379                assert_eq!(service.queued_pings.len(), num_inserted);
3380            }
3381        }
3382    }
3383
3384    #[tokio::test]
3385    async fn reserved_pings_admit_lookups() {
3386        let (_, mut service) = create_discv4().await;
3387        fill_unreserved_pings(&mut service);
3388
3389        let lookup = NodeRecord::new("127.0.0.2:30303".parse().unwrap(), PeerId::random());
3390        let ctx = LookupContext::new(kad_key(PeerId::random()), [], None);
3391        service.try_ping(lookup, PingReason::Lookup(lookup, ctx));
3392        assert!(service.pending_pings.contains_key(&lookup.id));
3393    }
3394
3395    #[tokio::test]
3396    async fn reserved_pings_admit_proven_renewals() {
3397        // The proven endpoint may be stored as IPv4-mapped IPv6.
3398        for stored in ["127.0.0.3:30303", "[::ffff:127.0.0.3]:30303"] {
3399            let (_, mut service) = create_discv4().await;
3400            let renewal = NodeRecord::new(stored.parse().unwrap(), PeerId::random());
3401            insert_proven_node(&mut service, renewal);
3402            fill_unreserved_pings(&mut service);
3403
3404            // Its node id at an endpoint it never proved gets no reserved slot.
3405            let other = NodeRecord::new("127.0.0.4:30303".parse().unwrap(), renewal.id);
3406            service.try_ping(other, PingReason::EstablishBond);
3407            assert!(!service.pending_pings.contains_key(&renewal.id));
3408
3409            // Its bond lapsed and it pings us from the endpoint it proved.
3410            service.received_pongs = PongTable::default();
3411            let ping = Ping {
3412                from: renewal.into(),
3413                to: service.local_node_record.into(),
3414                expire: service.ping_expiration(),
3415                enr_sq: None,
3416            };
3417            service.on_ping(ping, renewal.udp_addr(), renewal.id, B256::random());
3418            assert!(matches!(service.pending_pings[&renewal.id].reason, PingReason::EstablishBond));
3419        }
3420    }
3421
3422    #[tokio::test]
3423    async fn ping_buffered_keeps_unreserved_pings_queued() {
3424        let (_, mut service) = create_discv4().await;
3425        fill_unreserved_pings(&mut service);
3426        for _ in 0..2 {
3427            service.try_ping(rng_record(&mut rand::rng()), PingReason::InitialInsert);
3428        }
3429        let queued = service.queued_pings.iter().map(|(node, _)| node.id).collect::<Vec<_>>();
3430
3431        // Draining the queue sends a queued lookup and leaves the other pings queued in place.
3432        let lookup = NodeRecord::new("127.0.0.5:30303".parse().unwrap(), PeerId::random());
3433        let ctx = LookupContext::new(kad_key(PeerId::random()), [], None);
3434        service.queued_pings.insert(1, (lookup, PingReason::Lookup(lookup, ctx)));
3435        service.ping_buffered();
3436        assert!(service.pending_pings.contains_key(&lookup.id));
3437        assert_eq!(
3438            service.queued_pings.iter().map(|(node, _)| node.id).collect::<Vec<_>>(),
3439            queued
3440        );
3441    }
3442
3443    // Bootstraps with mainnet boot nodes
3444    #[tokio::test(flavor = "multi_thread")]
3445    #[ignore]
3446    async fn test_mainnet_lookup() {
3447        reth_tracing::init_test_tracing();
3448        let fork_id = ForkId { hash: ForkHash(hex!("743f3d89")), next: 16191202 };
3449
3450        let all_nodes = mainnet_nodes();
3451        let config = Discv4Config::builder()
3452            .add_boot_nodes(all_nodes)
3453            .lookup_interval(Duration::from_secs(1))
3454            .add_eip868_pair("eth", fork_id)
3455            .build();
3456        let (_discv4, mut service) = create_discv4_with_config(config).await;
3457
3458        let mut updates = service.update_stream();
3459
3460        let _handle = service.spawn();
3461
3462        let mut table = HashMap::new();
3463        while let Some(update) = updates.next().await {
3464            match update {
3465                DiscoveryUpdate::EnrForkId(record, fork_id) => {
3466                    println!("{record:?}, {fork_id:?}");
3467                }
3468                DiscoveryUpdate::Added(record) => {
3469                    table.insert(record.id, record);
3470                }
3471                DiscoveryUpdate::Removed(id) => {
3472                    table.remove(&id);
3473                }
3474                _ => {}
3475            }
3476            println!("total peers {}", table.len());
3477        }
3478    }
3479
3480    #[tokio::test]
3481    async fn test_mapped_ipv4() {
3482        reth_tracing::init_test_tracing();
3483        let mut rng = rand::rng();
3484        let config = Discv4Config::builder().build();
3485        let (_discv4, mut service) = create_discv4_with_config(config).await;
3486
3487        let v4: Ipv4Addr = "0.0.0.0".parse().unwrap();
3488        let v6 = v4.to_ipv6_mapped();
3489        let addr: SocketAddr = (v6, DEFAULT_DISCOVERY_PORT).into();
3490
3491        let ping = Ping {
3492            from: rng_endpoint(&mut rng),
3493            to: rng_endpoint(&mut rng),
3494            expire: service.ping_expiration(),
3495            enr_sq: Some(rng.random()),
3496        };
3497
3498        let id = PeerId::random();
3499        service.on_ping(ping, addr, id, B256::random());
3500
3501        let key = kad_key(id);
3502        match service.kbuckets.entry(&key) {
3503            kbucket::Entry::Present(entry, _) => {
3504                let node_addr = entry.value().record.address;
3505                assert!(node_addr.is_ipv4());
3506                assert_eq!(node_addr, IpAddr::from(v4));
3507            }
3508            _ => unreachable!(),
3509        };
3510    }
3511
3512    #[tokio::test]
3513    async fn test_respect_ping_expiration() {
3514        reth_tracing::init_test_tracing();
3515        let mut rng = rand::rng();
3516        let config = Discv4Config::builder().build();
3517        let (_discv4, mut service) = create_discv4_with_config(config).await;
3518
3519        let v4: Ipv4Addr = "0.0.0.0".parse().unwrap();
3520        let v6 = v4.to_ipv6_mapped();
3521        let addr: SocketAddr = (v6, DEFAULT_DISCOVERY_PORT).into();
3522
3523        let ping = Ping {
3524            from: rng_endpoint(&mut rng),
3525            to: rng_endpoint(&mut rng),
3526            expire: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() - 1,
3527            enr_sq: Some(rng.random()),
3528        };
3529
3530        let id = PeerId::random();
3531        service.on_ping(ping, addr, id, B256::random());
3532
3533        let key = kad_key(id);
3534        match service.kbuckets.entry(&key) {
3535            kbucket::Entry::Absent(_) => {}
3536            _ => unreachable!(),
3537        };
3538    }
3539
3540    #[tokio::test]
3541    async fn test_single_lookups() {
3542        reth_tracing::init_test_tracing();
3543
3544        let config = Discv4Config::builder().build();
3545        let (_discv4, mut service) = create_discv4_with_config(config.clone()).await;
3546
3547        let id = PeerId::random();
3548        let key = kad_key(id);
3549        let record = NodeRecord::new("0.0.0.0:0".parse().unwrap(), id);
3550
3551        let _ = service.kbuckets.insert_or_update(
3552            &key,
3553            NodeEntry::new_proven(record),
3554            NodeStatus {
3555                direction: ConnectionDirection::Incoming,
3556                state: ConnectionState::Connected,
3557            },
3558        );
3559
3560        service.lookup_self();
3561        assert_eq!(service.pending_find_nodes.len(), 1);
3562
3563        poll_fn(|cx| {
3564            let _ = service.poll(cx);
3565            assert_eq!(service.pending_find_nodes.len(), 1);
3566
3567            Poll::Ready(())
3568        })
3569        .await;
3570    }
3571
3572    #[tokio::test]
3573    async fn test_on_neighbours_recursive_lookup() {
3574        reth_tracing::init_test_tracing();
3575
3576        let config = Discv4Config::builder().build();
3577        let (_discv4, mut service) = create_discv4_with_config(config.clone()).await;
3578        let (_discv4, mut service2) = create_discv4_with_config(config).await;
3579
3580        let id = PeerId::random();
3581        let key = kad_key(id);
3582        let record = NodeRecord::new("0.0.0.0:0".parse().unwrap(), id);
3583
3584        let _ = service.kbuckets.insert_or_update(
3585            &key,
3586            NodeEntry::new_proven(record),
3587            NodeStatus {
3588                direction: ConnectionDirection::Incoming,
3589                state: ConnectionState::Connected,
3590            },
3591        );
3592        // Needed in this test to populate self.pending_find_nodes for as a prereq to a valid
3593        // on_neighbours request
3594        service.lookup_self();
3595        assert_eq!(service.pending_find_nodes.len(), 1);
3596
3597        poll_fn(|cx| {
3598            let _ = service.poll(cx);
3599            assert_eq!(service.pending_find_nodes.len(), 1);
3600
3601            Poll::Ready(())
3602        })
3603        .await;
3604
3605        let expiry = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs() +
3606            10000000000000;
3607        let msg = Neighbours { nodes: vec![service2.local_node_record], expire: expiry };
3608        service.on_neighbours(msg, record.tcp_addr(), id);
3609        // wait for the processed ping
3610        let event = poll_fn(|cx| service2.poll(cx)).await;
3611        assert_eq!(event, Discv4Event::Ping);
3612        // assert that no find_node req has been added here on top of the initial one, since both
3613        // sides of the endpoint proof is not completed here
3614        assert_eq!(service.pending_find_nodes.len(), 1);
3615        // we now wait for PONG
3616        let event = poll_fn(|cx| service.poll(cx)).await;
3617        assert_eq!(event, Discv4Event::Pong);
3618        // Ideally we want to assert against service.pending_lookup.len() here - but because the
3619        // service2 sends Pong and Ping consecutivley on_ping(), the pending_lookup table gets
3620        // drained almost immediately - and no way to grab the handle to its intermediary state here
3621        // :(
3622        let event = poll_fn(|cx| service.poll(cx)).await;
3623        assert_eq!(event, Discv4Event::Ping);
3624        // assert that we've added the find_node req here after both sides of the endpoint proof is
3625        // done
3626        assert_eq!(service.pending_find_nodes.len(), 2);
3627    }
3628
3629    #[tokio::test]
3630    async fn test_no_local_in_closest() {
3631        reth_tracing::init_test_tracing();
3632
3633        let config = Discv4Config::builder().build();
3634        let (_discv4, mut service) = create_discv4_with_config(config).await;
3635
3636        let target_key = kad_key(PeerId::random());
3637
3638        let id = PeerId::random();
3639        let key = kad_key(id);
3640        let record = NodeRecord::new("0.0.0.0:0".parse().unwrap(), id);
3641
3642        let _ = service.kbuckets.insert_or_update(
3643            &key,
3644            NodeEntry::new(record),
3645            NodeStatus {
3646                direction: ConnectionDirection::Incoming,
3647                state: ConnectionState::Connected,
3648            },
3649        );
3650
3651        let closest = service
3652            .kbuckets
3653            .closest_values(&target_key)
3654            .map(|n| n.value.record)
3655            .take(MAX_NODES_PER_BUCKET)
3656            .collect::<Vec<_>>();
3657
3658        assert_eq!(closest.len(), 1);
3659        assert!(!closest.iter().any(|r| r.id == *service.local_peer_id()));
3660    }
3661
3662    #[tokio::test]
3663    async fn test_random_lookup() {
3664        reth_tracing::init_test_tracing();
3665
3666        let config = Discv4Config::builder().build();
3667        let (_discv4, mut service) = create_discv4_with_config(config).await;
3668
3669        let target = PeerId::random();
3670
3671        let id = PeerId::random();
3672        let key = kad_key(id);
3673        let record = NodeRecord::new("0.0.0.0:0".parse().unwrap(), id);
3674
3675        let _ = service.kbuckets.insert_or_update(
3676            &key,
3677            NodeEntry::new_proven(record),
3678            NodeStatus {
3679                direction: ConnectionDirection::Incoming,
3680                state: ConnectionState::Connected,
3681            },
3682        );
3683
3684        service.lookup(target);
3685        assert_eq!(service.pending_find_nodes.len(), 1);
3686
3687        let ctx = service.pending_find_nodes.values().next().unwrap().lookup_context.clone();
3688
3689        assert_eq!(ctx.target(), target);
3690        assert_eq!(ctx.inner.closest_nodes.borrow().len(), 1);
3691
3692        ctx.add_node(record);
3693        assert_eq!(ctx.inner.closest_nodes.borrow().len(), 1);
3694    }
3695
3696    #[tokio::test]
3697    async fn test_reping_on_find_node_failures() {
3698        reth_tracing::init_test_tracing();
3699
3700        let config = Discv4Config::builder().build();
3701        let (_discv4, mut service) = create_discv4_with_config(config).await;
3702
3703        let target = PeerId::random();
3704
3705        let id = PeerId::random();
3706        let key = kad_key(id);
3707        let record = NodeRecord::new("0.0.0.0:0".parse().unwrap(), id);
3708
3709        let mut entry = NodeEntry::new_proven(record);
3710        entry.find_node_failures = u8::MAX;
3711        let _ = service.kbuckets.insert_or_update(
3712            &key,
3713            entry,
3714            NodeStatus {
3715                direction: ConnectionDirection::Incoming,
3716                state: ConnectionState::Connected,
3717            },
3718        );
3719
3720        service.lookup(target);
3721        assert_eq!(service.pending_find_nodes.len(), 0);
3722        assert_eq!(service.pending_pings.len(), 1);
3723
3724        service.update_on_pong(record, None);
3725
3726        service
3727            .on_entry(record.id, |entry| {
3728                // reset on pong
3729                assert_eq!(entry.find_node_failures, 0);
3730                assert!(entry.has_endpoint_proof);
3731            })
3732            .unwrap();
3733    }
3734
3735    #[tokio::test]
3736    async fn test_service_commands() {
3737        reth_tracing::init_test_tracing();
3738
3739        let config = Discv4Config::builder().build();
3740        let (discv4, mut service) = create_discv4_with_config(config).await;
3741
3742        service.lookup_self();
3743
3744        let _handle = service.spawn();
3745        discv4.send_lookup_self();
3746        let _ = discv4.lookup_self().await;
3747    }
3748
3749    #[tokio::test]
3750    async fn test_requests_timeout() {
3751        reth_tracing::init_test_tracing();
3752        let fork_id = ForkId { hash: ForkHash(hex!("743f3d89")), next: 16191202 };
3753
3754        let config = Discv4Config::builder()
3755            .request_timeout(Duration::from_millis(200))
3756            .ping_expiration(Duration::from_millis(200))
3757            .lookup_neighbours_expiration(Duration::from_millis(200))
3758            .add_eip868_pair("eth", fork_id)
3759            .build();
3760        let (_disv4, mut service) = create_discv4_with_config(config).await;
3761
3762        let id = PeerId::random();
3763        let key = kad_key(id);
3764        let record = NodeRecord::new("0.0.0.0:0".parse().unwrap(), id);
3765
3766        let _ = service.kbuckets.insert_or_update(
3767            &key,
3768            NodeEntry::new_proven(record),
3769            NodeStatus {
3770                direction: ConnectionDirection::Incoming,
3771                state: ConnectionState::Connected,
3772            },
3773        );
3774
3775        service.lookup_self();
3776        assert_eq!(service.pending_find_nodes.len(), 1);
3777
3778        let ctx = service.pending_find_nodes.values().next().unwrap().lookup_context.clone();
3779
3780        service.pending_lookup.insert(record.id, (Instant::now(), ctx));
3781
3782        assert_eq!(service.pending_lookup.len(), 1);
3783
3784        let ping = Ping {
3785            from: service.local_node_record.into(),
3786            to: record.into(),
3787            expire: service.ping_expiration(),
3788            enr_sq: service.enr_seq(),
3789        };
3790        let echo_hash = service.send_packet(Message::Ping(ping), record.udp_addr());
3791        let ping_request = PingRequest {
3792            sent_at: Instant::now(),
3793            node: record,
3794            echo_hash,
3795            reason: PingReason::InitialInsert,
3796        };
3797        service.pending_pings.insert(record.id, ping_request);
3798
3799        assert_eq!(service.pending_pings.len(), 1);
3800
3801        tokio::time::sleep(Duration::from_secs(1)).await;
3802
3803        poll_fn(|cx| {
3804            let _ = service.poll(cx);
3805
3806            assert_eq!(service.pending_find_nodes.len(), 0);
3807            assert_eq!(service.pending_lookup.len(), 0);
3808            assert_eq!(service.pending_pings.len(), 0);
3809
3810            Poll::Ready(())
3811        })
3812        .await;
3813    }
3814
3815    // sends a PING packet with wrong 'to' field and expects a PONG response.
3816    #[tokio::test(flavor = "multi_thread")]
3817    async fn test_check_wrong_to() {
3818        reth_tracing::init_test_tracing();
3819
3820        let config = Discv4Config::builder().external_ip_resolver(None).build();
3821        let (_discv4, mut service_1) = create_discv4_with_config(config.clone()).await;
3822        let (_discv4, mut service_2) = create_discv4_with_config(config).await;
3823
3824        // ping node 2 with wrong to field
3825        let mut ping = Ping {
3826            from: service_1.local_node_record.into(),
3827            to: service_2.local_node_record.into(),
3828            expire: service_1.ping_expiration(),
3829            enr_sq: service_1.enr_seq(),
3830        };
3831        ping.to.address = "192.0.2.0".parse().unwrap();
3832
3833        let echo_hash = service_1.send_packet(Message::Ping(ping), service_2.local_addr());
3834        let ping_request = PingRequest {
3835            sent_at: Instant::now(),
3836            node: service_2.local_node_record,
3837            echo_hash,
3838            reason: PingReason::InitialInsert,
3839        };
3840        service_1.pending_pings.insert(*service_2.local_peer_id(), ping_request);
3841
3842        // wait for the processed ping
3843        let event = poll_fn(|cx| service_2.poll(cx)).await;
3844        assert_eq!(event, Discv4Event::Ping);
3845
3846        // we now wait for PONG
3847        let event = poll_fn(|cx| service_1.poll(cx)).await;
3848        assert_eq!(event, Discv4Event::Pong);
3849        // followed by a ping
3850        let event = poll_fn(|cx| service_1.poll(cx)).await;
3851        assert_eq!(event, Discv4Event::Ping);
3852    }
3853
3854    #[tokio::test(flavor = "multi_thread")]
3855    async fn test_check_ping_pong() {
3856        reth_tracing::init_test_tracing();
3857
3858        let config = Discv4Config::builder().external_ip_resolver(None).build();
3859        let (_discv4, mut service_1) = create_discv4_with_config(config.clone()).await;
3860        let (_discv4, mut service_2) = create_discv4_with_config(config).await;
3861
3862        // send ping from 1 -> 2
3863        service_1.add_node(service_2.local_node_record);
3864
3865        // wait for the processed ping
3866        let event = poll_fn(|cx| service_2.poll(cx)).await;
3867        assert_eq!(event, Discv4Event::Ping);
3868
3869        // node is now in the table but not connected yet
3870        let key1 = kad_key(*service_1.local_peer_id());
3871        match service_2.kbuckets.entry(&key1) {
3872            kbucket::Entry::Present(_entry, status) => {
3873                assert!(!status.is_connected());
3874            }
3875            _ => unreachable!(),
3876        }
3877
3878        // we now wait for PONG
3879        let event = poll_fn(|cx| service_1.poll(cx)).await;
3880        assert_eq!(event, Discv4Event::Pong);
3881
3882        // endpoint is proven
3883        let key2 = kad_key(*service_2.local_peer_id());
3884        match service_1.kbuckets.entry(&key2) {
3885            kbucket::Entry::Present(_entry, status) => {
3886                assert!(status.is_connected());
3887            }
3888            _ => unreachable!(),
3889        }
3890
3891        // we now wait for the PING initiated by 2
3892        let event = poll_fn(|cx| service_1.poll(cx)).await;
3893        assert_eq!(event, Discv4Event::Ping);
3894
3895        // Drain events from service_2 until we see the Pong. Intermediate EnrRequest and
3896        // FindNode events are expected: ENR requests come from the ping handshake, and FindNode
3897        // arrives because service_1 resets its lookup interval on the first bootnode pong.
3898        tokio::time::timeout(Duration::from_secs(5), async {
3899            loop {
3900                let event = poll_fn(|cx| service_2.poll(cx)).await;
3901                match event {
3902                    Discv4Event::Pong => break,
3903                    Discv4Event::EnrRequest | Discv4Event::FindNode => {}
3904                    ev => unreachable!("{ev:?}"),
3905                }
3906            }
3907        })
3908        .await
3909        .expect("timed out waiting for Pong from service_2");
3910
3911        // endpoint is proven
3912        match service_2.kbuckets.entry(&key1) {
3913            kbucket::Entry::Present(_entry, status) => {
3914                assert!(status.is_connected());
3915            }
3916            ev => unreachable!("{ev:?}"),
3917        }
3918    }
3919
3920    #[test]
3921    fn test_insert() {
3922        let local_node_record = rng_record(&mut rand::rng());
3923        let mut kbuckets: KBucketsTable<NodeKey, NodeEntry> = KBucketsTable::new(
3924            NodeKey::from(&local_node_record).into(),
3925            Duration::from_secs(60),
3926            MAX_NODES_PER_BUCKET,
3927            None,
3928            None,
3929        );
3930
3931        let new_record = rng_record(&mut rand::rng());
3932        let key = kad_key(new_record.id);
3933        match kbuckets.entry(&key) {
3934            kbucket::Entry::Absent(entry) => {
3935                let node = NodeEntry::new(new_record);
3936                let _ = entry.insert(
3937                    node,
3938                    NodeStatus {
3939                        direction: ConnectionDirection::Outgoing,
3940                        state: ConnectionState::Disconnected,
3941                    },
3942                );
3943            }
3944            _ => {
3945                unreachable!()
3946            }
3947        };
3948        match kbuckets.entry(&key) {
3949            kbucket::Entry::Present(_, _) => {}
3950            _ => {
3951                unreachable!()
3952            }
3953        }
3954    }
3955
3956    #[tokio::test]
3957    async fn test_bootnode_in_update_stream() {
3958        reth_tracing::init_test_tracing();
3959        let (_, service_1) = create_discv4().await;
3960        let peerid_1 = *service_1.local_peer_id();
3961
3962        let config = Discv4Config::builder().add_boot_node(service_1.local_node_record).build();
3963        service_1.spawn();
3964
3965        let (_, mut service_2) = create_discv4_with_config(config).await;
3966
3967        let mut updates = service_2.update_stream();
3968
3969        service_2.spawn();
3970
3971        // Poll for events for a reasonable time
3972        let mut bootnode_appeared = false;
3973        let timeout = tokio::time::sleep(Duration::from_secs(1));
3974        tokio::pin!(timeout);
3975
3976        loop {
3977            tokio::select! {
3978                Some(update) = updates.next() => {
3979                    if let DiscoveryUpdate::Added(record) = update
3980                        && record.id == peerid_1 {
3981                            bootnode_appeared = true;
3982                            break;
3983                        }
3984                }
3985                _ = &mut timeout => break,
3986            }
3987        }
3988
3989        assert!(bootnode_appeared, "Bootnode should appear in update stream");
3990    }
3991
3992    fn insert_proven_node(service: &mut Discv4Service, record: NodeRecord) {
3993        service.received_pongs.on_pong(record.id, record.address);
3994        let key = kad_key(record.id);
3995        let _ = service.kbuckets.insert_or_update(
3996            &key,
3997            NodeEntry::new_proven(record),
3998            NodeStatus {
3999                direction: ConnectionDirection::Incoming,
4000                state: ConnectionState::Connected,
4001            },
4002        );
4003    }
4004
4005    fn insert_initial_ping(service: &mut Discv4Service, record: NodeRecord) -> B256 {
4006        let echo_hash = B256::random();
4007        service.pending_pings.insert(
4008            record.id,
4009            PingRequest {
4010                sent_at: Instant::now(),
4011                node: record,
4012                echo_hash,
4013                reason: PingReason::InitialInsert,
4014            },
4015        );
4016        echo_hash
4017    }
4018
4019    fn make_pong(service: &Discv4Service, echo_hash: B256) -> Pong {
4020        Pong {
4021            to: rng_endpoint(&mut rand::rng()),
4022            echo: echo_hash,
4023            expire: service.ping_expiration(),
4024            enr_sq: None,
4025        }
4026    }
4027
4028    #[tokio::test]
4029    async fn test_pong_from_unpinged_ip_does_not_establish_bond() {
4030        let (_discv4, mut service) = create_discv4().await;
4031        let record = NodeRecord::new("127.0.0.1:30303".parse().unwrap(), PeerId::random());
4032        let echo_hash = insert_initial_ping(&mut service, record);
4033        let unexpected_addr = "127.0.0.2:30303".parse().unwrap();
4034
4035        service.on_pong(make_pong(&service, echo_hash), unexpected_addr, record.id);
4036
4037        assert!(service.pending_pings.contains_key(&record.id));
4038        assert!(!service.has_bond(record.id, unexpected_addr.ip()));
4039
4040        let expected_addr = SocketAddr::from((Ipv4Addr::LOCALHOST.to_ipv6_mapped(), 30304));
4041        service.on_pong(make_pong(&service, echo_hash), expected_addr, record.id);
4042
4043        assert!(!service.pending_pings.contains_key(&record.id));
4044        assert!(service.has_bond(record.id, expected_addr.ip()));
4045    }
4046
4047    #[tokio::test]
4048    async fn test_ping_at_capacity_announced_after_pong() {
4049        let (_discv4, mut service) = create_discv4().await;
4050        let (egress, mut packets) = mpsc::channel(16);
4051        service.egress = egress;
4052        let mut updates = service.update_stream().into_inner();
4053        let record =
4054            NodeRecord::new("10.1.0.1:30303".parse().unwrap(), full_bucket_peer(&mut service));
4055        let ping = Ping {
4056            from: record.into(),
4057            to: service.local_node_record.into(),
4058            expire: service.ping_expiration(),
4059            enr_sq: Some(1),
4060        };
4061
4062        service.on_ping(ping.clone(), record.udp_addr(), record.id, B256::random());
4063        assert!(updates.try_recv().is_err());
4064        let (packet, _) = packets.try_recv().unwrap();
4065        assert!(matches!(Message::decode(&packet).unwrap().msg, Message::Pong(_)));
4066        let (packet, _) = packets.try_recv().unwrap();
4067        assert!(matches!(Message::decode(&packet).unwrap().msg, Message::Ping(_)));
4068        assert!(!service.pending_enr_requests.contains_key(&record.id));
4069        let request = &service.pending_pings[&record.id];
4070        assert!(matches!(request.reason, PingReason::AtCapacity));
4071        let echo_hash = request.echo_hash;
4072
4073        service.on_pong(make_pong(&service, echo_hash), record.udp_addr(), record.id);
4074        assert!(matches!(
4075            updates.try_recv(),
4076            Ok(DiscoveryUpdate::DiscoveredAtCapacity(announced)) if announced == record
4077        ));
4078
4079        // Once bonded, the node is announced right away.
4080        service.on_ping(ping, record.udp_addr(), record.id, B256::random());
4081        assert!(matches!(
4082            updates.try_recv(),
4083            Ok(DiscoveryUpdate::DiscoveredAtCapacity(announced)) if announced == record
4084        ));
4085    }
4086
4087    #[tokio::test]
4088    async fn test_at_capacity_pong_proves_node_inserted_meanwhile() {
4089        let (_discv4, mut service) = create_discv4().await;
4090        let record =
4091            NodeRecord::new("10.1.0.1:30303".parse().unwrap(), full_bucket_peer(&mut service));
4092        let ping = Ping {
4093            from: record.into(),
4094            to: service.local_node_record.into(),
4095            expire: service.ping_expiration(),
4096            enr_sq: None,
4097        };
4098        service.on_ping(ping.clone(), record.udp_addr(), record.id, B256::random());
4099        let echo_hash = service.pending_pings[&record.id].echo_hash;
4100
4101        // The next ping inserts the node, and the pending ping stands in for its initial ping.
4102        free_farthest_bucket_slot(&mut service);
4103        service.on_ping(ping, record.udp_addr(), record.id, B256::random());
4104        assert_eq!(service.on_entry(record.id, |entry| entry.has_endpoint_proof), Some(false));
4105
4106        service.on_pong(make_pong(&service, echo_hash), record.udp_addr(), record.id);
4107        assert_eq!(service.on_entry(record.id, |entry| entry.has_endpoint_proof), Some(true));
4108    }
4109
4110    #[tokio::test]
4111    async fn test_failed_ping_to_other_endpoint_revalidates_proven_node() {
4112        let (_discv4, mut service) = create_discv4().await;
4113        let expired = Instant::now() + service.config.ping_expiration * 2;
4114
4115        // Neither another IP nor another UDP port on the stored IP is the stored endpoint.
4116        for other in ["127.0.0.2:30303", "127.0.0.1:30304"] {
4117            let record = NodeRecord::new("127.0.0.1:30303".parse().unwrap(), PeerId::random());
4118            insert_proven_node(&mut service, record);
4119            let other = NodeRecord::new(other.parse().unwrap(), record.id);
4120            service.send_ping(other, PingReason::EstablishBond);
4121            service.evict_expired_requests(expired);
4122
4123            assert!(service.on_entry(record.id, |_| ()).is_some());
4124            let request = &service.pending_pings[&record.id];
4125            assert_eq!(request.node, record);
4126            assert!(matches!(request.reason, PingReason::RePing));
4127
4128            // The stored endpoint does not pong either.
4129            service.evict_expired_requests(expired);
4130            assert!(service.on_entry(record.id, |_| ()).is_none());
4131        }
4132    }
4133
4134    #[tokio::test]
4135    async fn test_failed_ping_to_other_endpoint_evicts_unproven_node() {
4136        let (_discv4, mut service) = create_discv4().await;
4137        let record = NodeRecord::new("127.0.0.1:30303".parse().unwrap(), PeerId::random());
4138        let other = NodeRecord::new("127.0.0.2:30303".parse().unwrap(), record.id);
4139
4140        // The pending ping to the other endpoint drops the initial ping to the new entry.
4141        service.send_ping(other, PingReason::EstablishBond);
4142        assert!(service.add_node(record));
4143        assert_eq!(service.pending_pings[&record.id].node, other);
4144
4145        service.evict_expired_requests(Instant::now() + service.config.ping_expiration * 2);
4146        assert!(service.on_entry(record.id, |_| ()).is_none());
4147    }
4148
4149    #[tokio::test]
4150    async fn test_find_node_timeout_counts_only_at_stored_address() {
4151        let (_discv4, mut service) = create_discv4().await;
4152        let record = NodeRecord::new("127.0.0.1:30303".parse().unwrap(), PeerId::random());
4153        insert_proven_node(&mut service, record);
4154        let other = NodeRecord::new("127.0.0.2:30303".parse().unwrap(), record.id);
4155        let ctx = LookupContext::new(kad_key(PeerId::random()), [], None);
4156        let expired = Instant::now() + service.config.neighbours_expiration * 2;
4157
4158        for (destination, failures) in [(other, 0), (record, 1)] {
4159            service.find_node(&destination, ctx.clone());
4160            service.evict_failed_find_nodes(expired);
4161            assert_eq!(
4162                service.on_entry(record.id, |entry| entry.find_node_failures),
4163                Some(failures)
4164            );
4165        }
4166    }
4167
4168    #[tokio::test]
4169    async fn test_lookup_reset_on_first_bootnode_pong() {
4170        let record = NodeRecord::new("0.0.0.0:0".parse().unwrap(), PeerId::random());
4171        let config = Discv4Config::builder().add_boot_node(record).build();
4172        let (_discv4, mut service) = create_discv4_with_config(config).await;
4173
4174        // 1. initial state
4175        assert!(service.pending_lookup_reset);
4176
4177        // 2. setup: proven bootnode + pending InitialInsert ping
4178        insert_proven_node(&mut service, record);
4179        let echo_hash = insert_initial_ping(&mut service, record);
4180
4181        // 3. input: pong arrives
4182        service.on_pong(make_pong(&service, echo_hash), record.udp_addr(), record.id);
4183
4184        // 4. flag should be consumed — interval was reset
4185        assert!(!service.pending_lookup_reset, "flag should be consumed");
4186    }
4187
4188    #[tokio::test]
4189    async fn test_lookup_reset_fires_only_once() {
4190        let records: Vec<_> = (0..2)
4191            .map(|_| NodeRecord::new("0.0.0.0:0".parse().unwrap(), PeerId::random()))
4192            .collect();
4193        let config = Discv4Config::builder().add_boot_nodes(records.clone()).build();
4194        let (_discv4, mut service) = create_discv4_with_config(config).await;
4195
4196        // 1. setup: two proven bootnodes with pending InitialInsert pings
4197        for &r in &records {
4198            insert_proven_node(&mut service, r);
4199        }
4200        let hashes: Vec<_> =
4201            records.iter().map(|r| insert_initial_ping(&mut service, *r)).collect();
4202
4203        // 2. first pong -> consumes the flag (resets the interval)
4204        service.on_pong(make_pong(&service, hashes[0]), records[0].udp_addr(), records[0].id);
4205        assert!(!service.pending_lookup_reset);
4206
4207        // 3. second pong -> flag already consumed, no second reset
4208        service.on_pong(make_pong(&service, hashes[1]), records[1].udp_addr(), records[1].id);
4209        assert!(!service.pending_lookup_reset);
4210    }
4211
4212    #[tokio::test]
4213    async fn test_lookup_reset_not_triggered_by_non_bootnode() {
4214        let bootnode = NodeRecord::new("0.0.0.0:0".parse().unwrap(), PeerId::random());
4215        let config = Discv4Config::builder().add_boot_node(bootnode).build();
4216        let (_discv4, mut service) = create_discv4_with_config(config).await;
4217
4218        assert!(service.pending_lookup_reset);
4219
4220        // a non-bootnode pong should not consume the flag
4221        let stranger = NodeRecord::new("0.0.0.0:0".parse().unwrap(), PeerId::random());
4222        insert_proven_node(&mut service, stranger);
4223        let echo_hash = insert_initial_ping(&mut service, stranger);
4224        service.on_pong(make_pong(&service, echo_hash), stranger.udp_addr(), stranger.id);
4225
4226        assert!(service.pending_lookup_reset, "flag should not be consumed by non-bootnode");
4227    }
4228
4229    #[tokio::test]
4230    async fn test_lookup_reset_disabled_when_lookup_disabled() {
4231        let config = Discv4Config::builder().enable_lookup(false).build();
4232        let (_discv4, service) = create_discv4_with_config(config).await;
4233
4234        // flag should be false when lookups are disabled
4235        assert!(!service.pending_lookup_reset);
4236    }
4237
4238    #[tokio::test]
4239    async fn test_enr_response_preserves_pending_request() {
4240        let fork_id = ForkId { hash: ForkHash([1, 2, 3, 4]), next: 0 };
4241        let mut config = Discv4Config::default();
4242        config.add_eip868_pair("eth", EnrForkIdEntry::from(fork_id));
4243        let (_remote, mut remote) = create_discv4_with_config(config).await;
4244        let (_discv4, mut service) = create_discv4().await;
4245        let record = remote.local_node_record;
4246        let id = record.id;
4247        let addr = record.udp_addr();
4248        insert_proven_node(&mut service, record);
4249        service.update_on_reping(record, remote.enr_seq());
4250        let old_enr = remote.local_eip_868_enr.clone();
4251
4252        // Model a request sent in the previous second without waiting for the wall clock.
4253        let (_, old_hash) =
4254            Message::EnrRequest(EnrRequest { expire: service.enr_request_expiration() - 1 })
4255                .encode(&service.secret_key);
4256        service.pending_enr_requests.get_mut(&id).unwrap().echo_hash = old_hash;
4257
4258        // A newer sequence replaces the pending request before its response arrives.
4259        remote.local_eip_868_enr.set_tcp4(30304, &remote.secret_key).unwrap();
4260        service.on_ping(
4261            Ping {
4262                from: record.into(),
4263                to: service.local_node_record.into(),
4264                expire: service.ping_expiration(),
4265                enr_sq: remote.enr_seq(),
4266            },
4267            addr,
4268            id,
4269            B256::random(),
4270        );
4271        let request_hash = service.pending_enr_requests[&id].echo_hash;
4272        assert_ne!(request_hash, old_hash);
4273
4274        service.on_enr_response(EnrResponse { request_hash: old_hash, enr: old_enr }, addr, id);
4275        assert_eq!(service.pending_enr_requests[&id].echo_hash, request_hash);
4276        assert_eq!(service.on_entry(id, |entry| entry.fork_id), Some(None));
4277
4278        // A response with the right hash but a different node identity is also ignored.
4279        service.on_enr_response(
4280            EnrResponse { request_hash, enr: service.local_eip_868_enr.clone() },
4281            addr,
4282            id,
4283        );
4284        assert_eq!(service.pending_enr_requests[&id].echo_hash, request_hash);
4285        assert_eq!(service.on_entry(id, |entry| entry.fork_id), Some(None));
4286
4287        let mut updates = service.update_stream().into_inner();
4288        service.on_enr_response(
4289            EnrResponse { request_hash, enr: remote.local_eip_868_enr.clone() },
4290            addr,
4291            id,
4292        );
4293        assert!(!service.pending_enr_requests.contains_key(&id));
4294        assert_eq!(service.on_entry(id, |entry| entry.fork_id), Some(Some(fork_id)));
4295        assert_matches::assert_matches!(
4296            updates.try_recv().unwrap(),
4297            DiscoveryUpdate::EnrForkId(found_record, found_fork_id) => {
4298                assert_eq!(found_record, record);
4299                assert_eq!(found_fork_id, fork_id);
4300            }
4301        );
4302    }
4303
4304    /// Sets up a service with a pending `FindNode` request to a proven node at `node_addr`.
4305    async fn pending_find_node_service(node_addr: SocketAddr) -> (Discv4Service, NodeRecord) {
4306        let (_discv4, mut service) = create_discv4().await;
4307
4308        let id = PeerId::random();
4309        let record = NodeRecord::new(node_addr, id);
4310        let _ = service.kbuckets.insert_or_update(
4311            &kad_key(id),
4312            NodeEntry::new_proven(record),
4313            NodeStatus {
4314                direction: ConnectionDirection::Incoming,
4315                state: ConnectionState::Connected,
4316            },
4317        );
4318
4319        service.lookup(PeerId::random());
4320        assert_eq!(service.pending_find_nodes.len(), 1);
4321        (service, record)
4322    }
4323
4324    #[tokio::test]
4325    async fn test_neighbours_from_unexpected_ip_ignored() {
4326        reth_tracing::init_test_tracing();
4327
4328        let node_addr = SocketAddr::from(([10, 0, 0, 1], 30303));
4329        let (mut service, record) = pending_find_node_service(node_addr).await;
4330        let ctx = service.pending_find_nodes[&record.id].lookup_context.clone();
4331        let lookup_nodes = ctx.inner.closest_nodes.borrow().len();
4332
4333        let expire = service.find_node_expiration() + 1000;
4334        let discovered =
4335            NodeRecord::new(SocketAddr::from(([10, 0, 0, 9], 30303)), PeerId::random());
4336        let msg = Neighbours { nodes: vec![discovered], expire };
4337
4338        // A validly signed packet from the queried node's id but from another IP is ignored, even
4339        // if only the port or the address family differs.
4340        for spoofed in [
4341            SocketAddr::from(([10, 0, 0, 2], 30303)),
4342            SocketAddr::from(([10, 0, 0, 2], 1)),
4343            SocketAddr::from((Ipv4Addr::new(10, 0, 0, 2).to_ipv6_mapped(), 30303)),
4344            SocketAddr::from(([0, 0, 0, 0, 0, 0, 0, 1], 30303)),
4345        ] {
4346            service.on_neighbours(msg.clone(), spoofed, record.id);
4347
4348            let request = &service.pending_find_nodes[&record.id];
4349            assert!(!request.answered);
4350            assert_eq!(request.response_count, 0);
4351            assert_eq!(ctx.inner.closest_nodes.borrow().len(), lookup_nodes);
4352            assert!(service.pending_pings.is_empty());
4353        }
4354
4355        // The genuine reply from the queried IP is still accepted, regardless of the port.
4356        service.on_neighbours(msg, SocketAddr::from(([10, 0, 0, 1], 40404)), record.id);
4357        let request = &service.pending_find_nodes[&record.id];
4358        assert!(request.answered);
4359        assert_eq!(request.response_count, 1);
4360        assert_eq!(ctx.inner.closest_nodes.borrow().len(), lookup_nodes + 1);
4361    }
4362
4363    #[tokio::test]
4364    async fn test_neighbours_at_capacity_announced_after_pong() {
4365        let node_addr = SocketAddr::from(([10, 0, 0, 1], 30303));
4366        let (mut service, record) = pending_find_node_service(node_addr).await;
4367        let mut updates = service.update_stream().into_inner();
4368        let discovered = NodeRecord::new(
4369            SocketAddr::from(([10, 0, 0, 9], 30303)),
4370            full_bucket_peer(&mut service),
4371        );
4372
4373        let msg =
4374            Neighbours { nodes: vec![discovered], expire: service.find_node_expiration() + 1000 };
4375        service.on_neighbours(msg, node_addr, record.id);
4376        assert!(updates.try_recv().is_err());
4377        let request = &service.pending_pings[&discovered.id];
4378        assert!(matches!(request.reason, PingReason::AtCapacity));
4379
4380        service.on_pong(
4381            make_pong(&service, request.echo_hash),
4382            discovered.udp_addr(),
4383            discovered.id,
4384        );
4385        assert!(matches!(
4386            updates.try_recv(),
4387            Ok(DiscoveryUpdate::DiscoveredAtCapacity(announced)) if announced == discovered
4388        ));
4389    }
4390
4391    #[tokio::test]
4392    async fn test_neighbours_at_capacity_ping_timeout_keeps_node() {
4393        let node_addr = SocketAddr::from(([10, 0, 0, 1], 30303));
4394        let (mut service, record) = pending_find_node_service(node_addr).await;
4395        let id = full_bucket_peer(&mut service);
4396        let referral = NodeRecord::new(SocketAddr::from(([10, 0, 0, 9], 30303)), id);
4397        let msg =
4398            Neighbours { nodes: vec![referral], expire: service.find_node_expiration() + 1000 };
4399        service.on_neighbours(msg, node_addr, record.id);
4400        assert!(matches!(service.pending_pings[&id].reason, PingReason::AtCapacity));
4401
4402        // The node itself is inserted from another endpoint while the referral ping is pending.
4403        free_farthest_bucket_slot(&mut service);
4404        let node = NodeRecord::new(SocketAddr::from(([10, 0, 0, 50], 30303)), id);
4405        let ping = Ping {
4406            from: node.into(),
4407            to: service.local_node_record.into(),
4408            expire: service.ping_expiration(),
4409            enr_sq: None,
4410        };
4411        service.on_ping(ping, node.udp_addr(), id, B256::random());
4412        assert!(service.on_entry(id, |_| ()).is_some());
4413
4414        service.evict_expired_requests(Instant::now() + service.config.ping_expiration * 2);
4415        assert!(!service.pending_pings.contains_key(&id));
4416        assert!(service.on_entry(id, |_| ()).is_some());
4417    }
4418
4419    #[tokio::test]
4420    async fn test_at_capacity_pong_does_not_prove_node_at_other_endpoint() {
4421        let node_addr = SocketAddr::from(([10, 0, 0, 1], 30303));
4422        let (mut service, record) = pending_find_node_service(node_addr).await;
4423        let pinged = NodeRecord::new(
4424            SocketAddr::from(([10, 0, 0, 50], 30303)),
4425            full_bucket_peer(&mut service),
4426        );
4427        let ping = Ping {
4428            from: pinged.into(),
4429            to: service.local_node_record.into(),
4430            expire: service.ping_expiration(),
4431            enr_sq: None,
4432        };
4433        service.on_ping(ping, pinged.udp_addr(), pinged.id, B256::random());
4434        let echo_hash = service.pending_pings[&pinged.id].echo_hash;
4435
4436        // A referral inserts the node at another endpoint while the ping is pending.
4437        free_farthest_bucket_slot(&mut service);
4438        let referral = NodeRecord::new(SocketAddr::from(([10, 0, 0, 9], 30303)), pinged.id);
4439        let msg =
4440            Neighbours { nodes: vec![referral], expire: service.find_node_expiration() + 1000 };
4441        service.on_neighbours(msg, node_addr, record.id);
4442        assert_eq!(service.pending_pings[&pinged.id].node, pinged);
4443
4444        service.on_pong(make_pong(&service, echo_hash), pinged.udp_addr(), pinged.id);
4445        assert_eq!(service.on_entry(pinged.id, |entry| entry.has_endpoint_proof), Some(false));
4446        let request = &service.pending_pings[&pinged.id];
4447        assert_eq!(request.node, referral);
4448        assert!(matches!(request.reason, PingReason::InitialInsert));
4449    }
4450
4451    #[tokio::test]
4452    async fn test_at_capacity_pong_announces_stored_record() {
4453        let node_addr = SocketAddr::from(([10, 0, 0, 1], 30303));
4454        let (mut service, record) = pending_find_node_service(node_addr).await;
4455        let endpoint = SocketAddr::from(([10, 0, 0, 9], 30303));
4456        let referral =
4457            NodeRecord { tcp_port: 0, ..NodeRecord::new(endpoint, full_bucket_peer(&mut service)) };
4458        let msg =
4459            Neighbours { nodes: vec![referral], expire: service.find_node_expiration() + 1000 };
4460        service.on_neighbours(msg, node_addr, record.id);
4461        let echo_hash = service.pending_pings[&referral.id].echo_hash;
4462
4463        // The node pings from the referral's endpoint and is inserted with its own TCP port.
4464        free_farthest_bucket_slot(&mut service);
4465        let node = NodeRecord::new(endpoint, referral.id);
4466        let ping = Ping {
4467            from: node.into(),
4468            to: service.local_node_record.into(),
4469            expire: service.ping_expiration(),
4470            enr_sq: None,
4471        };
4472        service.on_ping(ping, endpoint, node.id, B256::random());
4473
4474        let mut updates = service.update_stream().into_inner();
4475        service.on_pong(make_pong(&service, echo_hash), endpoint, node.id);
4476        let added =
4477            std::iter::from_fn(|| updates.try_recv().ok()).find_map(|update| match update {
4478                DiscoveryUpdate::Added(record) => Some(record),
4479                _ => None,
4480            });
4481        assert_eq!(added, Some(node));
4482    }
4483
4484    #[tokio::test]
4485    async fn test_neighbours_ipv4_mapped_ip_accepted() {
4486        reth_tracing::init_test_tracing();
4487
4488        // A dual-stack socket reports IPv4 peers as IPv4-mapped IPv6 addresses.
4489        let node_addr = SocketAddr::from(([10, 0, 0, 1], 30303));
4490        let (mut service, record) = pending_find_node_service(node_addr).await;
4491
4492        let expire = service.find_node_expiration() + 1000;
4493        let msg = Neighbours { nodes: Vec::new(), expire };
4494        let mapped = SocketAddr::from((Ipv4Addr::new(10, 0, 0, 1).to_ipv6_mapped(), 30303));
4495        service.on_neighbours(msg, mapped, record.id);
4496
4497        let request = &service.pending_find_nodes[&record.id];
4498        assert!(request.answered);
4499    }
4500
4501    #[tokio::test]
4502    async fn test_neighbours_wrong_ip_replay_does_not_poison_cache() {
4503        let (_discv4, mut service) = create_discv4().await;
4504        let remote_key = SecretKey::new(&mut rand::rng());
4505        let node_addr = SocketAddr::from(([10, 0, 0, 1], 30303));
4506        let record = NodeRecord::from_secret_key(node_addr, &remote_key);
4507        insert_proven_node(&mut service, record);
4508        service.lookup(PeerId::random());
4509        assert_eq!(service.pending_find_nodes.len(), 1);
4510
4511        let ctx = service.pending_find_nodes[&record.id].lookup_context.clone();
4512        let lookup_nodes = ctx.inner.closest_nodes.borrow().len();
4513        let discovered =
4514            NodeRecord::new(SocketAddr::from(([10, 0, 0, 9], 30303)), PeerId::random());
4515        let msg = Message::Neighbours(Neighbours {
4516            nodes: vec![discovered],
4517            expire: service.find_node_expiration(),
4518        });
4519        let (packet, _) = msg.encode(&remote_key);
4520        let (tx, mut rx) = mpsc::channel(16);
4521        let mut handler = IngressHandler::new(tx, *service.local_peer_id());
4522
4523        // A valid replay from another IP must not consume the request or suppress its reply.
4524        handler.handle_packet(&packet, SocketAddr::from(([10, 0, 0, 2], 30303))).await;
4525        let IngressEvent::Packet(src, Packet { msg: Message::Neighbours(msg), node_id, .. }) =
4526            rx.try_recv().unwrap()
4527        else {
4528            panic!("expected a decoded Neighbours packet");
4529        };
4530        service.on_neighbours(msg, src, node_id);
4531        let request = &service.pending_find_nodes[&record.id];
4532        assert!(!request.answered);
4533        assert_eq!(request.response_count, 0);
4534        assert_eq!(ctx.inner.closest_nodes.borrow().len(), lookup_nodes);
4535        assert!(service.pending_pings.is_empty());
4536
4537        // The identical signed packet from the queried IP must still reach the service.
4538        handler.handle_packet(&packet, node_addr).await;
4539        let IngressEvent::Packet(src, Packet { msg: Message::Neighbours(msg), node_id, .. }) =
4540            rx.try_recv().expect("genuine reply was suppressed by the wrong-IP replay")
4541        else {
4542            panic!("expected a decoded Neighbours packet");
4543        };
4544        service.on_neighbours(msg, src, node_id);
4545        let request = &service.pending_find_nodes[&record.id];
4546        assert!(request.answered);
4547        assert_eq!(request.response_count, 1);
4548        assert_eq!(ctx.inner.closest_nodes.borrow().len(), lookup_nodes + 1);
4549
4550        // A port change or mapped address must not bypass deduplication for the same IP.
4551        let mapped = SocketAddr::from((Ipv4Addr::new(10, 0, 0, 1).to_ipv6_mapped(), 40404));
4552        handler.handle_packet(&packet, mapped).await;
4553        assert_matches::assert_matches!(rx.try_recv(), Err(mpsc::error::TryRecvError::Empty));
4554    }
4555
4556    #[tokio::test]
4557    async fn test_ban_until_is_evicted() {
4558        let permanent_ip: IpAddr = [1, 1, 1, 1].into();
4559        let expired_ip: IpAddr = [2, 2, 2, 2].into();
4560        let expired_peer_ip: IpAddr = [3, 3, 3, 3].into();
4561        let active_ip: IpAddr = [4, 4, 4, 4].into();
4562        let active_peer_ip: IpAddr = [5, 5, 5, 5].into();
4563        let expired_peer = PeerId::random();
4564        let active_peer = PeerId::random();
4565
4566        let config = Discv4Config::builder().ban_list(BanList::new([], [permanent_ip])).build();
4567        let (discv4, mut service) = create_discv4_with_config(config).await;
4568
4569        let expired = Instant::now() - Duration::from_millis(1);
4570        discv4.ban_ip_until(permanent_ip, expired);
4571        discv4.ban_ip_until(expired_ip, expired);
4572        discv4.ban_until(expired_peer, expired_peer_ip, expired);
4573        let active = Instant::now() + Duration::from_secs(3600);
4574        discv4.ban_ip_until(active_ip, active);
4575        discv4.ban_until(active_peer, active_peer_ip, active);
4576
4577        // Drains the commands, then waits for the first expire interval tick to evict.
4578        tokio::time::timeout(
4579            Duration::from_secs(5),
4580            poll_fn(|cx| {
4581                while service.poll(cx).is_ready() {}
4582                if service.config.ban_list.is_banned_ip(&expired_ip) {
4583                    Poll::Pending
4584                } else {
4585                    Poll::Ready(())
4586                }
4587            }),
4588        )
4589        .await
4590        .expect("expired ban was not evicted");
4591
4592        let bans = &service.config.ban_list;
4593        assert!(bans.is_banned_ip(&permanent_ip));
4594        assert!(bans.is_banned_ip(&active_ip));
4595        assert!(bans.is_banned_ip(&active_peer_ip));
4596        assert!(bans.is_banned_peer(&active_peer));
4597        assert!(!bans.is_banned_ip(&expired_ip));
4598        assert!(!bans.is_banned_ip(&expired_peer_ip));
4599        assert!(!bans.is_banned_peer(&expired_peer));
4600    }
4601}