iroh/socket/
mapped_addrs.rs

1//! The various mapped addresses we use.
2
3//! We use non-IP transports to carry datagrams.  Yet Noq needs to address those
4//! transports using IPv6 addresses.  These defines mappings of several IPv6 Unique Local
5//! Address ranges we use to keep track of the various "fake" address types we use.
6
7use std::{
8    collections::{HashMap, HashSet, VecDeque},
9    fmt,
10    hash::Hash,
11    net::{IpAddr, Ipv6Addr, SocketAddr, SocketAddrV6},
12    sync::Arc,
13};
14
15use iroh_base::{EndpointId, RelayUrl};
16use n0_error::{e, stack_error};
17use rand::Rng;
18use rustc_hash::FxHashMap;
19use tracing::trace;
20
21/// The Prefix/L of all Unique Local Addresses.
22const ADDR_PREFIXL: u8 = 0xfd;
23
24/// The Global ID used in n0's Unique Local Addresses.
25const ADDR_GLOBAL_ID: [u8; 5] = [0x15, 0x07, 0x0a, 0x51, 0x0b];
26
27/// The Subnet ID for [`RelayMappedAddr]: fd15:70a:510b:1::/64.
28const RELAY_MAPPED_SUBNET: [u8; 2] = [0x00, 0x01];
29
30/// The Subnet ID for [`CustomMappedAddr`]: fd15:70a:510b:3::/64.
31const CUSTOM_MAPPED_SUBNET: [u8; 2] = [0x00, 0x03];
32
33/// The Subnet ID for [`EndpointIdMappedAddr`]: fd15:70a:510b::/64.
34const ENDPOINT_ID_SUBNET: [u8; 2] = [0x00, 0x00];
35
36/// A default fake addr, using the maximum addr that the internal fake addrs could be using.
37pub(crate) const DEFAULT_FAKE_ADDR: SocketAddrV6 = SocketAddrV6::new(
38    Ipv6Addr::new(
39        u16::from_be_bytes([ADDR_PREFIXL, 21]),
40        u16::from_be_bytes([7, 10]),
41        u16::from_be_bytes([81, 11]),
42        u16::from_be_bytes([0, 0]),
43        u16::MAX,
44        u16::MAX,
45        u16::MAX,
46        u16::MAX,
47    ),
48    MAPPED_PORT,
49    0,
50    0,
51);
52
53/// The dummy port used for all mapped addresses.
54///
55/// We map each entity, usually an [`crate::EndpointId`], to an IPv6 address.  But socket addresses
56/// involve ports, so we use a dummy fixed port when creating socket addresses.
57const MAPPED_PORT: u16 = 12345;
58
59/// Generic mapped address.
60///
61/// Allows implementing [`AddrMap`].
62pub(crate) trait MappedAddr {
63    /// Generates a new mapped address in the IPv6 Unique Local Address space.
64    ///
65    /// The host bits are random so a remote peer cannot guess one of our live mapped
66    /// addresses (uniqueness is ensured by [`AddrMap::get`]).
67    fn generate() -> Self;
68
69    /// Returns a consistent [`SocketAddr`] for the mapped addr.
70    ///
71    /// This socket address does not have a routable IP address.  It uses a fake but
72    /// consistent port number, since the port does not play a role in the addressing.  This
73    /// socket address is only to be used to pass into Noq.
74    fn private_socket_addr(&self) -> SocketAddr;
75}
76
77/// An enum encompassing all the mapped and unmapped addresses.
78///
79/// This is essentially a slightly-stronger typed version of the IPv6 mapped addresses that
80/// we use on the Noq side.  It categorises the addressed in what kind of mapped or
81/// unmapped addresses they are.
82///
83/// It does not guarantee that a mapped address exists in the mapping.  Or that a particular
84/// address is even supported on this platform.  Hence no wasm exceptions here.
85#[derive(Clone, Debug)]
86pub(crate) enum MultipathMappedAddr {
87    /// An address for a [`crate::EndpointId`], via one or more paths.
88    Mixed(EndpointIdMappedAddr),
89    /// An address for a particular [`crate::EndpointId`] via a particular relay.
90    Relay(RelayMappedAddr),
91    /// An IP based transport address.
92    Ip(SocketAddr),
93    /// Custom transport address.
94    Custom(CustomMappedAddr),
95}
96
97impl From<SocketAddr> for MultipathMappedAddr {
98    fn from(value: SocketAddr) -> Self {
99        match value.ip() {
100            IpAddr::V4(_) => Self::Ip(value),
101            IpAddr::V6(addr) => {
102                if let Ok(addr) = EndpointIdMappedAddr::try_from(addr) {
103                    return Self::Mixed(addr);
104                }
105                if let Ok(addr) = RelayMappedAddr::try_from(addr) {
106                    return Self::Relay(addr);
107                }
108                if let Ok(addr) = CustomMappedAddr::try_from(addr) {
109                    return Self::Custom(addr);
110                }
111                Self::Ip(value)
112            }
113        }
114    }
115}
116
117/// An address used to address a endpoint on any or all paths.
118///
119/// This is only used for initially connecting to a remote endpoint.  We instruct Noq to
120/// send to this address, and duplicate all packets for this address to send on all paths we
121/// might want to send the initial on:
122///
123/// - If this the first connection to the remote endpoint we don't know which path will work
124///   and send to all of them.
125///
126/// - If there already is an active connection to this endpoint we now which path to use.
127///
128/// It is but a newtype around an IPv6 Unique Local Addr.  And in our QUIC-facing socket
129/// APIs like [`noq::AsyncUdpSocket`] it comes in as the inner [`Ipv6Addr`], in those
130/// interfaces we have to be careful to do the conversion to this type.
131#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
132pub(crate) struct EndpointIdMappedAddr(Ipv6Addr);
133
134impl MappedAddr for EndpointIdMappedAddr {
135    /// Generates a globally unique fake UDP address.
136    ///
137    /// This generates and IPv6 Unique Local Address according to RFC 4193.
138    fn generate() -> Self {
139        let mut addr = [0u8; 16];
140        addr[0] = ADDR_PREFIXL;
141        addr[1..6].copy_from_slice(&ADDR_GLOBAL_ID);
142        addr[6..8].copy_from_slice(&ENDPOINT_ID_SUBNET);
143        rand::rng().fill_bytes(&mut addr[8..16]);
144
145        Self(Ipv6Addr::from(addr))
146    }
147
148    /// Returns a consistent [`SocketAddr`] for the [`EndpointIdMappedAddr`].
149    ///
150    /// This socket address does not have a routable IP address and port.
151    ///
152    /// This uses a made-up port number, since the port does not play a role in the
153    /// addressing.  This socket address is only to be used to pass into Noq.
154    fn private_socket_addr(&self) -> SocketAddr {
155        SocketAddr::new(IpAddr::from(self.0), MAPPED_PORT)
156    }
157}
158
159impl std::fmt::Display for EndpointIdMappedAddr {
160    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
161        write!(f, "EndpointIdMappedAddr({})", self.0)
162    }
163}
164
165impl TryFrom<Ipv6Addr> for EndpointIdMappedAddr {
166    type Error = EndpointIdMappedAddrError;
167
168    fn try_from(value: Ipv6Addr) -> Result<Self, Self::Error> {
169        let octets = value.octets();
170        if octets[0] == ADDR_PREFIXL
171            && octets[1..6] == ADDR_GLOBAL_ID
172            && octets[6..8] == ENDPOINT_ID_SUBNET
173        {
174            return Ok(Self(value));
175        }
176        Err(e!(EndpointIdMappedAddrError))
177    }
178}
179
180/// Can occur when converting a [`SocketAddr`] to an [`EndpointIdMappedAddr`]
181#[stack_error(derive, add_meta)]
182#[error("Failed to convert")]
183pub(crate) struct EndpointIdMappedAddrError;
184
185/// An Ipv6 ULA address, identifying a relay path for a [`crate::EndpointId`].
186///
187/// Since iroh endpoint are reachable via a relay server we have a network path indicated by
188/// the `(EndpointId, RelayUrl)`.  However Noq can only handle socket addresses, so we use
189/// IPv6 addresses in a private IPv6 Unique Local Address range, which map to a unique
190/// `(EndointId, RelayUrl)` pair.
191#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
192pub(crate) struct RelayMappedAddr(Ipv6Addr);
193
194impl MappedAddr for RelayMappedAddr {
195    /// Generates a globally unique fake UDP address.
196    ///
197    /// This generates a new IPv6 address in the Unique Local Address range (RFC 4193)
198    /// which is recognised by iroh as an IP mapped address.
199    fn generate() -> Self {
200        let mut addr = [0u8; 16];
201        addr[0] = ADDR_PREFIXL;
202        addr[1..6].copy_from_slice(&ADDR_GLOBAL_ID);
203        addr[6..8].copy_from_slice(&RELAY_MAPPED_SUBNET);
204        rand::rng().fill_bytes(&mut addr[8..16]);
205
206        Self(Ipv6Addr::from(addr))
207    }
208
209    /// Returns a consistent [`SocketAddr`] for the [`RelayMappedAddr`].
210    ///
211    /// This socket address does not have a routable IP address and port.
212    ///
213    /// This uses a made-up port number, since the port does not play a role in the
214    /// addressing.  This socket address is only to be used to pass into Noq.
215    fn private_socket_addr(&self) -> SocketAddr {
216        SocketAddr::new(IpAddr::from(self.0), MAPPED_PORT)
217    }
218}
219
220impl TryFrom<Ipv6Addr> for RelayMappedAddr {
221    type Error = RelayMappedAddrError;
222
223    fn try_from(value: Ipv6Addr) -> std::result::Result<Self, Self::Error> {
224        let octets = value.octets();
225        if octets[0] == ADDR_PREFIXL
226            && octets[1..6] == ADDR_GLOBAL_ID
227            && octets[6..8] == RELAY_MAPPED_SUBNET
228        {
229            return Ok(Self(value));
230        }
231        Err(e!(RelayMappedAddrError))
232    }
233}
234
235/// Can occur when converting a [`SocketAddr`] to an [`RelayMappedAddr`]
236#[stack_error(derive, add_meta)]
237#[error("Failed to convert")]
238pub(crate) struct RelayMappedAddrError;
239
240impl std::fmt::Display for RelayMappedAddr {
241    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
242        write!(f, "RelayMappedAddr({})", self.0)
243    }
244}
245
246/// An Ipv6 ULA address, identifying a custom transport path.
247///
248/// Custom transports allow user-defined transport mechanisms. However Noq can only handle
249/// socket addresses, so we use IPv6 addresses in a private IPv6 Unique Local Address range,
250/// which map to a unique [`iroh_base::CustomAddr`].
251#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
252pub(crate) struct CustomMappedAddr(Ipv6Addr);
253
254impl MappedAddr for CustomMappedAddr {
255    /// Generates a globally unique fake UDP address.
256    ///
257    /// This generates a new IPv6 address in the Unique Local Address range (RFC 4193)
258    /// which is recognised by iroh as an IP mapped address.
259    fn generate() -> Self {
260        let mut addr = [0u8; 16];
261        addr[0] = ADDR_PREFIXL;
262        addr[1..6].copy_from_slice(&ADDR_GLOBAL_ID);
263        addr[6..8].copy_from_slice(&CUSTOM_MAPPED_SUBNET);
264        rand::rng().fill_bytes(&mut addr[8..16]);
265
266        Self(Ipv6Addr::from(addr))
267    }
268
269    /// Returns a consistent [`SocketAddr`] for the [`CustomMappedAddr`].
270    ///
271    /// This socket address does not have a routable IP address and port.
272    ///
273    /// This uses a made-up port number, since the port does not play a role in the
274    /// addressing.  This socket address is only to be used to pass into Noq.
275    fn private_socket_addr(&self) -> SocketAddr {
276        SocketAddr::new(IpAddr::from(self.0), MAPPED_PORT)
277    }
278}
279
280impl TryFrom<IpAddr> for CustomMappedAddr {
281    type Error = CustomMappedAddrError;
282
283    fn try_from(value: IpAddr) -> std::result::Result<Self, Self::Error> {
284        match value {
285            IpAddr::V4(_) => Err(e!(CustomMappedAddrError)),
286            IpAddr::V6(addr) => addr.try_into(),
287        }
288    }
289}
290
291impl TryFrom<Ipv6Addr> for CustomMappedAddr {
292    type Error = CustomMappedAddrError;
293
294    fn try_from(value: Ipv6Addr) -> std::result::Result<Self, Self::Error> {
295        let octets = value.octets();
296        if octets[0] == ADDR_PREFIXL
297            && octets[1..6] == ADDR_GLOBAL_ID
298            && octets[6..8] == CUSTOM_MAPPED_SUBNET
299        {
300            return Ok(Self(value));
301        }
302        Err(e!(CustomMappedAddrError))
303    }
304}
305
306/// Can occur when converting a [`SocketAddr`] to a [`CustomMappedAddr`]
307#[stack_error(derive, add_meta)]
308#[error("Failed to convert")]
309pub(crate) struct CustomMappedAddrError;
310
311impl std::fmt::Display for CustomMappedAddr {
312    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
313        write!(f, "CustomMappedAddr({})", self.0)
314    }
315}
316
317/// A bi-directional map between a key and a [`MappedAddr`].
318///
319/// Entries are only removed explicitly with [`AddrMap::remove`]. Keys come from trusted
320/// sources or are removed by their owner, see [`RelayAddrMap`] for relay-chosen keys.
321///
322/// The forward map uses the standard library's randomly seeded hasher because keys may be
323/// chosen by remotes whereas the reverse map uses `FxHashMap` because mapped addresses are
324/// generated locally at random.
325#[derive(Debug, Clone)]
326pub(super) struct AddrMap<K, V> {
327    inner: Arc<std::sync::Mutex<AddrMapInner<K, V>>>,
328}
329
330// Manual impl because derive ends up requiring T: Default.
331impl<K, V> Default for AddrMap<K, V> {
332    fn default() -> Self {
333        Self {
334            inner: Default::default(),
335        }
336    }
337}
338
339impl<K, V> AddrMap<K, V>
340where
341    K: Eq + Hash + Clone + fmt::Debug,
342    V: MappedAddr + Eq + Hash + Copy + fmt::Debug,
343{
344    /// Returns the [`MappedAddr`], generating one if needed.
345    pub(super) fn get(&self, key: &K) -> V {
346        let mut inner = self.inner.lock().expect("poisoned");
347        match inner.addrs.get(key) {
348            Some(addr) => *addr,
349            None => {
350                let addr = generate_unique(&inner.lookup);
351                inner.addrs.insert(key.clone(), addr);
352                inner.lookup.insert(addr, key.clone());
353                trace!(?addr, ?key, "generated new addr");
354                addr
355            }
356        }
357    }
358
359    /// Removes the entry for `key`, if any.
360    pub(super) fn remove(&self, key: &K) {
361        let mut inner = self.inner.lock().expect("poisoned");
362        if let Some(addr) = inner.addrs.remove(key) {
363            inner.lookup.remove(&addr);
364            trace!(?addr, ?key, "removed addr");
365        }
366    }
367
368    /// Performs the reverse lookup.
369    pub(super) fn lookup(&self, addr: &V) -> Option<K> {
370        let inner = self.inner.lock().expect("poisoned");
371        inner.lookup.get(addr).cloned()
372    }
373}
374
375#[derive(Debug)]
376struct AddrMapInner<K, V> {
377    addrs: HashMap<K, V>,
378    lookup: FxHashMap<V, K>,
379}
380
381// Manual impl because derive ends up requiring T: Default.
382impl<K, V> Default for AddrMapInner<K, V> {
383    fn default() -> Self {
384        Self {
385            addrs: Default::default(),
386            lookup: Default::default(),
387        }
388    }
389}
390
391/// Generates a mapped address not yet present in `lookup`.
392///
393/// It's important these are generated randomly and not a counter in order to be
394/// unpredictable from the outside.
395fn generate_unique<V: MappedAddr + Eq + Hash, K>(lookup: &FxHashMap<V, K>) -> V {
396    loop {
397        let candidate = V::generate();
398        if !lookup.contains_key(&candidate) {
399            break candidate;
400        }
401    }
402}
403
404/// Maximum number of unpinned entries per relay in a [`RelayAddrMap`].
405///
406/// Bounding per relay ensures a relay forging source IDs can only evict unpinned entries
407/// from its own traffic.
408const MAX_UNPINNED_PER_RELAY: usize = 1024;
409
410/// Maximum number of relays with unpinned entries in a [`RelayAddrMap`].
411///
412/// Adding a relay beyond this limit evicts all unpinned entries of the least recently used
413/// relay, bounding entries left behind by relays we are no longer connected to.
414const MAX_UNPINNED_RELAYS: usize = 64;
415
416/// A bi-directional map between `(RelayUrl, EndpointId)` and [`RelayMappedAddr`].
417///
418/// Every datagram received over a relay needs a mapped address, and the relay chooses the
419/// source [`EndpointId`]. Noq may keep using a mapped address for as long as a connection
420/// or handshake refers to it, so entries are either pinned or unpinned:
421///
422/// - [`RelayAddrMap::get_unpinned`] looks up or inserts an entry for a received datagram.
423///   New entries are unpinned.
424///
425/// - The `RemoteStateActor` of an endpoint pins the entries of that endpoint which its
426///   connections use as paths, with [`RelayAddrMap::get_pinned`] or
427///   [`RelayAddrMap::pin_addr`]. Pinned entries are never evicted.
428///   [`RelayAddrMap::unpin_endpoint`] unpins them again once the actor stops.
429///
430/// - Unpinned entries are bounded per relay and in the number of relays. When a bound is
431///   exceeded, the oldest unpinned entries are removed.
432#[derive(Debug, Clone, Default)]
433pub(super) struct RelayAddrMap {
434    inner: Arc<std::sync::Mutex<RelayAddrMapInner>>,
435}
436
437impl RelayAddrMap {
438    /// Returns the [`RelayMappedAddr`] for `key`, pinning it for the endpoint it names.
439    pub(super) fn get_pinned(&self, key: &(RelayUrl, EndpointId)) -> RelayMappedAddr {
440        let mut inner = self.inner.lock().expect("poisoned");
441        if !inner.entries.addrs.contains_key(key) {
442            inner.entries.insert(key);
443        }
444        inner.entries.pin(key)
445    }
446
447    /// Pins the entry for `addr` and returns its key, if the entry exists and names
448    /// `endpoint_id`.
449    ///
450    /// Looking up and pinning under one lock ensures the entry cannot be evicted in between.
451    /// Entries naming another endpoint are not pinned and `None` is returned: they would
452    /// otherwise stay pinned for an endpoint whose actor may never run, and so never be
453    /// unpinned.
454    pub(super) fn pin_addr(
455        &self,
456        addr: &RelayMappedAddr,
457        endpoint_id: &EndpointId,
458    ) -> Option<(RelayUrl, EndpointId)> {
459        let mut inner = self.inner.lock().expect("poisoned");
460        let key = inner
461            .entries
462            .lookup
463            .get(addr)
464            .filter(|key| key.1 == *endpoint_id)
465            .cloned()?;
466        inner.entries.pin(&key);
467        Some(key)
468    }
469
470    /// Returns the [`RelayMappedAddr`] for `key`, inserting an unpinned entry if needed.
471    pub(super) fn get_unpinned(&self, key: &(RelayUrl, EndpointId)) -> RelayMappedAddr {
472        let mut guard = self.inner.lock().expect("poisoned");
473        let inner = &mut *guard;
474        // Only receive traffic refreshes a relay, so silent relays are evicted first.
475        let pushed = inner.touch_relay(&key.0);
476        match inner.entries.addrs.get(key) {
477            Some(RelayEntry {
478                addr,
479                queued: Some(seq),
480            }) => {
481                let (addr, seq) = (*addr, *seq);
482                if pushed - seq > MAX_UNPINNED_PER_RELAY as u64 / 2 {
483                    // Refresh active unpinned entries once they are past the midpoint of the
484                    // queue, avoiding a new queue record on every packet.
485                    inner.enqueue(key);
486                }
487                addr
488            }
489            Some(RelayEntry { addr, queued: None }) => *addr,
490            None => {
491                let addr = inner.entries.insert(key);
492                inner.enqueue(key);
493                addr
494            }
495        }
496    }
497
498    /// Unpins all entries of `endpoint_id` after its `RemoteStateActor` has stopped.
499    ///
500    /// The entries are queued rather than removed, so Noq can finish handshakes that are
501    /// still in flight and a reconnecting peer keeps its mapped address unless evicted in
502    /// the meantime.
503    pub(super) fn unpin_endpoint(&self, endpoint_id: &EndpointId) {
504        let mut inner = self.inner.lock().expect("poisoned");
505        let relays = inner.entries.pinned.remove(endpoint_id).unwrap_or_default();
506        for relay in relays {
507            inner.enqueue(&(relay, *endpoint_id));
508        }
509    }
510
511    /// Performs the reverse lookup.
512    pub(super) fn lookup(&self, addr: &RelayMappedAddr) -> Option<(RelayUrl, EndpointId)> {
513        let inner = self.inner.lock().expect("poisoned");
514        inner.entries.lookup.get(addr).cloned()
515    }
516
517    /// Returns the number of entries.
518    #[cfg(test)]
519    pub(super) fn len(&self) -> usize {
520        self.inner.lock().expect("poisoned").entries.addrs.len()
521    }
522
523    /// Returns whether an entry for `addr` exists and is pinned.
524    #[cfg(test)]
525    pub(super) fn is_pinned(&self, addr: &RelayMappedAddr) -> bool {
526        let inner = self.inner.lock().expect("poisoned");
527        inner
528            .entries
529            .lookup
530            .get(addr)
531            .and_then(|key| inner.entries.addrs.get(key))
532            .is_some_and(|entry| entry.queued.is_none())
533    }
534}
535
536#[derive(Debug, Default)]
537struct RelayAddrMapInner {
538    entries: RelayEntries,
539    /// Per-relay FIFO queues of unpinned entries.
540    queues: HashMap<RelayUrl, UnpinnedQueue>,
541    /// Monotonic counter incremented on [`RelayAddrMap::get_unpinned`], used for
542    /// [`UnpinnedQueue::last_used`].
543    tick: u64,
544}
545
546/// Forward, reverse, and pin tables for a [`RelayAddrMap`].
547#[derive(Debug, Default)]
548struct RelayEntries {
549    addrs: HashMap<(RelayUrl, EndpointId), RelayEntry>,
550    lookup: FxHashMap<RelayMappedAddr, (RelayUrl, EndpointId)>,
551    /// Relays on which each endpoint currently has pinned entries.
552    pinned: HashMap<EndpointId, HashSet<RelayUrl>>,
553}
554
555#[derive(Debug)]
556struct RelayEntry {
557    addr: RelayMappedAddr,
558    /// Sequence number of this entry's live record in its relay's [`UnpinnedQueue`], or
559    /// `None` if the entry is pinned.
560    ///
561    /// Queue records with any other sequence number are stale (left behind when the entry
562    /// was pinned or requeued) and are ignored on pop.
563    queued: Option<u64>,
564}
565
566#[derive(Debug, Default)]
567struct UnpinnedQueue {
568    /// Queued `(key, seq)` records from oldest to newest.
569    ///
570    /// May contain stale records; see [`RelayEntry::queued`].
571    records: VecDeque<((RelayUrl, EndpointId), u64)>,
572    /// Sequence number of the most recently pushed record.
573    pushed: u64,
574    /// Value of [`RelayAddrMapInner::tick`] when this relay last delivered a datagram.
575    last_used: u64,
576}
577
578impl RelayAddrMapInner {
579    /// Marks `relay` as recently used, first evicting the unpinned entries of the least
580    /// recently used relay if adding `relay` would exceed [`MAX_UNPINNED_RELAYS`].
581    ///
582    /// Returns [`UnpinnedQueue::pushed`] of `relay`'s queue.
583    fn touch_relay(&mut self, relay: &RelayUrl) -> u64 {
584        self.tick += 1;
585        // Runs on every received relay datagram, so the common case is a single lookup.
586        if let Some(queue) = self.queues.get_mut(relay) {
587            queue.last_used = self.tick;
588            return queue.pushed;
589        }
590        if self.queues.len() >= MAX_UNPINNED_RELAYS {
591            let least_recent = self
592                .queues
593                .iter()
594                .min_by_key(|(_, queue)| queue.last_used)
595                .map(|(relay, _)| relay.clone());
596            if let Some(queue) = least_recent.and_then(|relay| self.queues.remove(&relay)) {
597                for (key, seq) in queue.records {
598                    self.entries.evict_record(&key, seq);
599                }
600            }
601        }
602        let queue = UnpinnedQueue {
603            last_used: self.tick,
604            ..Default::default()
605        };
606        self.queues.insert(relay.clone(), queue);
607        0
608    }
609
610    /// Pushes `key` onto its relay's queue and evicts the oldest records past
611    /// [`MAX_UNPINNED_PER_RELAY`].
612    ///
613    /// Does not update `last_used`: if the relay has no queue yet, it is created with
614    /// `last_used = 0`, so unpinning entries of silent relays cannot displace active ones.
615    /// If [`MAX_UNPINNED_RELAYS`] queues already exist, the entry is evicted immediately.
616    fn enqueue(&mut self, key: &(RelayUrl, EndpointId)) {
617        let Self {
618            entries, queues, ..
619        } = self;
620        let Some(entry) = entries.addrs.get_mut(key) else {
621            return;
622        };
623        if !queues.contains_key(&key.0) && queues.len() >= MAX_UNPINNED_RELAYS {
624            entries.remove(key);
625            return;
626        }
627
628        let queue = queues.entry(key.0.clone()).or_default();
629        queue.pushed += 1;
630        queue.records.push_back((key.clone(), queue.pushed));
631        entry.queued = Some(queue.pushed);
632        while queue.records.len() > MAX_UNPINNED_PER_RELAY {
633            if let Some((key, seq)) = queue.records.pop_front() {
634                entries.evict_record(&key, seq);
635            }
636        }
637    }
638}
639
640impl RelayEntries {
641    /// Generates and inserts a fresh entry for `key` (which must not already exist).
642    ///
643    /// The caller must immediately either pin or enqueue the new entry.
644    fn insert(&mut self, key: &(RelayUrl, EndpointId)) -> RelayMappedAddr {
645        let addr = generate_unique(&self.lookup);
646        self.addrs
647            .insert(key.clone(), RelayEntry { addr, queued: None });
648        self.lookup.insert(addr, key.clone());
649        trace!(?addr, ?key, "generated new addr");
650        addr
651    }
652
653    /// Marks the existing entry for `key` as pinned by the endpoint it names.
654    fn pin(&mut self, key: &(RelayUrl, EndpointId)) -> RelayMappedAddr {
655        let entry = self.addrs.get_mut(key).expect("checked by caller");
656        entry.queued = None;
657        self.pinned.entry(key.1).or_default().insert(key.0.clone());
658        entry.addr
659    }
660
661    /// Removes the entry for `key` if `seq` is still its current queue record.
662    fn evict_record(&mut self, key: &(RelayUrl, EndpointId), seq: u64) {
663        if self
664            .addrs
665            .get(key)
666            .is_some_and(|entry| entry.queued == Some(seq))
667        {
668            self.remove(key);
669        }
670    }
671
672    /// Removes the entry for `key`.
673    fn remove(&mut self, key: &(RelayUrl, EndpointId)) {
674        if let Some(entry) = self.addrs.remove(key) {
675            self.lookup.remove(&entry.addr);
676            trace!(addr = ?entry.addr, ?key, "evicted unpinned addr");
677        }
678    }
679}
680
681#[cfg(test)]
682mod tests {
683    use std::sync::atomic::{AtomicU64, Ordering};
684
685    use iroh_base::SecretKey;
686
687    use super::*;
688
689    const MAX: u64 = MAX_UNPINNED_PER_RELAY as u64;
690    const RELAYS: u8 = MAX_UNPINNED_RELAYS as u8;
691
692    fn id(i: u64) -> EndpointId {
693        let mut bytes = [0u8; 32];
694        bytes[..8].copy_from_slice(&i.to_le_bytes());
695        SecretKey::from_bytes(&bytes).public()
696    }
697
698    fn url(relay: u8) -> RelayUrl {
699        format!("https://relay{relay}.example")
700            .parse()
701            .expect("valid url")
702    }
703
704    fn key(relay: u8, i: u64) -> (RelayUrl, EndpointId) {
705        (url(relay), id(i))
706    }
707
708    /// Inserts `n` unpinned entries for distinct endpoints on `relay`.
709    fn flood(map: &RelayAddrMap, relay: u8, n: u64) -> Vec<RelayMappedAddr> {
710        static NEXT_ID: AtomicU64 = AtomicU64::new(1_000_000);
711        (0..n)
712            .map(|_| {
713                let i = NEXT_ID.fetch_add(1, Ordering::Relaxed);
714                map.get_unpinned(&key(relay, i))
715            })
716            .collect()
717    }
718
719    #[test]
720    fn test_addr_map_remove() {
721        let map = AddrMap::<EndpointId, RelayMappedAddr>::default();
722        let addr = map.get(&id(1));
723        assert_eq!(map.get(&id(1)), addr);
724        assert_eq!(map.lookup(&addr), Some(id(1)));
725
726        map.remove(&id(1));
727        assert_eq!(map.lookup(&addr), None);
728        assert!(map.inner.lock().unwrap().addrs.is_empty());
729    }
730
731    #[test]
732    fn test_get_is_stable_and_reversible() {
733        let map = RelayAddrMap::default();
734        let addr = map.get_pinned(&key(0, 1));
735        assert_eq!(map.get_pinned(&key(0, 1)), addr);
736        assert_eq!(map.get_unpinned(&key(0, 1)), addr);
737        assert_eq!(map.lookup(&addr), Some(key(0, 1)));
738    }
739
740    /// Flooding a relay with unpinned entries stays within the per-relay cap and preserves
741    /// pinned entries and other relays.
742    #[test]
743    fn test_unpinned_entries_are_bounded_per_relay() {
744        let map = RelayAddrMap::default();
745        let pinned = map.get_pinned(&key(0, 0));
746        // Created on receive, then registered as a path by the actor of id(1).
747        let received = map.get_unpinned(&key(0, 1));
748        map.pin_addr(&received, &id(1));
749        let other_relay = map.get_unpinned(&key(1, 2));
750
751        let flood = flood(&map, 0, 3 * MAX);
752
753        assert_eq!(map.lookup(&pinned), Some(key(0, 0)));
754        assert_eq!(map.lookup(&received), Some(key(0, 1)));
755        assert_eq!(map.lookup(&other_relay), Some(key(1, 2)));
756        assert!(map.lookup(flood.last().unwrap()).is_some());
757        assert!(map.lookup(&flood[0]).is_none());
758        // Two pinned entries, the other relay's entry, plus the capped relay.
759        assert_eq!(map.len(), 3 + MAX_UNPINNED_PER_RELAY);
760    }
761
762    /// Pinning an unpinned entry protects it from eviction.
763    #[test]
764    fn test_get_pinned_pins_unpinned_entry() {
765        let map = RelayAddrMap::default();
766        let addr = map.get_unpinned(&key(0, 1));
767        assert_eq!(map.get_pinned(&key(0, 1)), addr);
768        flood(&map, 0, 2 * MAX);
769        assert_eq!(map.lookup(&addr), Some(key(0, 1)));
770    }
771
772    /// `pin_addr` only pins entries naming the given endpoint.
773    #[test]
774    fn test_pin_addr_ignores_other_endpoints() {
775        let map = RelayAddrMap::default();
776        let addr = map.get_unpinned(&key(0, 1));
777        // A relay labelled id(2)'s path as id(1).
778        assert_eq!(map.pin_addr(&addr, &id(2)), None);
779        assert!(map.inner.lock().unwrap().entries.pinned.is_empty());
780        flood(&map, 0, MAX);
781        assert_eq!(map.lookup(&addr), None);
782        assert_eq!(map.pin_addr(&addr, &id(1)), None, "evicted");
783    }
784
785    /// `pin_addr` pins entries naming the given endpoint and returns their key.
786    #[test]
787    fn test_pin_addr_returns_key() {
788        let map = RelayAddrMap::default();
789        let addr = map.get_unpinned(&key(0, 1));
790        assert_eq!(map.pin_addr(&addr, &id(1)), Some(key(0, 1)));
791        assert!(map.is_pinned(&addr));
792    }
793
794    /// Unpinning an endpoint keeps its entries until they are evicted and places them at the
795    /// back of the queue even if they were previously near the front.
796    #[test]
797    fn test_unpin_endpoint() {
798        let map = RelayAddrMap::default();
799        // Created on receive, then registered as a path by the actor of id(1).
800        let received = map.get_unpinned(&key(0, 1));
801        map.pin_addr(&received, &id(1));
802        flood(&map, 0, MAX - 1);
803        let pinned = map.get_pinned(&key(1, 1));
804        let other = map.get_pinned(&key(0, 2));
805
806        // The actor of id(1) stops.
807        map.unpin_endpoint(&id(1));
808        assert_eq!(map.lookup(&received), Some(key(0, 1)));
809        assert_eq!(map.lookup(&pinned), Some(key(1, 1)));
810
811        flood(&map, 0, MAX - 1);
812        assert_eq!(map.lookup(&received), Some(key(0, 1)));
813        flood(&map, 0, 1);
814        assert_eq!(map.lookup(&received), None);
815        assert_eq!(map.lookup(&pinned), Some(key(1, 1)), "other relay");
816        assert_eq!(map.lookup(&other), Some(key(0, 2)), "still pinned");
817        assert!(
818            !map.inner
819                .lock()
820                .unwrap()
821                .entries
822                .pinned
823                .contains_key(&id(1))
824        );
825    }
826
827    /// Unpinning entries of relays without a queue once at [`MAX_UNPINNED_RELAYS`] evicts
828    /// those entries instead of displacing active relays.
829    #[test]
830    fn test_unpin_does_not_add_relays() {
831        let map = RelayAddrMap::default();
832        let addrs: Vec<_> = (0..RELAYS)
833            .map(|relay| map.get_unpinned(&key(relay, relay as u64)))
834            .collect();
835        // Pinned entries on relays that have no unpinned queue yet.
836        let candidates: Vec<_> = (0..10)
837            .map(|i| map.get_pinned(&key(RELAYS + i, 500)))
838            .collect();
839
840        map.unpin_endpoint(&id(500));
841        assert!(addrs.iter().all(|addr| map.lookup(addr).is_some()));
842        assert!(candidates.iter().all(|addr| map.lookup(addr).is_none()));
843        assert_eq!(map.inner.lock().unwrap().queues.len(), MAX_UNPINNED_RELAYS);
844    }
845
846    /// A hit on a pinned entry marks its relay as used.
847    #[test]
848    fn test_pinned_hit_marks_relay_used() {
849        let map = RelayAddrMap::default();
850        let unpinned = map.get_unpinned(&key(0, 0));
851        map.get_pinned(&key(0, 1));
852        for relay in 1..RELAYS {
853            map.get_unpinned(&key(relay, relay as u64 + 100));
854        }
855        // Receive traffic on the pinned entry refreshes relay 0.
856        map.get_unpinned(&key(0, 1));
857
858        map.get_unpinned(&key(RELAYS, 1000));
859        assert_eq!(map.lookup(&unpinned), Some(key(0, 0)));
860    }
861
862    /// An unpinned entry that keeps receiving traffic is refreshed before it reaches the
863    /// front of the queue.
864    #[test]
865    fn test_used_unpinned_entry_is_requeued() {
866        let map = RelayAddrMap::default();
867        let addr = map.get_unpinned(&key(0, 1));
868        for i in 0..3 * MAX {
869            map.get_unpinned(&key(0, 100 + i));
870            assert_eq!(map.get_unpinned(&key(0, 1)), addr);
871        }
872    }
873
874    /// Unpinning into a new relay queue leaves `last_used` at 0 so that silent relays are
875    /// evicted before relays with receive traffic.
876    #[test]
877    fn test_unpin_does_not_refresh_relays() {
878        let map = RelayAddrMap::default();
879        // A relay with a handshake in flight.
880        let handshake = map.get_unpinned(&key(0, 0));
881        // An actor that pinned entries on relays without receive traffic stops.
882        for relay in 1..RELAYS {
883            map.get_pinned(&key(relay, 500));
884        }
885        map.unpin_endpoint(&id(500));
886        {
887            let inner = map.inner.lock().unwrap();
888            assert_eq!(inner.queues.len(), MAX_UNPINNED_RELAYS);
889            for relay in 1..RELAYS {
890                assert_eq!(inner.queues[&url(relay)].last_used, 0);
891            }
892        }
893
894        // Traffic from a new relay evicts one of the silent relays, not the active one.
895        map.get_unpinned(&key(RELAYS, 1000));
896        assert_eq!(map.lookup(&handshake), Some(key(0, 0)));
897    }
898
899    /// Popping an older stale queue record does not evict an entry that was pinned and later
900    /// requeued with a newer sequence number.
901    #[test]
902    fn test_stale_record_does_not_evict_requeued_entry() {
903        let map = RelayAddrMap::default();
904        let addr = map.get_unpinned(&key(0, 1));
905        // Pin and later unpin: the first record becomes stale once the second is pushed.
906        map.get_pinned(&key(0, 1));
907        flood(&map, 0, MAX - 1);
908        // Requeueing overflows the queue and pops the stale record.
909        map.unpin_endpoint(&id(1));
910        assert_eq!(map.lookup(&addr), Some(key(0, 1)));
911        assert_eq!(map.len(), MAX_UNPINNED_PER_RELAY);
912    }
913
914    /// The number of relays with unpinned entries is capped at [`MAX_UNPINNED_RELAYS`],
915    /// evicting the least recently used relay.
916    #[test]
917    fn test_unpinned_relays_are_bounded() {
918        let map = RelayAddrMap::default();
919        let first = map.get_unpinned(&key(0, 0));
920        let second = map.get_unpinned(&key(1, 1));
921        let rest: Vec<_> = (2..RELAYS)
922            .map(|relay| map.get_unpinned(&key(relay, relay as u64)))
923            .collect();
924        // Refresh relay 0 so relay 1 becomes the least recently used.
925        map.get_unpinned(&key(0, 0));
926
927        let new = map.get_unpinned(&key(RELAYS, 1000));
928        assert_eq!(map.lookup(&first), Some(key(0, 0)));
929        assert_eq!(
930            map.lookup(&second),
931            None,
932            "least recently used relay evicted"
933        );
934        assert!(rest.iter().all(|addr| map.lookup(addr).is_some()));
935        assert!(map.lookup(&new).is_some());
936        assert_eq!(map.len(), MAX_UNPINNED_RELAYS);
937        assert_eq!(map.inner.lock().unwrap().queues.len(), MAX_UNPINNED_RELAYS);
938    }
939}