reth_discv4/
table.rs

1//! Additional support for tracking nodes.
2
3use reth_network_peers::PeerId;
4use std::{collections::HashMap, net::IpAddr, time::Instant};
5
6/// Keeps track of nodes from which we have received a `Pong` message.
7#[derive(Debug, Clone, Default)]
8pub(crate) struct PongTable {
9    /// The nodes we have received a `Pong` from.
10    nodes: HashMap<NodeKey, Instant>,
11}
12
13impl PongTable {
14    /// Updates the timestamp we received a `Pong` from the given node.
15    pub(crate) fn on_pong(&mut self, remote_id: PeerId, remote_ip: IpAddr) {
16        let key = NodeKey { remote_id, remote_ip };
17        self.nodes.insert(key, Instant::now());
18    }
19
20    /// Returns the timestamp we received a `Pong` from the given node.
21    pub(crate) fn last_pong(&self, remote_id: PeerId, remote_ip: IpAddr) -> Option<Instant> {
22        self.nodes.get(&NodeKey { remote_id, remote_ip }).copied()
23    }
24
25    /// Removes all nodes from the table that have not sent a `Pong` for at least `timeout`.
26    pub(crate) fn evict_expired(&mut self, now: Instant, timeout: std::time::Duration) {
27        self.nodes.retain(|_, last_pong| now - *last_pong < timeout);
28    }
29}
30
31#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
32pub(crate) struct NodeKey {
33    pub(crate) remote_id: PeerId,
34    pub(crate) remote_ip: IpAddr,
35}