1use 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
21const ADDR_PREFIXL: u8 = 0xfd;
23
24const ADDR_GLOBAL_ID: [u8; 5] = [0x15, 0x07, 0x0a, 0x51, 0x0b];
26
27const RELAY_MAPPED_SUBNET: [u8; 2] = [0x00, 0x01];
29
30const CUSTOM_MAPPED_SUBNET: [u8; 2] = [0x00, 0x03];
32
33const ENDPOINT_ID_SUBNET: [u8; 2] = [0x00, 0x00];
35
36pub(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
53const MAPPED_PORT: u16 = 12345;
58
59pub(crate) trait MappedAddr {
63 fn generate() -> Self;
68
69 fn private_socket_addr(&self) -> SocketAddr;
75}
76
77#[derive(Clone, Debug)]
86pub(crate) enum MultipathMappedAddr {
87 Mixed(EndpointIdMappedAddr),
89 Relay(RelayMappedAddr),
91 Ip(SocketAddr),
93 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#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
132pub(crate) struct EndpointIdMappedAddr(Ipv6Addr);
133
134impl MappedAddr for EndpointIdMappedAddr {
135 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 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#[stack_error(derive, add_meta)]
182#[error("Failed to convert")]
183pub(crate) struct EndpointIdMappedAddrError;
184
185#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
192pub(crate) struct RelayMappedAddr(Ipv6Addr);
193
194impl MappedAddr for RelayMappedAddr {
195 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 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#[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#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
252pub(crate) struct CustomMappedAddr(Ipv6Addr);
253
254impl MappedAddr for CustomMappedAddr {
255 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 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#[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#[derive(Debug, Clone)]
326pub(super) struct AddrMap<K, V> {
327 inner: Arc<std::sync::Mutex<AddrMapInner<K, V>>>,
328}
329
330impl<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 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 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 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
381impl<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
391fn 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
404const MAX_UNPINNED_PER_RELAY: usize = 1024;
409
410const MAX_UNPINNED_RELAYS: usize = 64;
415
416#[derive(Debug, Clone, Default)]
433pub(super) struct RelayAddrMap {
434 inner: Arc<std::sync::Mutex<RelayAddrMapInner>>,
435}
436
437impl RelayAddrMap {
438 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 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 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 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 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 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 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 #[cfg(test)]
519 pub(super) fn len(&self) -> usize {
520 self.inner.lock().expect("poisoned").entries.addrs.len()
521 }
522
523 #[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 queues: HashMap<RelayUrl, UnpinnedQueue>,
541 tick: u64,
544}
545
546#[derive(Debug, Default)]
548struct RelayEntries {
549 addrs: HashMap<(RelayUrl, EndpointId), RelayEntry>,
550 lookup: FxHashMap<RelayMappedAddr, (RelayUrl, EndpointId)>,
551 pinned: HashMap<EndpointId, HashSet<RelayUrl>>,
553}
554
555#[derive(Debug)]
556struct RelayEntry {
557 addr: RelayMappedAddr,
558 queued: Option<u64>,
564}
565
566#[derive(Debug, Default)]
567struct UnpinnedQueue {
568 records: VecDeque<((RelayUrl, EndpointId), u64)>,
572 pushed: u64,
574 last_used: u64,
576}
577
578impl RelayAddrMapInner {
579 fn touch_relay(&mut self, relay: &RelayUrl) -> u64 {
584 self.tick += 1;
585 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 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 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 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 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 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 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 #[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 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 assert_eq!(map.len(), 3 + MAX_UNPINNED_PER_RELAY);
760 }
761
762 #[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 #[test]
774 fn test_pin_addr_ignores_other_endpoints() {
775 let map = RelayAddrMap::default();
776 let addr = map.get_unpinned(&key(0, 1));
777 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 #[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 #[test]
797 fn test_unpin_endpoint() {
798 let map = RelayAddrMap::default();
799 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 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 #[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 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 #[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 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 #[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 #[test]
877 fn test_unpin_does_not_refresh_relays() {
878 let map = RelayAddrMap::default();
879 let handshake = map.get_unpinned(&key(0, 0));
881 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 map.get_unpinned(&key(RELAYS, 1000));
896 assert_eq!(map.lookup(&handshake), Some(key(0, 0)));
897 }
898
899 #[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 map.get_pinned(&key(0, 1));
907 flood(&map, 0, MAX - 1);
908 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 #[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 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}