Skip to main content

hyprstream_p2p/
locator.rs

1//! Mainline (BEP5) DHT locator — untrusted peer rendezvous for `did:at9p`.
2//!
3//! Track C of the at9p epic (#880, story C1 = #889). This module wraps the
4//! standalone [`mainline`] crate (MIT, pubky/pkarr lineage) to provide
5//! arbitrary-infohash `announce_peer` / `get_peers`, which iroh's internal
6//! pkarr integration cannot do (it is NodeId-lookup only).
7//!
8//! # Trust model
9//!
10//! The DHT is an **untrusted locator**: it only ever yields *candidate* peer
11//! contacts. Zero authority is derived from anything read here — capsules
12//! fetched from returned peers must pass the full GATE pipeline
13//! (canon → H512 == cid512 → composite signature) before use (#879 §5.6).
14//!
15//! # TRUNC20 confinement (review rule R2)
16//!
17//! BEP5 keys are 20-byte infohashes; at9p identities are 64-byte BLAKE3-512
18//! CIDs. The truncation from 64 → 20 bytes happens in exactly one place:
19//! [`rendezvous_infohash`], private to this module. Every public API takes
20//! the full [`Cid512`] plus fixed-width rendezvous parameters; no truncated
21//! form escapes this module.
22//!
23//! # No name path — review rule R1 (story C4 = #892)
24//!
25//! Every public entry point on [`MainlineLocator`] takes a [`Cid512`]. There
26//! is deliberately **no** string-name lookup, no `name → cid` resolution, and
27//! no `name → cid` cache anywhere in this module. A name cache *inside the
28//! DHT client* re-opens threat A5: it turns the DHT into a trusted namespace
29//! authority (whoever poisons the cache chooses which capsule a name resolves
30//! to), exactly the "toxic mold" failure mode #879 §3 excludes. Names are
31//! resolved by a PQ-signed `NameRecord` from a trusted namespace authority
32//! (PDS / discovery / MoQ group) *above* this layer; the locator only ever
33//! answers "where might bytes for *this* cid live", never "which cid does
34//! *this* name mean".
35//!
36//! This is enforced **structurally** as a closed-world allowlist, not by
37//! enumerating forbidden string forms:
38//! - [`Cid512`] is a `[u8; 64]` newtype with no `FromStr`, `From<&str>`,
39//!   `AsRef<str>`, or `Deref<Target = str>` — the only way in is the full
40//!   64-byte digest.
41//! - `tests/locator_r1_invariants.rs` parses this module with `syn` and fails
42//!   unless **every** public function/method parameter, public struct/enum
43//!   field, and type-alias RHS is one of the vetted types — `Cid512`,
44//!   `RendezvousKey`, `PeerContact`, `LookupHints`, `SocketAddrV4`, primitives,
45//!   and byte views (recursing through `&`/`Option`/`Vec`/`Box`/slices). Any
46//!   other type — a `String`, a struct-wrapped name (`NameQuery`), a generic
47//!   (`<S: ToString>`, `impl Display`), an externally-aliased name — is
48//!   rejected *because it is not vetted*, so a name path cannot enter in any
49//!   new form; adding a public parameter type is a deliberate allowlist edit.
50//!   Macros and `pub use` are forbidden outright in this module. `Cid512` may
51//!   not gain a string-conversion trait impl. See the test's module doc for the
52//!   coverage matrix, the known limitation (test-time vs compile-time), and the
53//!   follow-up tracking a hard `compile_error!` enforcement.
54//!
55//! # Add-only hints — review rule R7 (story C4 = #892)
56//!
57//! #879 §6.1 lists two rendezvous strategies: (1) BEP5 `announce_peer` /
58//! `get_peers` (chosen), and (2) a BEP44 deterministic-mailbox channel whose
59//! keypair is derived from the cid and is therefore public-by-construction —
60//! an overwrite war that is availability-only, acceptable *only* because the
61//! values are untrusted hints. The v1 decision (Q3) is recorded by
62//! [`V1_MAILBOX_HINT_CHANNEL`]: **BEP5-only for v1; the mailbox is deferred.**
63//!
64//! Whether or not the mailbox ships, R7 is load-bearing: a hint channel may
65//! only **add** lookup targets — it may never prune, replace, or terminate the
66//! watermark-anchored BEP5 scan (A14: a bogus "current epoch" hint that skips
67//! the scan converts an availability channel into a rollback assist). That
68//! constraint is encoded in [`LookupHints`], an accumulator whose API is
69//! add-only by construction (no `remove` / `replace` / `clear`), and in
70//! [`MainlineLocator::providers_with_hints`], which **always** performs the
71//! scan and then unions the hints in. There is no code path that lets a hint
72//! skip the scan.
73//!
74//! # wasm / browser note (documented, not built — C1 acceptance)
75//!
76//! There is **no raw mainline DHT from wasm**: browsers cannot open UDP
77//! sockets, and iroh itself falls back to a pkarr HTTP relay
78//! (`dns.iroh.link`) there. The wasm locator therefore needs either a relay
79//! bridge (an HTTP/WebTransport endpoint on a trusted-for-liveness node that
80//! proxies `get_peers`) or a PDS fallback (capsule fetched via atproto
81//! records, #910). That surface is shared with #470 and is deliberately not
82//! implemented here; this module is native-only.
83
84use std::net::SocketAddrV4;
85
86use async_trait::async_trait;
87use futures::StreamExt;
88
89use crate::error::{Error, Result};
90
91/// Length in bytes of an at9p content identifier (BLAKE3-512 digest).
92pub const CID512_LEN: usize = 64;
93
94/// Width in bytes of the fixed-width rendezvous k-index.
95pub const RENDEZVOUS_K_INDEX_LEN: usize = 4;
96
97/// Width in bytes of the rendezvous epoch.
98pub const RENDEZVOUS_EPOCH_LEN: usize = 8;
99
100const RENDEZVOUS_CONTEXT: &str = "hyprstream.at9p.mainline-locator.rendezvous.v1";
101
102/// A full-width at9p content identifier (64-byte BLAKE3-512 CID).
103///
104/// This is the only key type the locator's public API accepts. The 20-byte
105/// BEP5 infohash derived from it never leaves this module (R2).
106#[derive(Clone, Copy, PartialEq, Eq, Hash)]
107pub struct Cid512([u8; CID512_LEN]);
108
109impl Cid512 {
110    /// Construct from a full 64-byte digest.
111    pub fn from_bytes(bytes: [u8; CID512_LEN]) -> Self {
112        Self(bytes)
113    }
114
115    /// Construct from a slice, rejecting anything that is not exactly
116    /// 64 bytes. There is deliberately no constructor from shorter input:
117    /// callers must hold the full-width CID.
118    pub fn from_slice(bytes: &[u8]) -> Result<Self> {
119        let arr: [u8; CID512_LEN] = bytes.try_into().map_err(|_| {
120            Error::other(format!(
121                "cid512 must be {CID512_LEN} bytes, got {}",
122                bytes.len()
123            ))
124        })?;
125        Ok(Self(arr))
126    }
127
128    /// The full 64-byte digest.
129    pub fn as_bytes(&self) -> &[u8; CID512_LEN] {
130        &self.0
131    }
132}
133
134impl std::fmt::Debug for Cid512 {
135    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136        write!(f, "Cid512({})", hex::encode(self.0))
137    }
138}
139
140/// Fixed-width rendezvous parameters folded into the CID-keyed lookup.
141///
142/// `k_index` is encoded as big-endian `u32` and `epoch` as big-endian `u64`
143/// when deriving the internal 64-byte rendezvous key. There is no string-name
144/// path in this API (R1).
145#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
146pub struct RendezvousKey {
147    k_index: u32,
148    epoch: u64,
149}
150
151impl RendezvousKey {
152    /// Default rendezvous slot for the current minimal C2 API surface.
153    ///
154    /// Later scoring/parallel-fetch work (#891) can fan out across additional
155    /// fixed-width `k_index` values without changing the DHT key model.
156    pub const DEFAULT: Self = Self {
157        k_index: 0,
158        epoch: 0,
159    };
160
161    /// Construct a rendezvous slot from fixed-width integer fields.
162    pub const fn new(k_index: u32, epoch: u64) -> Self {
163        Self { k_index, epoch }
164    }
165
166    /// The fixed-width k-index.
167    pub const fn k_index(&self) -> u32 {
168        self.k_index
169    }
170
171    /// The rendezvous epoch.
172    pub const fn epoch(&self) -> u64 {
173        self.epoch
174    }
175
176    fn k_index_be_bytes(&self) -> [u8; RENDEZVOUS_K_INDEX_LEN] {
177        self.k_index.to_be_bytes()
178    }
179
180    fn epoch_be_bytes(&self) -> [u8; RENDEZVOUS_EPOCH_LEN] {
181        self.epoch.to_be_bytes()
182    }
183}
184
185/// Full-width derived rendezvous key used internally before BEP5 truncation.
186#[derive(Clone, Copy, PartialEq, Eq, Hash)]
187struct RendezvousCid512([u8; CID512_LEN]);
188
189fn rendezvous_cid512(cid: &Cid512, key: RendezvousKey) -> RendezvousCid512 {
190    let mut hasher = blake3::Hasher::new();
191    hasher.update(RENDEZVOUS_CONTEXT.as_bytes());
192    hasher.update(cid.as_bytes());
193    hasher.update(&key.k_index_be_bytes());
194    hasher.update(&key.epoch_be_bytes());
195
196    let mut out = [0u8; CID512_LEN];
197    hasher.finalize_xof().fill(&mut out);
198    RendezvousCid512(out)
199}
200
201/// Candidate peer contact returned by the untrusted mainline locator.
202///
203/// This is a reachability hint only. It intentionally carries no trust,
204/// verification, or dial-authority marker; callers must fetch candidate
205/// content and verify it against the full [`Cid512`] through the GATE pipeline
206/// before deriving authority or dialing based on the result.
207#[derive(Clone, Debug, PartialEq, Eq, Hash)]
208pub struct PeerContact {
209    socket_addr: SocketAddrV4,
210}
211
212impl PeerContact {
213    /// Wrap a DHT-provided IPv4 socket address as an untrusted candidate.
214    pub fn untrusted(socket_addr: SocketAddrV4) -> Self {
215        Self { socket_addr }
216    }
217
218    /// The candidate IPv4 socket address advertised in mainline.
219    ///
220    /// This address is still untrusted; this accessor is for fetch/scoring
221    /// plumbing, not direct admission.
222    pub fn socket_addr(&self) -> SocketAddrV4 {
223        self.socket_addr
224    }
225}
226
227/// v1 decision on the BEP44 deterministic-mailbox hint channel (#879 §6.1,
228/// Q3 — resolved by story C4 / #892).
229///
230/// Records whether the public-by-construction BEP44 mailbox (§6.1 option 2)
231/// ships for v1. This is a *decision marker*, not a runtime switch: it exists
232/// so the rationale is discoverable from the compiled artifact and reviewers
233/// can see which branch of R7 binds.
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub enum MailboxHintDecision {
236    /// Ship BEP5 `announce_peer` / `get_peers` only (§6.1 option 1, "chosen").
237    /// The deterministic mailbox is deferred. R7's add-only rule nonetheless
238    /// binds the moment any future channel feeds [`LookupHints`].
239    Bep5Only,
240
241    /// Deterministic mailbox shipped; its values flow through [`LookupHints`]
242    /// and are add-only by construction (R7).
243    Mailbox,
244}
245
246/// The v1 mailbox decision: **BEP5-only** (#879 §6.1 names option 1 "chosen").
247///
248/// See the module-level "Add-only hints" doc for the rationale and for why
249/// R7 binds regardless of this value.
250pub const V1_MAILBOX_HINT_CHANNEL: MailboxHintDecision = MailboxHintDecision::Bep5Only;
251
252/// Maximum number of out-of-band rendezvous buckets one lookup will scan in
253/// addition to the canonical key. Bounds DHT work: a malicious hint source
254/// (untrusted PDS record, relay bridge, mailbox) cannot amplify a single
255/// [`MainlineLocator::providers_with_hints`] into an unbounded fan-out.
256pub const MAX_HINTED_RENDEZVOUS: usize = 8;
257
258/// Maximum number of out-of-band candidate peers one lookup will union in.
259pub const MAX_HINTED_PEERS: usize = 64;
260
261/// Maximum total candidate peers a single lookup will return (canonical scan
262/// unioned with hints, post-dedup). Keeps a flooded provider list from being
263/// amplified into unbounded downstream fetch work.
264pub const MAX_LOCATOR_RESULTS: usize = 256;
265
266/// Add-only accumulator of out-of-band lookup hints (review rule R7).
267///
268/// Hints supplement — never replace — the watermark-anchored BEP5 scan. This
269/// type is the structural home for the BEP44 deterministic-mailbox channel
270/// when it ships (see [`V1_MAILBOX_HINT_CHANNEL`]); today it is fed by any
271/// out-of-band source (PDS record, relay bridge, configuration).
272///
273/// **Provably add-only.** The API exposes [`LookupHints::add_rendezvous`] and
274/// [`LookupHints::add_peer`] and nothing that removes, replaces, or clears
275/// entries. [`MainlineLocator::providers_with_hints`] always performs the
276/// scan at the canonical rendezvous key and then unions these hints in — a
277/// hint can enlarge the candidate set, never prune it or skip the scan (A14).
278///
279/// **Bounded (DoS).** Hints often originate from untrusted sources, so the
280/// accumulator caps both rendezvous buckets ([`MAX_HINTED_RENDEZVOUS`]) and
281/// peers ([`MAX_HINTED_PEERS`]), dedupes by value, and the locator caps total
282/// returned candidates ([`MAX_LOCATOR_RESULTS`]). An attacker who feeds a huge
283/// hint set can do no more than a fixed amount of extra DHT/network work.
284#[derive(Default, Clone, Debug)]
285pub struct LookupHints {
286    extra_rendezvous: Vec<RendezvousKey>,
287    extra_peers: Vec<PeerContact>,
288}
289
290impl LookupHints {
291    /// Empty hint set.
292    pub fn new() -> Self {
293        Self::default()
294    }
295
296    /// Add an additional rendezvous bucket to scan, beyond the canonical key.
297    /// Add-only (R7): there is no corresponding remove.
298    ///
299    /// Returns `false` (without storing) if `key` is a duplicate or the
300    /// [`MAX_HINTED_RENDEZVOUS`] cap is reached — bounding DHT work from
301    /// untrusted hint sources. The set otherwise never shrinks.
302    pub fn add_rendezvous(&mut self, key: RendezvousKey) -> bool {
303        if self.extra_rendezvous.len() >= MAX_HINTED_RENDEZVOUS
304            || self.extra_rendezvous.contains(&key)
305        {
306            return false;
307        }
308        self.extra_rendezvous.push(key);
309        true
310    }
311
312    /// Add a candidate peer discovered out-of-band (e.g. from a PDS record).
313    /// Add-only (R7): there is no corresponding remove.
314    ///
315    /// Returns `false` (without storing) if `peer` is a duplicate or the
316    /// [`MAX_HINTED_PEERS`] cap is reached — bounding downstream fetch work.
317    pub fn add_peer(&mut self, peer: PeerContact) -> bool {
318        if self.extra_peers.len() >= MAX_HINTED_PEERS || self.extra_peers.contains(&peer) {
319            return false;
320        }
321        self.extra_peers.push(peer);
322        true
323    }
324
325    /// Additional rendezvous buckets to scan (in insertion order, deduped).
326    pub fn extra_rendezvous(&self) -> &[RendezvousKey] {
327        &self.extra_rendezvous
328    }
329
330    /// Additional candidate peers to union in (in insertion order, deduped).
331    pub fn extra_peers(&self) -> &[PeerContact] {
332        &self.extra_peers
333    }
334
335    /// Total number of hints accumulated.
336    pub fn len(&self) -> usize {
337        self.extra_rendezvous.len() + self.extra_peers.len()
338    }
339
340    /// Whether the set is empty.
341    pub fn is_empty(&self) -> bool {
342        self.extra_rendezvous.is_empty() && self.extra_peers.is_empty()
343    }
344}
345
346/// TRUNC20: derive the 20-byte BEP5 infohash for a derived rendezvous key.
347///
348/// **This is the single truncation site in the codebase** (R2). The result
349/// is passed straight into the BEP5 client and is never returned to callers.
350fn rendezvous_infohash(cid: &Cid512, key: RendezvousKey) -> [u8; 20] {
351    let rendezvous = rendezvous_cid512(cid, key);
352    let mut infohash = [0u8; 20];
353    infohash.copy_from_slice(&rendezvous.0[..20]);
354    infohash
355}
356
357/// Minimal BEP5 operations the locator needs, abstracted so unit tests never
358/// touch the real DHT (and so C2+ can inject scoring/relay variants).
359#[async_trait]
360trait Bep5Client: Send + Sync {
361    /// Announce this process as a provider for `info_hash`.
362    ///
363    /// `port: None` lets remote nodes infer the port (BEP5 implied_port).
364    async fn announce(&self, info_hash: [u8; 20], port: Option<u16>) -> Result<()>;
365
366    /// Collect currently-announced providers for `info_hash`.
367    async fn get_peers(&self, info_hash: [u8; 20]) -> Result<Vec<SocketAddrV4>>;
368}
369
370/// Real BEP5 client backed by [`mainline::async_dht::AsyncDht`].
371///
372/// Runs in client mode (queries + stores, no inbound routing duties). The
373/// underlying crate drives its own UDP socket thread; the async wrapper is
374/// runtime-agnostic and works under tokio.
375pub struct MainlineBep5 {
376    dht: mainline::async_dht::AsyncDht,
377}
378
379impl MainlineBep5 {
380    /// Bootstrap a client-mode node against the default mainline routers.
381    ///
382    /// This *does* touch the network — never call it from unit tests.
383    pub fn new() -> Result<Self> {
384        let dht = mainline::Dht::builder()
385            .build()
386            .map_err(|e| Error::other(format!("mainline DHT bootstrap failed: {e}")))?;
387        Ok(Self {
388            dht: dht.as_async(),
389        })
390    }
391}
392
393#[async_trait]
394impl Bep5Client for MainlineBep5 {
395    async fn announce(&self, info_hash: [u8; 20], port: Option<u16>) -> Result<()> {
396        self.dht
397            .announce_peer(mainline::Id::from(info_hash), port)
398            .await
399            .map_err(|e| Error::other(format!("mainline announce_peer failed: {e}")))?;
400        Ok(())
401    }
402
403    async fn get_peers(&self, info_hash: [u8; 20]) -> Result<Vec<SocketAddrV4>> {
404        let mut stream = self.dht.get_peers(mainline::Id::from(info_hash));
405        let mut peers = Vec::new();
406        while let Some(batch) = stream.next().await {
407            peers.extend(batch);
408        }
409        Ok(peers)
410    }
411}
412
413/// The at9p mainline locator: full-width CID in, candidate peers out.
414///
415/// Provider scoring, parallel fetch, and size caps are C3 (#891).
416pub struct MainlineLocator {
417    client: Box<dyn Bep5Client>,
418}
419
420impl MainlineLocator {
421    /// Locator over the real mainline DHT (network-touching).
422    pub fn new() -> Result<Self> {
423        Ok(Self::with_client(Box::new(MainlineBep5::new()?)))
424    }
425
426    /// Locator over an injected BEP5 client (tests, relay bridges).
427    fn with_client(client: Box<dyn Bep5Client>) -> Self {
428        Self { client }
429    }
430
431    /// Announce this node as a provider for `cid`.
432    pub async fn announce(&self, cid: &Cid512, port: Option<u16>) -> Result<()> {
433        self.announce_at(cid, RendezvousKey::DEFAULT, port).await
434    }
435
436    /// Announce this node as a provider for a specific k-derived rendezvous.
437    pub async fn announce_at(
438        &self,
439        cid: &Cid512,
440        key: RendezvousKey,
441        port: Option<u16>,
442    ) -> Result<()> {
443        self.client
444            .announce(rendezvous_infohash(cid, key), port)
445            .await
446    }
447
448    /// Look up candidate providers for `cid`.
449    ///
450    /// Returned contacts are **untrusted hints**: anyone can announce on any
451    /// infohash. Callers must verify fetched content against the full
452    /// `cid` via the GATE pipeline before deriving anything from it.
453    pub async fn providers(&self, cid: &Cid512) -> Result<Vec<PeerContact>> {
454        self.providers_at(cid, RendezvousKey::DEFAULT).await
455    }
456
457    /// Look up candidate providers for a specific k-derived rendezvous.
458    ///
459    /// Results remain untrusted hints; the `key` only selects the rendezvous
460    /// bucket and does not add authority.
461    pub async fn providers_at(&self, cid: &Cid512, key: RendezvousKey) -> Result<Vec<PeerContact>> {
462        Ok(self
463            .client
464            .get_peers(rendezvous_infohash(cid, key))
465            .await?
466            .into_iter()
467            .map(PeerContact::untrusted)
468            .collect())
469    }
470
471    /// Look up candidate providers, unioning in add-only [`LookupHints`] (R7).
472    ///
473    /// The watermark-anchored BEP5 scan at `key` is **always** performed; each
474    /// rendezvous bucket in `hints` is scanned as well (capped by
475    /// [`MAX_HINTED_RENDEZVOUS`]), and the hint peers are appended (capped by
476    /// [`MAX_HINTED_PEERS`]). `hints` may only enlarge the candidate set —
477    /// there is no parameter and no code path that prunes, replaces, or skips
478    /// the scan (A14). Results are deduped and capped at
479    /// [`MAX_LOCATOR_RESULTS`], so untrusted hint input cannot amplify into
480    /// unbounded DHT/network work. Results remain untrusted: verification
481    /// against the full [`Cid512`] is the caller's job via the GATE pipeline.
482    pub async fn providers_with_hints(
483        &self,
484        cid: &Cid512,
485        key: RendezvousKey,
486        hints: &LookupHints,
487    ) -> Result<Vec<PeerContact>> {
488        // The canonical scan is unconditional — a hint can never suppress it.
489        let mut found = self.providers_at(cid, key).await?;
490
491        // Additional rendezvous buckets from hints: scanned, not trusted, and
492        // strictly best-effort. A hint bucket lookup that errors must never
493        // discard the canonical results already in `found` — propagating `?`
494        // here would let an untrusted hint source induce a failure that
495        // suppresses the whole canonical scan (an A14 availability downgrade
496        // dressed as an error), contradicting R7. Errors are dropped; canonical
497        // and every other hint result survive.
498        // `LookupHints` already bounded this to MAX_HINTED_RENDEZVOUS.
499        for extra in hints.extra_rendezvous() {
500            if let Ok(peers) = self.providers_at(cid, *extra).await {
501                found.extend(peers);
502            }
503        }
504
505        // Out-of-band peer contacts: unioned in verbatim, still untrusted.
506        // `LookupHints` already bounded this to MAX_HINTED_PEERS.
507        found.extend(hints.extra_peers().iter().cloned());
508
509        // Dedup by value and cap total candidates so an attacker flooding the
510        // DHT/hints cannot amplify into unbounded downstream fetch work.
511        dedup_and_cap(&mut found, MAX_LOCATOR_RESULTS);
512
513        Ok(found)
514    }
515}
516
517/// Deduplicate `peers` by value (preserving first-seen order) and truncate to
518/// `cap`. Keeps a flooded provider list bounded for callers.
519fn dedup_and_cap(peers: &mut Vec<PeerContact>, cap: usize) {
520    let mut seen = std::collections::HashSet::new();
521    peers.retain(|p| seen.insert(p.clone()));
522    if peers.len() > cap {
523        peers.truncate(cap);
524    }
525}
526
527#[cfg(test)]
528#[allow(clippy::unwrap_used, clippy::expect_used)]
529mod tests {
530    use super::*;
531    use parking_lot::Mutex;
532    use std::collections::HashMap;
533    use std::net::Ipv4Addr;
534
535    use std::sync::Arc;
536
537    /// In-memory BEP5 fake: a HashMap keyed by the 20-byte infohash, exactly
538    /// like the real DHT's keyspace. No sockets, no network. Clone shares
539    /// state so tests can inspect what the locator sent.
540    #[derive(Default, Clone)]
541    struct MockBep5 {
542        table: Arc<Mutex<HashMap<[u8; 20], Vec<SocketAddrV4>>>>,
543        seen_infohashes: Arc<Mutex<Vec<[u8; 20]>>>,
544    }
545
546    #[async_trait]
547    impl Bep5Client for MockBep5 {
548        async fn announce(&self, info_hash: [u8; 20], port: Option<u16>) -> Result<()> {
549            self.seen_infohashes.lock().push(info_hash);
550            let addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, port.unwrap_or(6881));
551            self.table.lock().entry(info_hash).or_default().push(addr);
552            Ok(())
553        }
554
555        async fn get_peers(&self, info_hash: [u8; 20]) -> Result<Vec<SocketAddrV4>> {
556            self.seen_infohashes.lock().push(info_hash);
557            Ok(self
558                .table
559                .lock()
560                .get(&info_hash)
561                .cloned()
562                .unwrap_or_default())
563        }
564    }
565
566    fn cid(fill: u8) -> Cid512 {
567        Cid512::from_bytes([fill; CID512_LEN])
568    }
569
570    #[tokio::test]
571    async fn announce_then_providers_roundtrip() {
572        let locator = MainlineLocator::with_client(Box::<MockBep5>::default());
573        let id = cid(0xAB);
574
575        locator.announce(&id, Some(4242)).await.unwrap();
576        let peers = locator.providers(&id).await.unwrap();
577
578        assert_eq!(
579            peers,
580            vec![PeerContact::untrusted(SocketAddrV4::new(
581                Ipv4Addr::LOCALHOST,
582                4242
583            ))]
584        );
585    }
586
587    #[tokio::test]
588    async fn providers_of_unannounced_cid_is_empty() {
589        let locator = MainlineLocator::with_client(Box::<MockBep5>::default());
590        assert!(locator.providers(&cid(0x01)).await.unwrap().is_empty());
591    }
592
593    #[tokio::test]
594    async fn rendezvous_derivation_is_deterministic_for_same_cid_epoch_and_k() {
595        let id = cid(0xAB);
596        let key = RendezvousKey::new(7, 42);
597
598        assert_eq!(rendezvous_infohash(&id, key), rendezvous_infohash(&id, key));
599        assert_eq!(rendezvous_cid512(&id, key).0.len(), CID512_LEN);
600    }
601
602    #[test]
603    fn k_index_and_epoch_are_fixed_width_big_endian() {
604        let key = RendezvousKey::new(0x0102_0304, 0x0102_0304_0506_0708);
605
606        assert_eq!(key.k_index_be_bytes(), [0x01, 0x02, 0x03, 0x04]);
607        assert_eq!(
608            key.epoch_be_bytes(),
609            [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]
610        );
611        assert_eq!(key.k_index_be_bytes().len(), RENDEZVOUS_K_INDEX_LEN);
612        assert_eq!(key.epoch_be_bytes().len(), RENDEZVOUS_EPOCH_LEN);
613    }
614
615    #[tokio::test]
616    async fn truncation_is_internal_and_derived_from_full_rendezvous_key() {
617        let mock = MockBep5::default();
618        let locator = MainlineLocator::with_client(Box::new(mock.clone()));
619
620        let mut bytes = [0u8; CID512_LEN];
621        for (i, b) in bytes.iter_mut().enumerate() {
622            *b = i as u8;
623        }
624        let id = Cid512::from_bytes(bytes);
625        let key = RendezvousKey::new(1, 9);
626
627        locator.announce_at(&id, key, None).await.unwrap();
628
629        // The BEP5 client only sees the private 20-byte projection of the
630        // full-width derived rendezvous key; public locator APIs never expose it.
631        let seen = mock.seen_infohashes.lock().clone();
632        assert_eq!(seen.len(), 1);
633        assert_eq!(seen[0], rendezvous_infohash(&id, key));
634        assert_eq!(seen[0].len(), 20);
635    }
636
637    #[tokio::test]
638    async fn k_index_and_epoch_select_distinct_rendezvous_buckets() {
639        let locator = MainlineLocator::with_client(Box::<MockBep5>::default());
640        let id = cid(0x55);
641
642        locator
643            .announce_at(&id, RendezvousKey::new(0, 7), Some(1111))
644            .await
645            .unwrap();
646
647        assert_eq!(
648            locator
649                .providers_at(&id, RendezvousKey::new(0, 7))
650                .await
651                .unwrap()
652                .len(),
653            1
654        );
655        assert!(locator
656            .providers_at(&id, RendezvousKey::new(1, 7))
657            .await
658            .unwrap()
659            .is_empty());
660        assert!(locator
661            .providers_at(&id, RendezvousKey::new(0, 8))
662            .await
663            .unwrap()
664            .is_empty());
665    }
666
667    #[test]
668    fn peer_contact_carries_only_untrusted_candidate_contact_info() {
669        let addr = SocketAddrV4::new(Ipv4Addr::new(192, 0, 2, 10), 6881);
670        let contact = PeerContact::untrusted(addr);
671
672        assert_eq!(contact.socket_addr(), addr);
673    }
674
675    #[test]
676    fn cid512_rejects_wrong_lengths() {
677        assert!(Cid512::from_slice(&[0u8; 20]).is_err());
678        assert!(Cid512::from_slice(&[0u8; 32]).is_err());
679        assert!(Cid512::from_slice(&[0u8; 63]).is_err());
680        assert!(Cid512::from_slice(&[0u8; 64]).is_ok());
681        assert!(Cid512::from_slice(&[0u8; 65]).is_err());
682    }
683
684    // ----- R1 enforcement (story C4 / #892) --------------------------------
685    //
686    // The "no string-name path in the public locator API" invariant is enforced
687    // structurally by `tests/locator_r1_invariants.rs`, which parses THIS
688    // module with `syn` and walks every public item signature (functions,
689    // inherent/trait methods, multi-line + generic forms), failing on any
690    // string-like public parameter or string-conversion impl on Cid512. A grep
691    // over single-line signatures is bypassable; an AST walk is not.
692
693    #[test]
694    fn r1_cid512_is_constructible_only_from_full_bytes() {
695        // Positive compile-time check: the only constructors take bytes.
696        let _ = Cid512::from_bytes([0xAB; CID512_LEN]);
697        let _ = Cid512::from_slice(&[0xCD; CID512_LEN]).unwrap();
698    }
699
700    // ----- R7 add-only hints (story C4 / #892) -----------------------------
701
702    #[test]
703    fn v1_mailbox_decision_is_recorded_and_bep5_only() {
704        // Q3 decision: ship BEP5-only for v1; the mailbox is deferred.
705        assert_eq!(V1_MAILBOX_HINT_CHANNEL, MailboxHintDecision::Bep5Only);
706    }
707
708    #[test]
709    fn lookup_hints_starts_empty_and_grows_only() {
710        let mut hints = LookupHints::new();
711        assert!(hints.is_empty());
712        assert_eq!(hints.len(), 0);
713
714        hints.add_rendezvous(RendezvousKey::new(1, 0));
715        assert!(!hints.is_empty());
716        assert_eq!(hints.len(), 1);
717
718        hints.add_peer(PeerContact::untrusted(SocketAddrV4::new(
719            Ipv4Addr::LOCALHOST,
720            7000,
721        )));
722        assert_eq!(hints.len(), 2);
723
724        assert_eq!(hints.extra_rendezvous(), &[RendezvousKey::new(1, 0)]);
725        assert_eq!(
726            hints.extra_peers(),
727            &[PeerContact::untrusted(SocketAddrV4::new(
728                Ipv4Addr::LOCALHOST,
729                7000
730            ))]
731        );
732    }
733
734    /// R7 load-bearing proof: hints can only ADD candidates. The canonical
735    /// BEP5 scan is always performed and its results always survive — a hint
736    /// set, however large, can never prune them.
737    #[tokio::test]
738    async fn r7_hints_are_add_only_scan_results_survive() {
739        let mock = MockBep5::default();
740        let locator = MainlineLocator::with_client(Box::new(mock.clone()));
741        let id = cid(0x77);
742        let canonical = RendezvousKey::DEFAULT;
743        let extra = RendezvousKey::new(2, 0);
744
745        // Seed the canonical bucket with a real provider.
746        locator
747            .announce_at(&id, canonical, Some(4242))
748            .await
749            .unwrap();
750        // Seed the extra hinted bucket with a different provider.
751        locator.announce_at(&id, extra, Some(5353)).await.unwrap();
752
753        let mut hints = LookupHints::new();
754        hints.add_rendezvous(extra);
755        hints.add_peer(PeerContact::untrusted(SocketAddrV4::new(
756            Ipv4Addr::new(192, 0, 2, 99),
757            9999,
758        )));
759
760        let found = locator
761            .providers_with_hints(&id, canonical, &hints)
762            .await
763            .unwrap();
764
765        // Canonical scan result survives (never pruned by hints):
766        let canonical_addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 4242);
767        assert!(
768            found.iter().any(|p| p.socket_addr() == canonical_addr),
769            "R7: canonical scan result must survive hints (no prune)"
770        );
771        // Hinted rendezvous bucket was scanned and unioned in:
772        assert!(
773            found
774                .iter()
775                .any(|p| p.socket_addr() == SocketAddrV4::new(Ipv4Addr::LOCALHOST, 5353)),
776            "R7: hinted rendezvous bucket must be unioned in (add-only)"
777        );
778        // Out-of-band peer hint was unioned in:
779        assert!(
780            found
781                .iter()
782                .any(|p| p.socket_addr() == SocketAddrV4::new(Ipv4Addr::new(192, 0, 2, 99), 9999)),
783            "R7: hinted peer must be unioned in (add-only)"
784        );
785    }
786
787    /// R7 proof: with no hints, the hinted path is identical to the plain scan
788    /// — confirming hints are purely additive.
789    #[tokio::test]
790    async fn r7_empty_hints_equal_plain_scan() {
791        let mock = MockBep5::default();
792        let locator = MainlineLocator::with_client(Box::new(mock.clone()));
793        let id = cid(0x33);
794        locator.announce(&id, Some(8080)).await.unwrap();
795
796        let plain = locator.providers(&id).await.unwrap();
797        let with_hints = locator
798            .providers_with_hints(&id, RendezvousKey::DEFAULT, &LookupHints::new())
799            .await
800            .unwrap();
801
802        assert_eq!(plain, with_hints);
803    }
804
805    /// R7 proof: a hint set cannot suppress the scan even when the hint points
806    /// at a *different* rendezvous bucket that has no providers. The canonical
807    /// scan still returns its providers — the misleading hint prunes nothing.
808    #[tokio::test]
809    async fn r7_misleading_hint_cannot_prune_scan() {
810        let mock = MockBep5::default();
811        let locator = MainlineLocator::with_client(Box::new(mock.clone()));
812        let id = cid(0x44);
813        let canonical = RendezvousKey::DEFAULT;
814
815        // Real provider at the canonical bucket.
816        locator
817            .announce_at(&id, canonical, Some(1234))
818            .await
819            .unwrap();
820
821        // Misleading hint directing attention elsewhere (empty bucket).
822        let mut hints = LookupHints::new();
823        hints.add_rendezvous(RendezvousKey::new(9, 9));
824
825        let found = locator
826            .providers_with_hints(&id, canonical, &hints)
827            .await
828            .unwrap();
829
830        // The real canonical provider is still returned despite the misleading
831        // hint — A14 is excluded: a hint cannot skip the watermark scan.
832        assert!(
833            found
834                .iter()
835                .any(|p| p.socket_addr() == SocketAddrV4::new(Ipv4Addr::LOCALHOST, 1234)),
836            "R7/A14: misleading hint must not prune the canonical scan"
837        );
838    }
839
840    // ----- R7 DoS bounds (review of #1000) ---------------------------------
841
842    /// R7 + DoS: add-only still holds, but duplicates are dropped and the
843    /// rendezvous/peer caps are enforced so untrusted hint input cannot
844    /// amplify into unbounded DHT/network work.
845    #[tokio::test]
846    async fn r7_hints_are_bounded_and_deduped() {
847        // Duplicate rendezvous hint: second add returns false, stored once.
848        let mut hints = LookupHints::new();
849        assert!(hints.add_rendezvous(RendezvousKey::new(1, 0)));
850        assert!(!hints.add_rendezvous(RendezvousKey::new(1, 0)));
851        assert_eq!(hints.extra_rendezvous().len(), 1);
852
853        // Duplicate peer hint: same — deduped, add returns false.
854        let peer = PeerContact::untrusted(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 1));
855        assert!(hints.add_peer(peer.clone()));
856        assert!(!hints.add_peer(peer));
857        assert_eq!(hints.extra_peers().len(), 1);
858
859        // Rendezvous cap: extras beyond MAX_HINTED_RENDEZVOUS are refused.
860        for i in 1..(MAX_HINTED_RENDEZVOUS as u32) + 5 {
861            hints.add_rendezvous(RendezvousKey::new(i.wrapping_add(10), 0));
862        }
863        assert_eq!(
864            hints.extra_rendezvous().len(),
865            MAX_HINTED_RENDEZVOUS,
866            "rendezvous hints must be capped at MAX_HINTED_RENDEZVOUS"
867        );
868
869        // Peer cap: extras beyond MAX_HINTED_PEERS are refused.
870        for port in 100..(MAX_HINTED_PEERS as u16) + 200 {
871            hints.add_peer(PeerContact::untrusted(SocketAddrV4::new(
872                Ipv4Addr::LOCALHOST,
873                port,
874            )));
875        }
876        assert_eq!(
877            hints.extra_peers().len(),
878            MAX_HINTED_PEERS,
879            "peer hints must be capped at MAX_HINTED_PEERS"
880        );
881    }
882
883    /// R7 + DoS: the locator dedupes and caps the final candidate list so a
884    /// flooded provider list cannot amplify into unbounded fetch work, while
885    /// the add-only property (canonical scan always present) still holds.
886    #[tokio::test]
887    async fn r7_locator_dedupes_and_caps_results() {
888        let mock = MockBep5::default();
889        let locator = MainlineLocator::with_client(Box::new(mock.clone()));
890        let id = cid(0x88);
891        let canonical = RendezvousKey::DEFAULT;
892
893        // Canonical bucket returns one real provider.
894        locator
895            .announce_at(&id, canonical, Some(4242))
896            .await
897            .unwrap();
898
899        // Hint the SAME peer the scan already returns: result must be deduped.
900        let mut hints = LookupHints::new();
901        hints.add_peer(PeerContact::untrusted(SocketAddrV4::new(
902            Ipv4Addr::LOCALHOST,
903            4242,
904        )));
905
906        let found = locator
907            .providers_with_hints(&id, canonical, &hints)
908            .await
909            .unwrap();
910        assert_eq!(
911            found
912                .iter()
913                .filter(|p| p.socket_addr().port() == 4242)
914                .count(),
915            1,
916            "duplicate candidate must be deduped"
917        );
918
919        // Cap: flood well past MAX_LOCATOR_RESULTS via hinted peers and confirm
920        // the returned set is bounded.
921        let mut flood = LookupHints::new();
922        for port in 0..(MAX_LOCATOR_RESULTS as u16) * 4 {
923            flood.add_peer(PeerContact::untrusted(SocketAddrV4::new(
924                Ipv4Addr::new(203, 0, 113, 1),
925                port,
926            )));
927        }
928        let found = locator
929            .providers_with_hints(&id, canonical, &flood)
930            .await
931            .unwrap();
932        assert!(
933            found.len() <= MAX_LOCATOR_RESULTS,
934            "returned candidates must be capped at MAX_LOCATOR_RESULTS, got {}",
935            found.len()
936        );
937        // Canonical provider still present — add-only holds through bounding.
938        assert!(found
939            .iter()
940            .any(|p| p.socket_addr() == SocketAddrV4::new(Ipv4Addr::LOCALHOST, 4242)));
941    }
942
943    /// BEP5 fake that succeeds for the canonical bucket but returns `Err` for a
944    /// designated (attacker-chosen) infohash. Models an untrusted hint source
945    /// whose bucket lookup fails at the network layer.
946    #[derive(Clone)]
947    struct FailingBucketBep5 {
948        table: Arc<Mutex<HashMap<[u8; 20], Vec<SocketAddrV4>>>>,
949        fail_on: [u8; 20],
950    }
951
952    #[async_trait]
953    impl Bep5Client for FailingBucketBep5 {
954        async fn announce(&self, info_hash: [u8; 20], port: Option<u16>) -> Result<()> {
955            let addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, port.unwrap_or(6881));
956            self.table.lock().entry(info_hash).or_default().push(addr);
957            Ok(())
958        }
959
960        async fn get_peers(&self, info_hash: [u8; 20]) -> Result<Vec<SocketAddrV4>> {
961            if info_hash == self.fail_on {
962                return Err(Error::Dht("simulated hinted-bucket failure".into()));
963            }
964            Ok(self
965                .table
966                .lock()
967                .get(&info_hash)
968                .cloned()
969                .unwrap_or_default())
970        }
971    }
972
973    /// R7 regression: a hinted-bucket lookup that *errors* must not discard the
974    /// canonical scan results. Best-effort hint scans; the canonical providers
975    /// survive an untrusted hint that induces a failure (A14 downgrade excluded).
976    #[tokio::test]
977    async fn r7_failing_hint_bucket_does_not_discard_canonical() {
978        let id = cid(0x99);
979        let canonical = RendezvousKey::DEFAULT;
980        let bad = RendezvousKey::new(3, 1);
981
982        // Seed the canonical bucket with a real provider first (via a plain mock
983        // announce path), then reuse its table under the failing wrapper.
984        let table: Arc<Mutex<HashMap<[u8; 20], Vec<SocketAddrV4>>>> = Arc::default();
985        table.lock().insert(
986            rendezvous_infohash(&id, canonical),
987            vec![SocketAddrV4::new(Ipv4Addr::LOCALHOST, 4242)],
988        );
989
990        let mock = FailingBucketBep5 {
991            table,
992            fail_on: rendezvous_infohash(&id, bad),
993        };
994        let locator = MainlineLocator::with_client(Box::new(mock));
995
996        let mut hints = LookupHints::new();
997        hints.add_rendezvous(bad);
998
999        let found = locator
1000            .providers_with_hints(&id, canonical, &hints)
1001            .await
1002            .expect("a failing hint bucket must not make the whole lookup error");
1003
1004        assert!(
1005            found
1006                .iter()
1007                .any(|p| p.socket_addr() == SocketAddrV4::new(Ipv4Addr::LOCALHOST, 4242)),
1008            "R7: canonical scan result must survive a failing hinted-bucket lookup"
1009        );
1010    }
1011}