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;
25
26use tokio::sync::Mutex;
27
28use dig_nat::PeerId;
29
30use crate::clock::now_secs;
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::{ProviderSnapshot, 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 /// The AUTHORITATIVE provider store — records whose provider attribution this node established
77 /// (its own announces, the mTLS-checked serving-side `add_provider`, the caller-verified
78 /// [`ingest_verified_provider`](DhtService::ingest_verified_provider)). This is the store that
79 /// answers an inbound `find_providers`, so everything in it becomes THIS NODE'S CLAIM about who
80 /// holds what.
81 providers: Arc<Mutex<ProviderStore>>,
82 /// The DISCOVERY CACHE — records this node collected from its OWN lookups (SPEC §6.8). Same
83 /// type, same admission control, different trust provenance and therefore a different store:
84 /// see [`cache_discovered`](DhtService::cache_discovered) for why these two must never be one.
85 discovered: Arc<Mutex<ProviderStore>>,
86 transport: Arc<dyn DhtTransport>,
87}
88
89impl DhtService {
90 /// Create a service for the node identified by `local_id`, advertising `local_addresses` in the
91 /// provider records it announces, driving RPC over `transport`.
92 pub fn new(
93 local_id: PeerId,
94 local_addresses: Vec<CandidateAddr>,
95 config: DhtConfig,
96 transport: Arc<dyn DhtTransport>,
97 ) -> Self {
98 let routing = RoutingTable::new(&local_id, config.k);
99 let providers = ProviderStore::with_limits(config.provider_store_limits);
100 let discovered = ProviderStore::with_limits(config.discovery_cache_limits);
101 DhtService {
102 local_id,
103 local_addresses,
104 config,
105 routing: Arc::new(Mutex::new(routing)),
106 providers: Arc::new(Mutex::new(providers)),
107 discovered: Arc::new(Mutex::new(discovered)),
108 transport,
109 }
110 }
111
112 /// This node's id.
113 pub fn local_id(&self) -> &PeerId {
114 &self.local_id
115 }
116
117 /// This node's own [`Contact`] (its id + advertised addresses) — the authenticated caller
118 /// identity supplied to the transport as the RPC `from`.
119 fn local_contact(&self) -> Contact {
120 Contact::new(&self.local_id, self.local_addresses.clone())
121 }
122
123 // ---- Bootstrap ---------------------------------------------------------------------------
124
125 /// Seed the routing table from `peers` and populate it by looking up this node's own id (the
126 /// canonical Kademlia bootstrap: a self-lookup fills the buckets around us). Returns the number
127 /// of distinct peers now known.
128 ///
129 /// Safe to call repeatedly (on reconnect / when new bootstrap peers arrive) — it merges, never
130 /// resets.
131 pub async fn bootstrap(&self, peers: &[BootstrapPeer]) -> Result<usize, DhtError> {
132 {
133 let mut rt = self.routing.lock().await;
134 for p in peers {
135 let _ = rt.insert(p.to_contact());
136 }
137 }
138 // Self-lookup: find the nodes closest to us to fill our buckets.
139 let self_key = Key::from_peer_id(&self.local_id);
140 let seeds: Vec<Contact> = peers.iter().map(|p| p.to_contact()).collect();
141 let result = self.run_lookup(self_key, seeds, false).await;
142 self.absorb_contacts(&result.closest).await;
143 Ok(self.routing.lock().await.len())
144 }
145
146 /// Add a single live peer to the routing table as it connects (e.g. a `dig-gossip`
147 /// `PoolEvent::PeerAdded`), WITHOUT the network round-trip [`bootstrap`](Self::bootstrap) does.
148 ///
149 /// This is the LIVE seam the one-shot pre-connect bootstrap cannot cover: in a freshly-formed
150 /// network the pool is empty when `bootstrap` runs, so routing stays empty and `find_providers`
151 /// finds nobody. Feeding each connected peer here populates routing as the pool fills, which is
152 /// what makes cross-node discovery work (#1574). Idempotent — re-adding a known peer merges its
153 /// address(es) via the routing table's insert policy; adding this node's own id is a no-op.
154 pub async fn add_peer(&self, peer_id: &PeerId, addresses: Vec<CandidateAddr>) {
155 let contact = Contact::new(peer_id, addresses);
156 let _ = self.routing.lock().await.insert(contact);
157 }
158
159 /// Remove a peer from the routing table as it leaves (a `dig-gossip` `PoolEvent::PeerRemoved`),
160 /// keeping routing accurate so lookups don't seed from a dead contact. Returns whether it was
161 /// present. `peer_id_hex` is the 64-char hex id (as carried on `Contact::provider_peer_id` /
162 /// [`PeerId::to_hex`]).
163 pub async fn remove_peer(&self, peer_id_hex: &str) -> bool {
164 self.routing.lock().await.remove(peer_id_hex)
165 }
166
167 // ---- Client operations -------------------------------------------------------------------
168
169 /// Find the `k` peers closest to `peer_id` (the routing primitive). Runs an iterative
170 /// `find_node` lookup and returns the converged closest contacts.
171 pub async fn find_node(&self, peer_id: &PeerId) -> Result<Vec<Contact>, DhtError> {
172 let target = Key::from_peer_id(peer_id);
173 let seeds = self.seed_contacts(&target).await;
174 if seeds.is_empty() {
175 return Err(DhtError::NoPeers);
176 }
177 let result = self.run_lookup(target, seeds, false).await;
178 self.absorb_contacts(&result.closest).await;
179 Ok(result.closest)
180 }
181
182 /// Find the providers of `content` — the peers holding it. Answers from this node's
183 /// **discovery cache** when a recent lookup for the same key is still live (SPEC §6.8);
184 /// otherwise runs an iterative `find_providers` lookup toward the content key, caches what it
185 /// learns, and returns every live provider record collected (deduped by provider). The node
186 /// then connects to those providers over dig-nat and fetches via the L7 peer RPC.
187 ///
188 /// **Cached answers are what make a later direct dial free** (dig_ecosystem#3128 requirement 7):
189 /// a `.dig` fetch issues many requests against the same store, and without the cache each one
190 /// paid a fresh Kademlia walk. A live cache entry is treated as evidence that this node
191 /// completed a lookup for the key recently, so the walk is skipped entirely — records this node
192 /// holds AUTHORITATIVELY are deliberately NOT such evidence, since they may be its own announce
193 /// and short-circuiting on them would stop a publisher ever learning the other holders of its
194 /// own content.
195 ///
196 /// A cached holder is a claim by an untrusted peer, so a dial to it may fail. That costs one
197 /// failed dial, never a wrong answer — the content is accepted because it verifies against the
198 /// merkle root, never because a peer supplied it (NC-12). A caller that finds every cached
199 /// candidate undialable calls [`forget_discovered`](Self::forget_discovered) and asks again,
200 /// which re-runs the full walk.
201 ///
202 /// Returns an empty vec (not an error) when the content simply has no known providers; returns
203 /// [`DhtError::NoPeers`] only when there is no one to ask (empty routing table + no bootstrap).
204 pub async fn find_providers(
205 &self,
206 content: &ContentId,
207 ) -> Result<Vec<ProviderRecord>, DhtError> {
208 let target = content.to_key();
209 let key_hex = target.to_hex();
210
211 // Local short-circuit: if we already hold providers for this key, include them.
212 let now = now_secs();
213 let local = self.providers.lock().await.get(&key_hex, now);
214
215 let cached = self.discovered.lock().await.get(&key_hex, now);
216 if !cached.is_empty() {
217 return Ok(merge_dedup_by_provider(local, cached, now));
218 }
219
220 let seeds = self.seed_contacts(&target).await;
221 if seeds.is_empty() {
222 // No peers to ask — return whatever we hold locally (possibly empty).
223 return Ok(local);
224 }
225 let result = self.run_lookup(target, seeds, true).await;
226 self.absorb_contacts(&result.closest).await;
227
228 // Discovered records come straight off the wire from other peers' responses, bypassing
229 // `ProviderRecord::new`'s address cap — capped here before they are cached or handed back
230 // to our caller (SPEC §5.5, §14). Records for a key we did not query were already discarded
231 // at the wire boundary in `run_lookup`'s query closure (SPEC §6.7).
232 let mut discovered = result.providers;
233 for r in &mut discovered {
234 crate::record::sort_and_cap_addresses(&mut r.addresses);
235 }
236 self.cache_discovered(&key_hex, &discovered).await;
237
238 Ok(merge_dedup_by_provider(local, discovered, now_secs()))
239 }
240
241 /// The provider records this node has CACHED for `content` from its own lookups, live as of
242 /// now — the direct-dial shortcut requirement 7 exists to provide, with no network round-trip
243 /// and no fallback walk.
244 ///
245 /// # These records MUST NOT be re-served to anyone
246 ///
247 /// They are hearsay: some peer along a lookup said that some other peer holds this content, and
248 /// nothing authenticated that claim — unlike an authoritative record, which either names the
249 /// mTLS-verified caller that announced it or was signature-checked by the caller of
250 /// [`ingest_verified_provider`](Self::ingest_verified_provider). Hearsay belongs on the FETCH
251 /// path, where a wrong candidate is merely a wasted dial because the merkle bind catches it. On
252 /// the ASSERTION path — an inbound `find_providers`, a redirect answer, anything a stranger
253 /// reads — it becomes THIS NODE'S claim about the world, and re-serving it would launder an
254 /// attacker's fabricated holder into an answer other nodes trust. This node therefore never
255 /// serves the cache (see [`handle_request_from`](Self::handle_request_from), which reads the
256 /// authoritative store only) and never publishes it (see
257 /// [`provider_snapshot`](Self::provider_snapshot)).
258 pub async fn cached_providers(&self, content: &ContentId) -> Vec<ProviderRecord> {
259 self.discovered
260 .lock()
261 .await
262 .get(&content.to_key().to_hex(), now_secs())
263 }
264
265 /// Forget every cached provider for `content`, so the next
266 /// [`find_providers`](Self::find_providers) runs a real lookup again. Returns how many cached
267 /// records were dropped.
268 ///
269 /// This is what keeps a cache miss CHEAP and keeps it from being mistaken for absence: a caller
270 /// that has tried every cached candidate and reached none of them calls this and asks again,
271 /// rather than concluding the content has no providers. It touches only this node's own cache —
272 /// never the authoritative store, so it can neither censor a key this node serves nor be
273 /// observed by any other peer.
274 pub async fn forget_discovered(&self, content: &ContentId) -> usize {
275 self.discovered
276 .lock()
277 .await
278 .remove_key(&content.to_key().to_hex())
279 }
280
281 /// Announce that THIS node holds `content`: build a provider record (this node's `peer_id` +
282 /// addresses, expiring at `now + provider_ttl`), store it locally, remember to republish it, and
283 /// PUT it at the `k` nodes closest to the content key. Returns how many peers accepted the PUT.
284 ///
285 /// Called when the node's inventory gains content (a new capsule/root/resource it now serves).
286 pub async fn announce_provider(&self, content: &ContentId) -> Result<usize, DhtError> {
287 let target = content.to_key();
288 let record = self.build_local_record(&target);
289
290 // Store locally + remember for republish.
291 {
292 let mut ps = self.providers.lock().await;
293 ps.put(record.clone());
294 ps.mark_announced(target.to_hex());
295 }
296
297 // PUT at the k closest peers we can find.
298 let seeds = self.seed_contacts(&target).await;
299 if seeds.is_empty() {
300 // No peers yet — the local record stands; republish will re-attempt once bootstrapped.
301 return Ok(0);
302 }
303 let result = self.run_lookup(target, seeds, false).await;
304 self.absorb_contacts(&result.closest).await;
305 Ok(self.put_record_at(&result.closest, &record).await)
306 }
307
308 /// Stop announcing `content` (the node no longer holds it). The record ages out of the DHT via
309 /// TTL; we just stop republishing it. Returns whether it was being announced.
310 ///
311 /// This is the **passive** withdraw: it leaves this node's own local provider record in place
312 /// (it only expires with TTL) and merely stops re-publishing it, so a `find_providers` on this
313 /// node may still return self until the local record's TTL elapses. For an **immediate**
314 /// own-retract — the local-state half of the #1423 evict+retract step — use
315 /// [`retract_own_provider`](Self::retract_own_provider).
316 pub async fn withdraw_provider(&self, content: &ContentId) -> bool {
317 let key = content.to_key().to_hex();
318 self.providers.lock().await.unmark_announced(&key)
319 }
320
321 // ---- Real-time holdings API (#1394 / #1423) ----------------------------------------------
322
323 /// Ingest a provider record for a THIRD-PARTY holder that the caller has ALREADY verified was
324 /// signed by `record.provider_peer_id` — the inbound-**add** half of the real-time holdings map
325 /// (SPEC §6.5). Returns the store admission outcome.
326 ///
327 /// This is the authenticated push path a node's announce receiver calls after verifying a
328 /// signed `HoldingsAnnounce` (dig-gossip opcode 222): the holder's signature has replaced mTLS
329 /// attribution as the proof of who provides the content, so — unlike the serving-side
330 /// `add_provider` (§6.4) — this method **bypasses the mTLS self-announce identity check** (the
331 /// caller, not the DHT, established authenticity). dig-dht itself stays crypto-free (SPEC §15):
332 /// it NEVER verifies a signature; passing an unverified record here is a caller bug that
333 /// poisons the local provider set.
334 ///
335 /// Every other admission guard still applies exactly as for `add_provider`: the address list is
336 /// capped ([`MAX_ADDRESSES_PER_RECORD`](crate::MAX_ADDRESSES_PER_RECORD)), `expires_at` is
337 /// clamped to `min(record.expires_at, now + provider_ttl)` (§6.2), and the per-key / global
338 /// admission caps (§6.3) are enforced — an over-capacity ingest returns
339 /// [`PutOutcome::RejectedOverCapacity`] and stores nothing. On acceptance the holder is folded
340 /// into the routing table so this node can reach it.
341 pub async fn ingest_verified_provider(&self, record: ProviderRecord) -> PutOutcome {
342 self.admit_verified_record(record).await
343 }
344
345 /// Remove exactly the local provider record for `(content_key, provider_peer_id)` — the
346 /// inbound-**retract** half of the real-time holdings map (SPEC §6.6). Returns whether a record
347 /// was removed.
348 ///
349 /// `content_key` and `provider_peer_id` are the 64-hex forms as they appear on a
350 /// [`ProviderRecord`] (`content` → `content.to_key().to_hex()`; the holder's `peer_id` hex).
351 /// The caller MUST have verified the retract was signed by that same `provider_peer_id`
352 /// (authenticated retract): a retract signed by one holder removes ONLY that holder's record and
353 /// can never evict another provider of the same key (censorship-resistance, §6.6). dig-dht does
354 /// not verify the signature (SPEC §15) — that is the caller's responsibility.
355 pub async fn remove_provider_record(&self, content_key: &str, provider_peer_id: &str) -> bool {
356 self.providers
357 .lock()
358 .await
359 .remove(content_key, provider_peer_id)
360 }
361
362 /// A bounded, AGGREGATED view of this node's provider store — content keys and their live
363 /// provider COUNTS, with no provider identities (dig_ecosystem #1935).
364 ///
365 /// Exposed so a node can answer the relay's RLY-009 `get_dht_records` without the caller needing
366 /// access to the store itself. Because a Kademlia node holds records for keys near its OWN
367 /// `peer_id`, this describes MANY OTHER peers' content rather than what this node caches — which
368 /// is what makes the union across nodes a usable view of the network's content layer.
369 ///
370 /// `max_keys` bounds the result; see [`ProviderStore::snapshot`] for the truncation and privacy
371 /// contract. Expired records are excluded as of the current time, so the counts agree with what
372 /// [`find_providers`](Self::find_providers) would actually return.
373 pub async fn provider_snapshot(&self, max_keys: usize) -> ProviderSnapshot {
374 self.providers.lock().await.snapshot(now_secs(), max_keys)
375 }
376
377 /// Actively retract THIS node's own provider record for `content`: remove the local record AND
378 /// stop republishing it, so `find_providers` on this node stops returning self as a holder
379 /// immediately (SPEC §6.6). Returns whether this node was providing the content (a local record
380 /// existed or the key was being announced).
381 ///
382 /// This is the local-state half of the #1423 atomic **evict + retract** step (on an LRU cache
383 /// eviction the node no longer serves the content). Unlike the passive
384 /// [`withdraw_provider`](Self::withdraw_provider) (which leaves the local record to expire via
385 /// TTL), this deletes it now. The copies previously PUT at the `k` closest peers are NOT deleted
386 /// by this call — they age out via TTL, or are removed sooner when dig-node floods the signed
387 /// retract announce and each recipient calls
388 /// [`remove_provider_record`](Self::remove_provider_record).
389 pub async fn retract_own_provider(&self, content: &ContentId) -> bool {
390 let key = content.to_key().to_hex();
391 let self_id = self.local_id.to_hex();
392 let mut ps = self.providers.lock().await;
393 let removed_record = ps.remove(&key, &self_id);
394 let was_announced = ps.unmark_announced(&key);
395 removed_record || was_announced
396 }
397
398 /// The `peer_id`s of the peers that hold `content` — a thin, address-free convenience over
399 /// [`find_providers`](Self::find_providers) for callers that only need "which peers hold X"
400 /// (e.g. an RPC holder-set query) and do not dial the holders themselves.
401 ///
402 /// `find_providers` remains the PRIMARY API: it returns full [`ProviderRecord`]s with candidate
403 /// addresses, which dig-download needs to actually connect and fetch. This method runs the same
404 /// distributed iterative lookup and simply projects each record to its holder `peer_id`
405 /// (records with a malformed peer id are skipped; the set is already deduped by provider).
406 pub async fn holders_of(&self, content: &ContentId) -> Result<Vec<PeerId>, DhtError> {
407 let records = self.find_providers(content).await?;
408 Ok(records
409 .iter()
410 .filter_map(|r| r.provider_peer_id())
411 .collect())
412 }
413
414 // ---- Maintenance -------------------------------------------------------------------------
415
416 /// Republish every content key this node still announces — re-runs the announce PUT so provider
417 /// records never expire while the node is online. Call on the [`DhtConfig::republish_interval`].
418 /// Returns the number of content keys republished.
419 pub async fn republish(&self) -> usize {
420 let keys = self.providers.lock().await.local_announcements();
421 let count = keys.len();
422 for hex in keys {
423 let Some(bytes) = hex64_to_bytes(&hex) else {
424 continue;
425 };
426 let target = Key::from_bytes(bytes);
427 let record = self.build_local_record(&target);
428 self.providers.lock().await.put(record.clone());
429 let seeds = self.seed_contacts(&target).await;
430 if !seeds.is_empty() {
431 let result = self.run_lookup(target, seeds, false).await;
432 self.absorb_contacts(&result.closest).await;
433 self.put_record_at(&result.closest, &record).await;
434 }
435 }
436 count
437 }
438
439 /// Refresh populated buckets by looking up a random key in each — keeps the routing table fresh
440 /// as peers churn. Call on the [`DhtConfig::refresh_interval`]. Returns the number of buckets
441 /// refreshed.
442 pub async fn refresh_buckets(&self) -> usize {
443 let indices = self.routing.lock().await.non_empty_bucket_indices();
444 let count = indices.len();
445 for idx in indices {
446 let target = self.random_key_in_bucket(idx);
447 let seeds = self.seed_contacts(&target).await;
448 if !seeds.is_empty() {
449 let result = self.run_lookup(target, seeds, false).await;
450 self.absorb_contacts(&result.closest).await;
451 }
452 }
453 count
454 }
455
456 /// Drop expired provider records from BOTH the authoritative store and the discovery cache
457 /// (SPEC §6.8). Call periodically (piggy-backs on republish/refresh). Returns the total number
458 /// of records removed.
459 ///
460 /// One `now` for both sweeps, so a maintenance tick cannot leave the two stores disagreeing
461 /// about which instant it ran at.
462 pub async fn gc(&self) -> usize {
463 let now = now_secs();
464 let authoritative = self.providers.lock().await.gc(now);
465 let cached = self.discovered.lock().await.gc(now);
466 authoritative + cached
467 }
468
469 /// Ping a peer for liveness; on failure, evict it from the routing table. Used by the
470 /// ping-and-replace maintenance when a bucket is full. Returns whether the peer is alive.
471 pub async fn ping(&self, peer: &Contact) -> bool {
472 let nonce = rand::random::<u64>();
473 let from = self.local_contact();
474 match self
475 .transport
476 .rpc(&from, peer, &DhtRequest::Ping { nonce })
477 .await
478 {
479 Ok(DhtResponse::Pong { nonce: got }) if got == nonce => true,
480 _ => {
481 self.routing.lock().await.remove(&peer.peer_id);
482 false
483 }
484 }
485 }
486
487 // ---- Serving side (inbound RPC) ----------------------------------------------------------
488
489 /// Answer an inbound DHT request from another node, without a known caller identity. Prefer
490 /// [`handle_request_from`](Self::handle_request_from) on an authenticated transport (it lets the
491 /// responder learn the caller and populate its routing table bidirectionally, the way Kademlia
492 /// tables fill).
493 pub async fn handle_request(&self, request: DhtRequest) -> DhtResponse {
494 self.handle_request_from(None, request).await
495 }
496
497 /// Answer an inbound DHT request, folding the **authenticated caller** into the routing table.
498 ///
499 /// This is the server half — a dig-node wires it to inbound DHT streams, passing the caller's
500 /// mTLS-verified [`Contact`] as `caller`. Learning the caller from every inbound RPC is how a
501 /// Kademlia node discovers peers *without* an explicit announce: a node that talks to you becomes
502 /// a candidate in your table. The caller MUST come from the authenticated transport (the mTLS
503 /// `peer_id`), never from the request body — identity is not self-asserted.
504 ///
505 /// It reads/writes only local state (routing table + provider store) and never makes outbound
506 /// RPCs, so it cannot recurse or block on the network.
507 pub async fn handle_request_from(
508 &self,
509 caller: Option<Contact>,
510 request: DhtRequest,
511 ) -> DhtResponse {
512 // The authenticated caller's peer_id (if any), kept for the AddProvider self-announce check
513 // below — taken BEFORE the caller Contact is (conditionally) moved into the routing table.
514 let caller_peer_id = caller.as_ref().map(|c| c.peer_id.clone());
515
516 // Learn the (authenticated) caller — every inbound RPC is evidence the caller is alive.
517 // Cap its address list at the boundary (SPEC §5.5, §14): a `Contact` decoded off the wire
518 // bypasses `Contact::new`'s cap entirely (its fields are public), so an uncapped caller
519 // address list would otherwise be folded straight into our routing table and later re-served
520 // to every peer that queries us.
521 if let Some(mut c) = caller {
522 if c.peer_id != self.local_id.to_hex() {
523 crate::record::sort_and_cap_addresses(&mut c.addresses);
524 let _ = self.routing.lock().await.insert(c);
525 }
526 }
527 match request {
528 DhtRequest::Ping { nonce } => DhtResponse::Pong { nonce },
529 DhtRequest::FindNode { target } => {
530 let Some(key) = parse_key(&target) else {
531 return DhtResponse::Error {
532 code: 2,
533 message: "bad target key".into(),
534 };
535 };
536 let nodes = self.routing.lock().await.closest(&key);
537 DhtResponse::Nodes { nodes }
538 }
539 DhtRequest::FindProviders { content_key } => {
540 let Some(key) = parse_key(&content_key) else {
541 return DhtResponse::Error {
542 code: 2,
543 message: "bad content key".into(),
544 };
545 };
546 let now = now_secs();
547 let providers = self.providers.lock().await.get(&key.to_hex(), now);
548 let closer = self.routing.lock().await.closest(&key);
549 DhtResponse::Providers { providers, closer }
550 }
551 DhtRequest::AddProvider { record } => {
552 // Self-announce check (SPEC §6.4, §14): when the caller identity is known (an
553 // authenticated transport), the record's provider_peer_id MUST be the caller itself.
554 // ProviderRecord carries no signature, so without this check any authenticated caller
555 // could announce an arbitrary THIRD-PARTY peer_id as a provider of arbitrary content
556 // at attacker-chosen addresses — provider-set poisoning. A caller we cannot identify
557 // (`handle_request`, no transport-supplied identity) cannot be checked and is let
558 // through unchanged — that path already deviates from the mTLS-authenticated model.
559 if let Some(caller_id) = &caller_peer_id {
560 if *caller_id != record.provider_peer_id {
561 return DhtResponse::Error {
562 code: 4,
563 message:
564 "add_provider: provider_peer_id must match the authenticated caller"
565 .into(),
566 };
567 }
568 }
569
570 // Address-cap, TTL-clamp, admission-control, and (on acceptance) fold into routing —
571 // the shared verified-record admission pipeline (SPEC §6.3, §14).
572 match self.admit_verified_record(record).await {
573 PutOutcome::Accepted => DhtResponse::AddProviderOk,
574 PutOutcome::RejectedOverCapacity => DhtResponse::Error {
575 code: 3,
576 message: "provider store over capacity".into(),
577 },
578 }
579 }
580 }
581 }
582
583 // ---- Internals ---------------------------------------------------------------------------
584
585 /// Admit a provider record whose provider attribution is ALREADY established — either the
586 /// serving-side mTLS self-announce check passed (`handle_request_from`'s `AddProvider` arm) or
587 /// the caller pre-verified the holder signature ([`ingest_verified_provider`]). This is the one
588 /// admission pipeline both paths share (SPEC §6.3, §14), in order:
589 ///
590 /// 1. **Cap the address list** at [`MAX_ADDRESSES_PER_RECORD`](crate::MAX_ADDRESSES_PER_RECORD)
591 /// — a record decoded off the wire bypasses `ProviderRecord::new`'s cap (its fields are
592 /// public), so an attacker could otherwise pack thousands of addresses into one record.
593 /// 2. **Clamp `expires_at`** to `now + provider_ttl` — an inbound record is never trusted to
594 /// self-report its expiry; without this a record naming `u64::MAX` would never GC.
595 /// 3. **Admission-control** via [`ProviderStore::put`], enforcing the per-key + global caps so a
596 /// flood cannot grow the store without bound.
597 /// 4. On [`PutOutcome::Accepted`], **fold the holder into the routing table** (its addresses let
598 /// us reach it). A rejected record folds nothing.
599 ///
600 /// [`ingest_verified_provider`]: Self::ingest_verified_provider
601 async fn admit_verified_record(&self, mut record: ProviderRecord) -> PutOutcome {
602 crate::record::sort_and_cap_addresses(&mut record.addresses);
603
604 let now = now_secs();
605 let clamp_ceiling = now.saturating_add(self.config.provider_ttl_secs());
606 record.expires_at = record.expires_at.min(clamp_ceiling);
607
608 // `put_at` with the SAME instant the clamp used, so admission cannot reclaim a slot it
609 // considers expired while the clamp considered it live (or vice versa).
610 let outcome = self.providers.lock().await.put_at(record.clone(), now);
611 if outcome == PutOutcome::Accepted {
612 if let Some(pid) = record.provider_peer_id() {
613 let contact = Contact::new(&pid, record.addresses.clone());
614 let _ = self.routing.lock().await.insert(contact);
615 }
616 }
617 outcome
618 }
619
620 /// Cache the records a lookup for `content_key` collected, so a later fetch of the same content
621 /// can dial directly instead of walking the DHT again (SPEC §6.8, dig_ecosystem#3128 req 7).
622 ///
623 /// # Why this is a SEPARATE store from the authoritative one
624 ///
625 /// The two hold the same type and are admission-controlled by the same code, but they carry
626 /// different trust provenance, and the difference decides who may read them. An authoritative
627 /// record was attributed — the serving side checked the announcing record against its
628 /// mTLS-verified caller, or the caller of `ingest_verified_provider` checked the holder's
629 /// signature. A record collected during a lookup was attributed by NOBODY: an arbitrary peer
630 /// along the walk asserted that some third party holds the content, at addresses of its
631 /// choosing. Merging the two would make this node re-serve that assertion as its own on every
632 /// inbound `find_providers` — turning one fabricated record fed to one node into a poisoned
633 /// answer the rest of the network reads back, at a keyspace position this node has no `k`-closest
634 /// duty over. Kept apart, the worst a fabricated record achieves is a wasted dial by the one
635 /// node that cached it.
636 ///
637 /// Three admission rules, in order:
638 ///
639 /// 1. **Never cache a record naming THIS node.** It is useless as a dial target, and worse, it
640 /// would make the cache non-empty and so suppress the next real lookup — a peer that echoed
641 /// our own record back at us could pin us to a provider set of one entry we cannot use.
642 /// 2. **Never cache a record for a different key.** The wire boundary already discards those
643 /// (SPEC §6.7); re-checking costs a string compare and this write outlives the lookup that
644 /// produced it, so the invariant is asserted rather than assumed.
645 /// 3. **Clamp the expiry DOWN to `now + discovery_cache_ttl`**, never up. A peer cannot extend
646 /// its residence in this node's cache by claiming a distant expiry, and a record that is
647 /// already expired is not cached at all.
648 ///
649 /// Every surviving record goes through [`ProviderStore::put_at`], so the discovery cache's
650 /// per-key and global caps bound it exactly as the authoritative store's bound that one — this
651 /// write path has no way to exceed them.
652 async fn cache_discovered(&self, content_key: &str, discovered: &[ProviderRecord]) {
653 let now = now_secs();
654 let ceiling = now.saturating_add(self.config.discovery_cache_ttl_secs());
655 let self_id = self.local_id.to_hex();
656
657 let mut cache = self.discovered.lock().await;
658 for record in discovered {
659 if record.provider_peer_id == self_id || record.content_key != content_key {
660 continue;
661 }
662 let mut entry = record.clone();
663 entry.expires_at = entry.expires_at.min(ceiling);
664 if entry.is_expired(now) {
665 continue;
666 }
667 cache.put_at(entry, now);
668 }
669 }
670
671 /// Build a provider record for content key `target` naming THIS node, expiring at
672 /// `now + provider_ttl`.
673 fn build_local_record(&self, target: &Key) -> ProviderRecord {
674 let expires_at = now_secs().saturating_add(self.config.provider_ttl_secs());
675 ProviderRecord::new(
676 target,
677 &self.local_id,
678 self.local_addresses.clone(),
679 expires_at,
680 )
681 }
682
683 /// The seed set for a lookup toward `target`: the closest contacts we currently know.
684 async fn seed_contacts(&self, target: &Key) -> Vec<Contact> {
685 self.routing.lock().await.closest(target)
686 }
687
688 /// Run an iterative lookup toward `target` from `seeds`, querying peers over the transport. Each
689 /// peer is asked `find_providers` (which also returns closer contacts), so ONE query kind serves
690 /// both node- and provider-lookups; `stop_on_providers` controls early exit.
691 async fn run_lookup(
692 &self,
693 target: Key,
694 seeds: Vec<Contact>,
695 stop_on_providers: bool,
696 ) -> crate::lookup::LookupResult {
697 let transport = self.transport.clone();
698 let content_key = target.to_hex();
699 let from = self.local_contact();
700 let query = move |contact: Contact| {
701 let transport = transport.clone();
702 let content_key = content_key.clone();
703 let from = from.clone();
704 async move {
705 let req = DhtRequest::FindProviders {
706 content_key: content_key.clone(),
707 };
708 match transport.rpc(&from, &contact, &req).await {
709 Ok(DhtResponse::Providers {
710 mut providers,
711 closer,
712 }) => {
713 // Answer-to-question binding (SPEC §6.7, §14): keep only records for the
714 // key we actually asked about. A responder is free to say ANYTHING here —
715 // `ProviderRecord` carries no signature and the peer is not the record's
716 // subject — so without this equality check any peer on the lookup path
717 // could stamp arbitrary provider peer_ids and address hints onto records
718 // for keys the finder never queried, and the finder would return them to
719 // its caller as dial targets (dial fan-out / wasted-dial DoS, and a
720 // spirit-defeat of the #1490 amplification bound).
721 //
722 // Filtering HERE, at the wire boundary, rather than at the final merge is
723 // load-bearing: the lookup's `stop_on_providers` early exit fires as soon
724 // as any provider is collected, so a mismatched record counted as "found"
725 // would end the walk before it reached a real holder — discovery
726 // censorship. Nothing downstream of this point sees an off-key record.
727 providers.retain(|r| r.content_key == content_key);
728 Ok(QueryOutcome { closer, providers })
729 }
730 Ok(DhtResponse::Nodes { nodes }) => Ok(QueryOutcome {
731 closer: nodes,
732 providers: vec![],
733 }),
734 _ => Err(()),
735 }
736 }
737 };
738 iterative_find(
739 target,
740 seeds,
741 self.config.k,
742 self.config.alpha,
743 stop_on_providers,
744 query,
745 )
746 .await
747 }
748
749 /// Fold discovered contacts back into the routing table (skipping ourselves). Applies the LRS
750 /// insert policy; a full bucket's [`InsertOutcome::Full`] is left for the ping-and-replace
751 /// maintenance (we do not ping inline to keep lookups fast).
752 ///
753 /// `contacts` come straight off the wire (a peer's `find_node`/`find_providers` response) and
754 /// so bypass [`Contact::new`]'s address cap (its fields are public) — this is another
755 /// untrusted-input boundary (SPEC §5.5, §14), capped here before insertion.
756 async fn absorb_contacts(&self, contacts: &[Contact]) {
757 let mut rt = self.routing.lock().await;
758 for c in contacts {
759 let mut c = c.clone();
760 crate::record::sort_and_cap_addresses(&mut c.addresses);
761 match rt.insert(c) {
762 InsertOutcome::Inserted => {}
763 InsertOutcome::Full { .. } => {
764 // Bucket full — leave for ping-and-replace; do not block the lookup on a ping.
765 }
766 }
767 }
768 }
769
770 /// PUT `record` at each of `peers` via `add_provider`, counting acceptances. A peer that errors
771 /// is skipped (best-effort replication — the record survives at the peers that accepted + locally).
772 async fn put_record_at(&self, peers: &[Contact], record: &ProviderRecord) -> usize {
773 let req = DhtRequest::AddProvider {
774 record: record.clone(),
775 };
776 let from = self.local_contact();
777 let mut accepted = 0;
778 for p in peers {
779 if p.peer_id == self.local_id.to_hex() {
780 continue; // already stored locally
781 }
782 if let Ok(DhtResponse::AddProviderOk) = self.transport.rpc(&from, p, &req).await {
783 accepted += 1;
784 }
785 }
786 accepted
787 }
788
789 /// A random key whose distance from this node falls in bucket `idx` (so a refresh lookup targets
790 /// that bucket's region). Sets the bit at position `255 - idx` and randomizes the lower bits.
791 fn random_key_in_bucket(&self, idx: usize) -> Key {
792 let local = *self.local_id.as_bytes();
793 let mut distance = [0u8; 32];
794 let bit = 255 - idx; // MSB-set position for this bucket
795 let byte = bit / 8;
796 let bit_in_byte = 7 - (bit % 8);
797 distance[byte] = 1 << bit_in_byte;
798 // Randomize lower-significant bits so successive refreshes vary the target.
799 for b in distance.iter_mut().skip(byte + 1) {
800 *b = rand::random::<u8>();
801 }
802 let mut target = [0u8; 32];
803 for i in 0..32 {
804 target[i] = local[i] ^ distance[i];
805 }
806 Key::from_bytes(target)
807 }
808
809 /// The contacts currently in this node's routing table closest to `target` (diagnostic /
810 /// introspection — the peers this node knows without any network round-trip).
811 pub async fn known_closest(&self, target: &Key) -> Vec<Contact> {
812 self.routing.lock().await.closest(target)
813 }
814
815 /// The number of peers currently in this node's routing table (diagnostic / metrics).
816 pub async fn routing_len(&self) -> usize {
817 self.routing.lock().await.len()
818 }
819}
820
821/// Merge two provider sets into one answer: `authoritative` first, then `extra`, deduped by
822/// provider `peer_id` and with anything expired at `now` dropped.
823///
824/// Order is the contract, not an accident. The caller dials the list front-to-back, so the records
825/// whose provenance this node established lead, and the weaker-provenance set (a discovery-cache
826/// hit, or the records a lookup just collected) follows. A provider present in both keeps its
827/// authoritative entry, because the first occurrence wins.
828fn merge_dedup_by_provider(
829 mut authoritative: Vec<ProviderRecord>,
830 extra: Vec<ProviderRecord>,
831 now: u64,
832) -> Vec<ProviderRecord> {
833 authoritative.extend(extra);
834 let mut seen = std::collections::HashSet::new();
835 authoritative.retain(|r| !r.is_expired(now) && seen.insert(r.provider_peer_id.clone()));
836 authoritative
837}
838
839/// Parse a 64-hex string into a [`Key`] (used on the serving side for wire targets).
840fn parse_key(hex: &str) -> Option<Key> {
841 hex64_to_bytes(hex).map(Key::from_bytes)
842}
843
844/// Decode a 64-char hex string to 32 bytes.
845fn hex64_to_bytes(hex: &str) -> Option<[u8; 32]> {
846 if hex.len() != 64 {
847 return None;
848 }
849 let mut out = [0u8; 32];
850 let bytes = hex.as_bytes();
851 for (i, chunk) in bytes.chunks(2).enumerate() {
852 let hi = (chunk[0] as char).to_digit(16)?;
853 let lo = (chunk[1] as char).to_digit(16)?;
854 out[i] = ((hi << 4) | lo) as u8;
855 }
856 Some(out)
857}
858
859#[cfg(test)]
860mod tests {
861 use super::*;
862
863 fn key_hex_round_trips() {
864 // sanity for the local hex helper
865 }
866
867 #[test]
868 fn hex64_round_trip() {
869 let bytes = [0xABu8; 32];
870 let hex = Key::from_bytes(bytes).to_hex();
871 assert_eq!(hex64_to_bytes(&hex).unwrap(), bytes);
872 assert!(hex64_to_bytes("short").is_none());
873 assert!(hex64_to_bytes(&"zz".repeat(32)).is_none());
874 key_hex_round_trips();
875 }
876
877 #[test]
878 fn parse_key_rejects_bad_hex() {
879 assert!(parse_key("nothex").is_none());
880 assert!(parse_key(&"00".repeat(32)).is_some());
881 }
882}
883
884#[cfg(test)]
885mod provider_snapshot_tests {
886 use super::*;
887 use crate::record::CandidateAddr;
888
889 /// A transport that is never dialled: these tests only exercise the LOCAL provider store.
890 struct UnusedTransport;
891
892 #[async_trait::async_trait]
893 impl crate::transport::DhtTransport for UnusedTransport {
894 async fn rpc(
895 &self,
896 _from: &Contact,
897 _peer: &Contact,
898 _request: &DhtRequest,
899 ) -> Result<DhtResponse, DhtError> {
900 unreachable!("provider-snapshot tests never dial a peer")
901 }
902 }
903
904 fn service() -> DhtService {
905 DhtService::new(
906 PeerId::from_bytes([9u8; 32]),
907 vec![CandidateAddr::direct("h", 9444)],
908 DhtConfig::default(),
909 Arc::new(UnusedTransport),
910 )
911 }
912
913 async fn announce(svc: &DhtService, content_seed: u8, provider_seed: u8) {
914 let content = ContentId::store([content_seed; 32]);
915 svc.ingest_verified_provider(ProviderRecord::new(
916 &content.to_key(),
917 &PeerId::from_bytes([provider_seed; 32]),
918 vec![CandidateAddr::direct("h", 9444)],
919 now_secs() + 3600,
920 ))
921 .await;
922 }
923
924 /// The accessor RLY-009 answers from: counts reachable WITHOUT handing out the store, and
925 /// without a single provider identity crossing the boundary (dig_ecosystem #1935).
926 #[tokio::test]
927 async fn provider_snapshot_reports_counts_and_no_identities() {
928 let svc = service();
929 announce(&svc, 1, 7).await;
930
931 let snap = svc.provider_snapshot(100).await;
932
933 assert_eq!(snap.total_keys, 1);
934 assert_eq!(snap.entries[0].providers, 1);
935 assert!(
936 !format!("{snap:?}").contains(&PeerId::from_bytes([7u8; 32]).to_hex()),
937 "a provider identity must never leave the store through this accessor"
938 );
939 }
940
941 /// The bound is honoured: the store is attacker-influenced, so the answer size must be OURS.
942 #[tokio::test]
943 async fn provider_snapshot_honours_the_bound() {
944 let svc = service();
945 for i in 0..6u8 {
946 announce(&svc, i, 100 + i).await;
947 }
948 let snap = svc.provider_snapshot(2).await;
949 assert_eq!(snap.entries.len(), 2);
950 assert!(snap.truncated);
951 assert_eq!(snap.total_keys, 6, "the true total survives truncation");
952 }
953}