Skip to main content

dig_dht/
service.rs

1//! [`DhtService`] — the public handle that ties the routing table, provider store, transport, and
2//! iterative lookup into the four operations a DIG Node needs:
3//!
4//! - [`bootstrap`](DhtService::bootstrap) — seed the routing table from known peers (the dig-gossip
5//!   pool / relay introducer) + populate it with a self-lookup.
6//! - [`find_providers`](DhtService::find_providers) — "who holds this content?" → the provider
7//!   records (the node then fetches over the L7 peer RPC).
8//! - [`announce_provider`](DhtService::announce_provider) — "I hold this content" → PUT a provider
9//!   record at the `k` nodes closest to the content key (and locally), and remember to republish it.
10//! - [`find_node`](DhtService::find_node) — the `k` peers closest to a `peer_id` (routing primitive).
11//!
12//! Plus maintenance ([`republish`](DhtService::republish), [`refresh_buckets`](DhtService::refresh_buckets),
13//! [`gc`](DhtService::gc)) and the **serving side** ([`handle_request`](DhtService::handle_request))
14//! that answers inbound DHT RPCs from other nodes.
15//!
16//! ## Serving vs. querying
17//!
18//! A node is both a client and a server of the DHT. [`handle_request`](DhtService::handle_request)
19//! is the server: given an inbound [`DhtRequest`], it reads/writes the local routing table +
20//! provider store and returns the [`DhtResponse`]. The `find_*` / `announce_*` methods are the
21//! client: they run iterative lookups over the [`DhtTransport`]. A dig-node wires `handle_request`
22//! to inbound DHT streams and gives the service a transport that dials outbound.
23
24use std::sync::Arc;
25use std::time::{SystemTime, UNIX_EPOCH};
26
27use tokio::sync::Mutex;
28
29use dig_nat::PeerId;
30
31use crate::config::DhtConfig;
32use crate::content::ContentId;
33use crate::error::DhtError;
34use crate::key::Key;
35use crate::lookup::{iterative_find, QueryOutcome};
36use crate::provider_store::{ProviderStore, PutOutcome};
37use crate::record::{CandidateAddr, ProviderRecord};
38use crate::routing::{Contact, InsertOutcome, RoutingTable};
39use crate::transport::DhtTransport;
40use crate::wire::{DhtRequest, DhtResponse};
41
42/// A peer to bootstrap the routing table from — its `peer_id` and at least one candidate address.
43/// These come from the node's existing discovery (the dig-gossip peer pool / the relay introducer);
44/// the DHT crate takes them as input and never hard-depends on a live relay itself.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct BootstrapPeer {
47    /// The bootstrap peer's identity.
48    pub peer_id: PeerId,
49    /// Candidate addresses to reach it.
50    pub addresses: Vec<CandidateAddr>,
51}
52
53impl BootstrapPeer {
54    /// A bootstrap peer with a single direct address.
55    pub fn direct(peer_id: PeerId, host: impl Into<String>, port: u16) -> Self {
56        BootstrapPeer {
57            peer_id,
58            addresses: vec![CandidateAddr::direct(host, port)],
59        }
60    }
61
62    fn to_contact(&self) -> Contact {
63        Contact::new(&self.peer_id, self.addresses.clone())
64    }
65}
66
67/// The DHT service for one node. Cloneable-by-`Arc` internally; wrap in `Arc` to share between the
68/// serving task (inbound RPC) and querying callers.
69pub struct DhtService {
70    local_id: PeerId,
71    /// This node's own candidate addresses — put into provider records it announces so finders can
72    /// reach it.
73    local_addresses: Vec<CandidateAddr>,
74    config: DhtConfig,
75    routing: Arc<Mutex<RoutingTable>>,
76    providers: Arc<Mutex<ProviderStore>>,
77    transport: Arc<dyn DhtTransport>,
78}
79
80impl DhtService {
81    /// Create a service for the node identified by `local_id`, advertising `local_addresses` in the
82    /// provider records it announces, driving RPC over `transport`.
83    pub fn new(
84        local_id: PeerId,
85        local_addresses: Vec<CandidateAddr>,
86        config: DhtConfig,
87        transport: Arc<dyn DhtTransport>,
88    ) -> Self {
89        let routing = RoutingTable::new(&local_id, config.k);
90        let providers = ProviderStore::with_limits(config.provider_store_limits);
91        DhtService {
92            local_id,
93            local_addresses,
94            config,
95            routing: Arc::new(Mutex::new(routing)),
96            providers: Arc::new(Mutex::new(providers)),
97            transport,
98        }
99    }
100
101    /// This node's id.
102    pub fn local_id(&self) -> &PeerId {
103        &self.local_id
104    }
105
106    /// This node's own [`Contact`] (its id + advertised addresses) — the authenticated caller
107    /// identity supplied to the transport as the RPC `from`.
108    fn local_contact(&self) -> Contact {
109        Contact::new(&self.local_id, self.local_addresses.clone())
110    }
111
112    // ---- Bootstrap ---------------------------------------------------------------------------
113
114    /// Seed the routing table from `peers` and populate it by looking up this node's own id (the
115    /// canonical Kademlia bootstrap: a self-lookup fills the buckets around us). Returns the number
116    /// of distinct peers now known.
117    ///
118    /// Safe to call repeatedly (on reconnect / when new bootstrap peers arrive) — it merges, never
119    /// resets.
120    pub async fn bootstrap(&self, peers: &[BootstrapPeer]) -> Result<usize, DhtError> {
121        {
122            let mut rt = self.routing.lock().await;
123            for p in peers {
124                let _ = rt.insert(p.to_contact());
125            }
126        }
127        // Self-lookup: find the nodes closest to us to fill our buckets.
128        let self_key = Key::from_peer_id(&self.local_id);
129        let seeds: Vec<Contact> = peers.iter().map(|p| p.to_contact()).collect();
130        let result = self.run_lookup(self_key, seeds, false).await;
131        self.absorb_contacts(&result.closest).await;
132        Ok(self.routing.lock().await.len())
133    }
134
135    /// Add a single live peer to the routing table as it connects (e.g. a `dig-gossip`
136    /// `PoolEvent::PeerAdded`), WITHOUT the network round-trip [`bootstrap`](Self::bootstrap) does.
137    ///
138    /// This is the LIVE seam the one-shot pre-connect bootstrap cannot cover: in a freshly-formed
139    /// network the pool is empty when `bootstrap` runs, so routing stays empty and `find_providers`
140    /// finds nobody. Feeding each connected peer here populates routing as the pool fills, which is
141    /// what makes cross-node discovery work (#1574). Idempotent — re-adding a known peer merges its
142    /// address(es) via the routing table's insert policy; adding this node's own id is a no-op.
143    pub async fn add_peer(&self, peer_id: &PeerId, addresses: Vec<CandidateAddr>) {
144        let contact = Contact::new(peer_id, addresses);
145        let _ = self.routing.lock().await.insert(contact);
146    }
147
148    /// Remove a peer from the routing table as it leaves (a `dig-gossip` `PoolEvent::PeerRemoved`),
149    /// keeping routing accurate so lookups don't seed from a dead contact. Returns whether it was
150    /// present. `peer_id_hex` is the 64-char hex id (as carried on `Contact::provider_peer_id` /
151    /// [`PeerId::to_hex`]).
152    pub async fn remove_peer(&self, peer_id_hex: &str) -> bool {
153        self.routing.lock().await.remove(peer_id_hex)
154    }
155
156    // ---- Client operations -------------------------------------------------------------------
157
158    /// Find the `k` peers closest to `peer_id` (the routing primitive). Runs an iterative
159    /// `find_node` lookup and returns the converged closest contacts.
160    pub async fn find_node(&self, peer_id: &PeerId) -> Result<Vec<Contact>, DhtError> {
161        let target = Key::from_peer_id(peer_id);
162        let seeds = self.seed_contacts(&target).await;
163        if seeds.is_empty() {
164            return Err(DhtError::NoPeers);
165        }
166        let result = self.run_lookup(target, seeds, false).await;
167        self.absorb_contacts(&result.closest).await;
168        Ok(result.closest)
169    }
170
171    /// Find the providers of `content` — the peers holding it. Runs an iterative `find_providers`
172    /// lookup toward the content key, returning every live provider record collected (deduped by
173    /// provider). The node then connects to those providers over dig-nat and fetches via the L7 peer
174    /// RPC.
175    ///
176    /// Returns an empty vec (not an error) when the content simply has no known providers; returns
177    /// [`DhtError::NoPeers`] only when there is no one to ask (empty routing table + no bootstrap).
178    pub async fn find_providers(
179        &self,
180        content: &ContentId,
181    ) -> Result<Vec<ProviderRecord>, DhtError> {
182        let target = content.to_key();
183
184        // Local short-circuit: if we already hold providers for this key, include them.
185        let now = now_secs();
186        let mut local = self.providers.lock().await.get(&target.to_hex(), now);
187
188        let seeds = self.seed_contacts(&target).await;
189        if seeds.is_empty() {
190            // No peers to ask — return whatever we hold locally (possibly empty).
191            return Ok(local);
192        }
193        let result = self.run_lookup(target, seeds, true).await;
194        self.absorb_contacts(&result.closest).await;
195
196        // Merge local + discovered, dedup by provider, drop expired. Discovered records come
197        // straight off the wire from other peers' responses, bypassing `ProviderRecord::new`'s
198        // address cap — capped here before handing them back to our caller (SPEC §5.5, §14).
199        let mut discovered = result.providers;
200        for r in &mut discovered {
201            crate::record::sort_and_cap_addresses(&mut r.addresses);
202        }
203        local.extend(discovered);
204        let now = now_secs();
205        let mut seen = std::collections::HashSet::new();
206        local.retain(|r| !r.is_expired(now) && seen.insert(r.provider_peer_id.clone()));
207        Ok(local)
208    }
209
210    /// Announce that THIS node holds `content`: build a provider record (this node's `peer_id` +
211    /// addresses, expiring at `now + provider_ttl`), store it locally, remember to republish it, and
212    /// PUT it at the `k` nodes closest to the content key. Returns how many peers accepted the PUT.
213    ///
214    /// Called when the node's inventory gains content (a new capsule/root/resource it now serves).
215    pub async fn announce_provider(&self, content: &ContentId) -> Result<usize, DhtError> {
216        let target = content.to_key();
217        let record = self.build_local_record(&target);
218
219        // Store locally + remember for republish.
220        {
221            let mut ps = self.providers.lock().await;
222            ps.put(record.clone());
223            ps.mark_announced(target.to_hex());
224        }
225
226        // PUT at the k closest peers we can find.
227        let seeds = self.seed_contacts(&target).await;
228        if seeds.is_empty() {
229            // No peers yet — the local record stands; republish will re-attempt once bootstrapped.
230            return Ok(0);
231        }
232        let result = self.run_lookup(target, seeds, false).await;
233        self.absorb_contacts(&result.closest).await;
234        Ok(self.put_record_at(&result.closest, &record).await)
235    }
236
237    /// Stop announcing `content` (the node no longer holds it). The record ages out of the DHT via
238    /// TTL; we just stop republishing it. Returns whether it was being announced.
239    ///
240    /// This is the **passive** withdraw: it leaves this node's own local provider record in place
241    /// (it only expires with TTL) and merely stops re-publishing it, so a `find_providers` on this
242    /// node may still return self until the local record's TTL elapses. For an **immediate**
243    /// own-retract — the local-state half of the #1423 evict+retract step — use
244    /// [`retract_own_provider`](Self::retract_own_provider).
245    pub async fn withdraw_provider(&self, content: &ContentId) -> bool {
246        let key = content.to_key().to_hex();
247        self.providers.lock().await.unmark_announced(&key)
248    }
249
250    // ---- Real-time holdings API (#1394 / #1423) ----------------------------------------------
251
252    /// Ingest a provider record for a THIRD-PARTY holder that the caller has ALREADY verified was
253    /// signed by `record.provider_peer_id` — the inbound-**add** half of the real-time holdings map
254    /// (SPEC §6.5). Returns the store admission outcome.
255    ///
256    /// This is the authenticated push path a node's announce receiver calls after verifying a
257    /// signed `HoldingsAnnounce` (dig-gossip opcode 222): the holder's signature has replaced mTLS
258    /// attribution as the proof of who provides the content, so — unlike the serving-side
259    /// `add_provider` (§6.4) — this method **bypasses the mTLS self-announce identity check** (the
260    /// caller, not the DHT, established authenticity). dig-dht itself stays crypto-free (SPEC §15):
261    /// it NEVER verifies a signature; passing an unverified record here is a caller bug that
262    /// poisons the local provider set.
263    ///
264    /// Every other admission guard still applies exactly as for `add_provider`: the address list is
265    /// capped ([`MAX_ADDRESSES_PER_RECORD`](crate::MAX_ADDRESSES_PER_RECORD)), `expires_at` is
266    /// clamped to `min(record.expires_at, now + provider_ttl)` (§6.2), and the per-key / global
267    /// admission caps (§6.3) are enforced — an over-capacity ingest returns
268    /// [`PutOutcome::RejectedOverCapacity`] and stores nothing. On acceptance the holder is folded
269    /// into the routing table so this node can reach it.
270    pub async fn ingest_verified_provider(&self, record: ProviderRecord) -> PutOutcome {
271        self.admit_verified_record(record).await
272    }
273
274    /// Remove exactly the local provider record for `(content_key, provider_peer_id)` — the
275    /// inbound-**retract** half of the real-time holdings map (SPEC §6.6). Returns whether a record
276    /// was removed.
277    ///
278    /// `content_key` and `provider_peer_id` are the 64-hex forms as they appear on a
279    /// [`ProviderRecord`] (`content` → `content.to_key().to_hex()`; the holder's `peer_id` hex).
280    /// The caller MUST have verified the retract was signed by that same `provider_peer_id`
281    /// (authenticated retract): a retract signed by one holder removes ONLY that holder's record and
282    /// can never evict another provider of the same key (censorship-resistance, §6.6). dig-dht does
283    /// not verify the signature (SPEC §15) — that is the caller's responsibility.
284    pub async fn remove_provider_record(&self, content_key: &str, provider_peer_id: &str) -> bool {
285        self.providers
286            .lock()
287            .await
288            .remove(content_key, provider_peer_id)
289    }
290
291    /// Actively retract THIS node's own provider record for `content`: remove the local record AND
292    /// stop republishing it, so `find_providers` on this node stops returning self as a holder
293    /// immediately (SPEC §6.6). Returns whether this node was providing the content (a local record
294    /// existed or the key was being announced).
295    ///
296    /// This is the local-state half of the #1423 atomic **evict + retract** step (on an LRU cache
297    /// eviction the node no longer serves the content). Unlike the passive
298    /// [`withdraw_provider`](Self::withdraw_provider) (which leaves the local record to expire via
299    /// TTL), this deletes it now. The copies previously PUT at the `k` closest peers are NOT deleted
300    /// by this call — they age out via TTL, or are removed sooner when dig-node floods the signed
301    /// retract announce and each recipient calls
302    /// [`remove_provider_record`](Self::remove_provider_record).
303    pub async fn retract_own_provider(&self, content: &ContentId) -> bool {
304        let key = content.to_key().to_hex();
305        let self_id = self.local_id.to_hex();
306        let mut ps = self.providers.lock().await;
307        let removed_record = ps.remove(&key, &self_id);
308        let was_announced = ps.unmark_announced(&key);
309        removed_record || was_announced
310    }
311
312    /// The `peer_id`s of the peers that hold `content` — a thin, address-free convenience over
313    /// [`find_providers`](Self::find_providers) for callers that only need "which peers hold X"
314    /// (e.g. an RPC holder-set query) and do not dial the holders themselves.
315    ///
316    /// `find_providers` remains the PRIMARY API: it returns full [`ProviderRecord`]s with candidate
317    /// addresses, which dig-download needs to actually connect and fetch. This method runs the same
318    /// distributed iterative lookup and simply projects each record to its holder `peer_id`
319    /// (records with a malformed peer id are skipped; the set is already deduped by provider).
320    pub async fn holders_of(&self, content: &ContentId) -> Result<Vec<PeerId>, DhtError> {
321        let records = self.find_providers(content).await?;
322        Ok(records
323            .iter()
324            .filter_map(|r| r.provider_peer_id())
325            .collect())
326    }
327
328    // ---- Maintenance -------------------------------------------------------------------------
329
330    /// Republish every content key this node still announces — re-runs the announce PUT so provider
331    /// records never expire while the node is online. Call on the [`DhtConfig::republish_interval`].
332    /// Returns the number of content keys republished.
333    pub async fn republish(&self) -> usize {
334        let keys = self.providers.lock().await.local_announcements();
335        let count = keys.len();
336        for hex in keys {
337            let Some(bytes) = hex64_to_bytes(&hex) else {
338                continue;
339            };
340            let target = Key::from_bytes(bytes);
341            let record = self.build_local_record(&target);
342            self.providers.lock().await.put(record.clone());
343            let seeds = self.seed_contacts(&target).await;
344            if !seeds.is_empty() {
345                let result = self.run_lookup(target, seeds, false).await;
346                self.absorb_contacts(&result.closest).await;
347                self.put_record_at(&result.closest, &record).await;
348            }
349        }
350        count
351    }
352
353    /// Refresh populated buckets by looking up a random key in each — keeps the routing table fresh
354    /// as peers churn. Call on the [`DhtConfig::refresh_interval`]. Returns the number of buckets
355    /// refreshed.
356    pub async fn refresh_buckets(&self) -> usize {
357        let indices = self.routing.lock().await.non_empty_bucket_indices();
358        let count = indices.len();
359        for idx in indices {
360            let target = self.random_key_in_bucket(idx);
361            let seeds = self.seed_contacts(&target).await;
362            if !seeds.is_empty() {
363                let result = self.run_lookup(target, seeds, false).await;
364                self.absorb_contacts(&result.closest).await;
365            }
366        }
367        count
368    }
369
370    /// Drop expired provider records. Call periodically (piggy-backs on republish/refresh). Returns
371    /// the number of records removed.
372    pub async fn gc(&self) -> usize {
373        self.providers.lock().await.gc(now_secs())
374    }
375
376    /// Ping a peer for liveness; on failure, evict it from the routing table. Used by the
377    /// ping-and-replace maintenance when a bucket is full. Returns whether the peer is alive.
378    pub async fn ping(&self, peer: &Contact) -> bool {
379        let nonce = rand::random::<u64>();
380        let from = self.local_contact();
381        match self
382            .transport
383            .rpc(&from, peer, &DhtRequest::Ping { nonce })
384            .await
385        {
386            Ok(DhtResponse::Pong { nonce: got }) if got == nonce => true,
387            _ => {
388                self.routing.lock().await.remove(&peer.peer_id);
389                false
390            }
391        }
392    }
393
394    // ---- Serving side (inbound RPC) ----------------------------------------------------------
395
396    /// Answer an inbound DHT request from another node, without a known caller identity. Prefer
397    /// [`handle_request_from`](Self::handle_request_from) on an authenticated transport (it lets the
398    /// responder learn the caller and populate its routing table bidirectionally, the way Kademlia
399    /// tables fill).
400    pub async fn handle_request(&self, request: DhtRequest) -> DhtResponse {
401        self.handle_request_from(None, request).await
402    }
403
404    /// Answer an inbound DHT request, folding the **authenticated caller** into the routing table.
405    ///
406    /// This is the server half — a dig-node wires it to inbound DHT streams, passing the caller's
407    /// mTLS-verified [`Contact`] as `caller`. Learning the caller from every inbound RPC is how a
408    /// Kademlia node discovers peers *without* an explicit announce: a node that talks to you becomes
409    /// a candidate in your table. The caller MUST come from the authenticated transport (the mTLS
410    /// `peer_id`), never from the request body — identity is not self-asserted.
411    ///
412    /// It reads/writes only local state (routing table + provider store) and never makes outbound
413    /// RPCs, so it cannot recurse or block on the network.
414    pub async fn handle_request_from(
415        &self,
416        caller: Option<Contact>,
417        request: DhtRequest,
418    ) -> DhtResponse {
419        // The authenticated caller's peer_id (if any), kept for the AddProvider self-announce check
420        // below — taken BEFORE the caller Contact is (conditionally) moved into the routing table.
421        let caller_peer_id = caller.as_ref().map(|c| c.peer_id.clone());
422
423        // Learn the (authenticated) caller — every inbound RPC is evidence the caller is alive.
424        // Cap its address list at the boundary (SPEC §5.5, §14): a `Contact` decoded off the wire
425        // bypasses `Contact::new`'s cap entirely (its fields are public), so an uncapped caller
426        // address list would otherwise be folded straight into our routing table and later re-served
427        // to every peer that queries us.
428        if let Some(mut c) = caller {
429            if c.peer_id != self.local_id.to_hex() {
430                crate::record::sort_and_cap_addresses(&mut c.addresses);
431                let _ = self.routing.lock().await.insert(c);
432            }
433        }
434        match request {
435            DhtRequest::Ping { nonce } => DhtResponse::Pong { nonce },
436            DhtRequest::FindNode { target } => {
437                let Some(key) = parse_key(&target) else {
438                    return DhtResponse::Error {
439                        code: 2,
440                        message: "bad target key".into(),
441                    };
442                };
443                let nodes = self.routing.lock().await.closest(&key);
444                DhtResponse::Nodes { nodes }
445            }
446            DhtRequest::FindProviders { content_key } => {
447                let Some(key) = parse_key(&content_key) else {
448                    return DhtResponse::Error {
449                        code: 2,
450                        message: "bad content key".into(),
451                    };
452                };
453                let now = now_secs();
454                let providers = self.providers.lock().await.get(&key.to_hex(), now);
455                let closer = self.routing.lock().await.closest(&key);
456                DhtResponse::Providers { providers, closer }
457            }
458            DhtRequest::AddProvider { record } => {
459                // Self-announce check (SPEC §6.4, §14): when the caller identity is known (an
460                // authenticated transport), the record's provider_peer_id MUST be the caller itself.
461                // ProviderRecord carries no signature, so without this check any authenticated caller
462                // could announce an arbitrary THIRD-PARTY peer_id as a provider of arbitrary content
463                // at attacker-chosen addresses — provider-set poisoning. A caller we cannot identify
464                // (`handle_request`, no transport-supplied identity) cannot be checked and is let
465                // through unchanged — that path already deviates from the mTLS-authenticated model.
466                if let Some(caller_id) = &caller_peer_id {
467                    if *caller_id != record.provider_peer_id {
468                        return DhtResponse::Error {
469                            code: 4,
470                            message:
471                                "add_provider: provider_peer_id must match the authenticated caller"
472                                    .into(),
473                        };
474                    }
475                }
476
477                // Address-cap, TTL-clamp, admission-control, and (on acceptance) fold into routing —
478                // the shared verified-record admission pipeline (SPEC §6.3, §14).
479                match self.admit_verified_record(record).await {
480                    PutOutcome::Accepted => DhtResponse::AddProviderOk,
481                    PutOutcome::RejectedOverCapacity => DhtResponse::Error {
482                        code: 3,
483                        message: "provider store over capacity".into(),
484                    },
485                }
486            }
487        }
488    }
489
490    // ---- Internals ---------------------------------------------------------------------------
491
492    /// Admit a provider record whose provider attribution is ALREADY established — either the
493    /// serving-side mTLS self-announce check passed (`handle_request_from`'s `AddProvider` arm) or
494    /// the caller pre-verified the holder signature ([`ingest_verified_provider`]). This is the one
495    /// admission pipeline both paths share (SPEC §6.3, §14), in order:
496    ///
497    /// 1. **Cap the address list** at [`MAX_ADDRESSES_PER_RECORD`](crate::MAX_ADDRESSES_PER_RECORD)
498    ///    — a record decoded off the wire bypasses `ProviderRecord::new`'s cap (its fields are
499    ///    public), so an attacker could otherwise pack thousands of addresses into one record.
500    /// 2. **Clamp `expires_at`** to `now + provider_ttl` — an inbound record is never trusted to
501    ///    self-report its expiry; without this a record naming `u64::MAX` would never GC.
502    /// 3. **Admission-control** via [`ProviderStore::put`], enforcing the per-key + global caps so a
503    ///    flood cannot grow the store without bound.
504    /// 4. On [`PutOutcome::Accepted`], **fold the holder into the routing table** (its addresses let
505    ///    us reach it). A rejected record folds nothing.
506    ///
507    /// [`ingest_verified_provider`]: Self::ingest_verified_provider
508    async fn admit_verified_record(&self, mut record: ProviderRecord) -> PutOutcome {
509        crate::record::sort_and_cap_addresses(&mut record.addresses);
510
511        let clamp_ceiling = now_secs().saturating_add(self.config.provider_ttl_secs());
512        record.expires_at = record.expires_at.min(clamp_ceiling);
513
514        let outcome = self.providers.lock().await.put(record.clone());
515        if outcome == PutOutcome::Accepted {
516            if let Some(pid) = record.provider_peer_id() {
517                let contact = Contact::new(&pid, record.addresses.clone());
518                let _ = self.routing.lock().await.insert(contact);
519            }
520        }
521        outcome
522    }
523
524    /// Build a provider record for content key `target` naming THIS node, expiring at
525    /// `now + provider_ttl`.
526    fn build_local_record(&self, target: &Key) -> ProviderRecord {
527        let expires_at = now_secs().saturating_add(self.config.provider_ttl_secs());
528        ProviderRecord::new(
529            target,
530            &self.local_id,
531            self.local_addresses.clone(),
532            expires_at,
533        )
534    }
535
536    /// The seed set for a lookup toward `target`: the closest contacts we currently know.
537    async fn seed_contacts(&self, target: &Key) -> Vec<Contact> {
538        self.routing.lock().await.closest(target)
539    }
540
541    /// Run an iterative lookup toward `target` from `seeds`, querying peers over the transport. Each
542    /// peer is asked `find_providers` (which also returns closer contacts), so ONE query kind serves
543    /// both node- and provider-lookups; `stop_on_providers` controls early exit.
544    async fn run_lookup(
545        &self,
546        target: Key,
547        seeds: Vec<Contact>,
548        stop_on_providers: bool,
549    ) -> crate::lookup::LookupResult {
550        let transport = self.transport.clone();
551        let content_key = target.to_hex();
552        let from = self.local_contact();
553        let query = move |contact: Contact| {
554            let transport = transport.clone();
555            let content_key = content_key.clone();
556            let from = from.clone();
557            async move {
558                let req = DhtRequest::FindProviders { content_key };
559                match transport.rpc(&from, &contact, &req).await {
560                    Ok(DhtResponse::Providers { providers, closer }) => {
561                        Ok(QueryOutcome { closer, providers })
562                    }
563                    Ok(DhtResponse::Nodes { nodes }) => Ok(QueryOutcome {
564                        closer: nodes,
565                        providers: vec![],
566                    }),
567                    _ => Err(()),
568                }
569            }
570        };
571        iterative_find(
572            target,
573            seeds,
574            self.config.k,
575            self.config.alpha,
576            stop_on_providers,
577            query,
578        )
579        .await
580    }
581
582    /// Fold discovered contacts back into the routing table (skipping ourselves). Applies the LRS
583    /// insert policy; a full bucket's [`InsertOutcome::Full`] is left for the ping-and-replace
584    /// maintenance (we do not ping inline to keep lookups fast).
585    ///
586    /// `contacts` come straight off the wire (a peer's `find_node`/`find_providers` response) and
587    /// so bypass [`Contact::new`]'s address cap (its fields are public) — this is another
588    /// untrusted-input boundary (SPEC §5.5, §14), capped here before insertion.
589    async fn absorb_contacts(&self, contacts: &[Contact]) {
590        let mut rt = self.routing.lock().await;
591        for c in contacts {
592            let mut c = c.clone();
593            crate::record::sort_and_cap_addresses(&mut c.addresses);
594            match rt.insert(c) {
595                InsertOutcome::Inserted => {}
596                InsertOutcome::Full { .. } => {
597                    // Bucket full — leave for ping-and-replace; do not block the lookup on a ping.
598                }
599            }
600        }
601    }
602
603    /// PUT `record` at each of `peers` via `add_provider`, counting acceptances. A peer that errors
604    /// is skipped (best-effort replication — the record survives at the peers that accepted + locally).
605    async fn put_record_at(&self, peers: &[Contact], record: &ProviderRecord) -> usize {
606        let req = DhtRequest::AddProvider {
607            record: record.clone(),
608        };
609        let from = self.local_contact();
610        let mut accepted = 0;
611        for p in peers {
612            if p.peer_id == self.local_id.to_hex() {
613                continue; // already stored locally
614            }
615            if let Ok(DhtResponse::AddProviderOk) = self.transport.rpc(&from, p, &req).await {
616                accepted += 1;
617            }
618        }
619        accepted
620    }
621
622    /// A random key whose distance from this node falls in bucket `idx` (so a refresh lookup targets
623    /// that bucket's region). Sets the bit at position `255 - idx` and randomizes the lower bits.
624    fn random_key_in_bucket(&self, idx: usize) -> Key {
625        let local = *self.local_id.as_bytes();
626        let mut distance = [0u8; 32];
627        let bit = 255 - idx; // MSB-set position for this bucket
628        let byte = bit / 8;
629        let bit_in_byte = 7 - (bit % 8);
630        distance[byte] = 1 << bit_in_byte;
631        // Randomize lower-significant bits so successive refreshes vary the target.
632        for b in distance.iter_mut().skip(byte + 1) {
633            *b = rand::random::<u8>();
634        }
635        let mut target = [0u8; 32];
636        for i in 0..32 {
637            target[i] = local[i] ^ distance[i];
638        }
639        Key::from_bytes(target)
640    }
641
642    /// The contacts currently in this node's routing table closest to `target` (diagnostic /
643    /// introspection — the peers this node knows without any network round-trip).
644    pub async fn known_closest(&self, target: &Key) -> Vec<Contact> {
645        self.routing.lock().await.closest(target)
646    }
647
648    /// The number of peers currently in this node's routing table (diagnostic / metrics).
649    pub async fn routing_len(&self) -> usize {
650        self.routing.lock().await.len()
651    }
652}
653
654/// Current wall-clock Unix seconds (saturating to 0 before the epoch), for provider TTLs.
655fn now_secs() -> u64 {
656    SystemTime::now()
657        .duration_since(UNIX_EPOCH)
658        .unwrap_or_default()
659        .as_secs()
660}
661
662/// Parse a 64-hex string into a [`Key`] (used on the serving side for wire targets).
663fn parse_key(hex: &str) -> Option<Key> {
664    hex64_to_bytes(hex).map(Key::from_bytes)
665}
666
667/// Decode a 64-char hex string to 32 bytes.
668fn hex64_to_bytes(hex: &str) -> Option<[u8; 32]> {
669    if hex.len() != 64 {
670        return None;
671    }
672    let mut out = [0u8; 32];
673    let bytes = hex.as_bytes();
674    for (i, chunk) in bytes.chunks(2).enumerate() {
675        let hi = (chunk[0] as char).to_digit(16)?;
676        let lo = (chunk[1] as char).to_digit(16)?;
677        out[i] = ((hi << 4) | lo) as u8;
678    }
679    Some(out)
680}
681
682#[cfg(test)]
683mod tests {
684    use super::*;
685
686    fn key_hex_round_trips() {
687        // sanity for the local hex helper
688    }
689
690    #[test]
691    fn hex64_round_trip() {
692        let bytes = [0xABu8; 32];
693        let hex = Key::from_bytes(bytes).to_hex();
694        assert_eq!(hex64_to_bytes(&hex).unwrap(), bytes);
695        assert!(hex64_to_bytes("short").is_none());
696        assert!(hex64_to_bytes(&"zz".repeat(32)).is_none());
697        key_hex_round_trips();
698    }
699
700    #[test]
701    fn parse_key_rejects_bad_hex() {
702        assert!(parse_key("nothex").is_none());
703        assert!(parse_key(&"00".repeat(32)).is_some());
704    }
705}