Repository navigation
feat(protocol): add cdn/dht/v1 wire types (ADR 022) (PR 1/4 of #320) - #642
Conversation
Introduces `DhtMessage` and the six request/response structs for the
Kademlia content DHT specified in ADR 022 §Message Types:
`FindValue{Request,Response}`, `Store{Request,Ack}`,
`FindNode{Request,Response}`. The variant order is frozen per
ADR 013 §Protocol Enums and pinned by per-variant discriminant tests so
a reorder fails CI loudly rather than breaking wire compatibility
silently.
Authentication on `StoreRequest` is by QUIC-bound NodeId equality, not
a per-record signature — this depends on records being pushed directly
by the holder and never relayed peer-to-peer. The module docs flag the
invariant so a future relay scheme reintroduces the signature plus
in-scope sender timestamp together (ADR 015 §Replay Safety Analysis).
`BatchStoreRequest` / `BatchStoreAck` are deferred to a follow-up
issue. ADR 022 specifies them as a bandwidth optimization with a
per-hash fallback only useful at C ≥ 10k cached blobs; when added they
append after `FindNodeResponse` so existing discriminants are
preserved.
Wire-cap constants (`MAX_PROVIDERS_PER_HASH = 50`,
`MAX_CLOSER_NODES = 20`) bound the max-size `FindValueResponse` under
the ~2.3 KB ceiling from ADR 022 §DHT Bandwidth Analysis; the upper
bound is asserted by a test so future field additions can't drift past
it unnoticed.
Refs #320.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces the wire message types for the cdn/dht/v1 Kademlia content DHT, defining the protocol enum and associated request/response structures along with serialization tests. The review identifies critical security risks related to memory exhaustion because the Vec collections in FindValueResponse and FindNodeResponse are not bounded during deserialization. Additionally, the reviewer suggests reordering the DhtMessage enum variants to align with the ADR 022 specification to ensure long-term wire format stability.
There was a problem hiding this comment.
Pull request overview
Adds the initial wire-level message surface for the upcoming cdn/dht/v1 Kademlia content-discovery protocol (ADR 022) to the leaf decdn-protocol crate, including re-exports and discriminant-pinning tests to preserve wire compatibility under ADR 013.
Changes:
- Introduce
crates/protocol/src/dht.rswithDhtMessageand the request/response structs forFindValue,Store, andFindNode. - Re-export the new DHT types and constants from
crates/protocol/src/lib.rs. - Add tests to pin enum discriminants and to guard encoded-size expectations for the largest
FindValueResponseshape.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
| crates/protocol/src/lib.rs | Exposes the new DHT module and re-exports its public wire types/constants. |
| crates/protocol/src/dht.rs | Defines cdn/dht/v1 wire message types plus discriminant/size/roundtrip tests. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Coverage reportTotal: 90.15% (was 89.98%, ▲ +0.17%) — 17139/19012 lines
History
|
…nonical Addresses PR #642 review feedback (gemini-code-assist + Copilot): - Add `#[serde(deserialize_with = ...)]` field-level hooks enforcing `MAX_PROVIDERS_PER_HASH`, `MAX_CLOSER_NODES`, and `MAX_BATCH_STORE_HASHES` at the wire boundary. Pattern mirrors `ProbeResponseBody::rate_per_mb`: postcard's positional layout stays derive-driven (no mirror struct, no manual `Deserialize` impl), and oversize Vec fields now fail decode rather than allocating an attacker-chosen size up to the 16 MiB framing ceiling. - Reorder `DhtMessage` variants to match ADR 022 §Message Types: the ADR lists `BatchStore`/`BatchStoreAck` at positions 4/5 and `FindNode`/`FindNodeResponse` at 6/7. The original PR put `FindNode` at 4/5; with postcard's sequential discriminant indexing this would have forced a future wire-breaking shuffle once `BatchStore` lands. Define the `BatchStore` wire types now (no handler) so the production ordering matches the ADR and the future BatchStore PR is a pure handler addition. - Replace the inner-struct-only size guard with a framed-size assertion that includes the `DhtMessage` enum discriminant byte AND the `write_frame` length-prefix varint, so the ~2.3 KB ADR 022 wire ceiling can't drift via discriminant or framing-layer changes. - New tests: discriminant pinning for `BatchStore` (4) / `BatchStoreAck` (5) / `FindNode` (6) / `FindNodeResponse` (7); decode-time rejection for oversize `providers`, `closer_nodes`, `BatchStore.hashes`, and `BatchStoreAck.results`; exact-MAX boundary acceptance. Refs #320, addresses #642 review. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Round 2 of PR #642 review (pr-test-analyzer + comment-analyzer). - `find_value_response_max_framed_size_under_ceiling` previously had only `framed_len <= 2_300`. A regression that dropped `providers` or `closer_nodes` from the wire shape would shrink the encoded size well below the ADR's modeled payload (~2.27 KB) and the test would silently pass. Add `framed_len > 2_000` so an accidental field removal fails the test loudly. - Module-level doc for `BatchStore` previously said the runtime "treats inbound BatchStore frames as unsupported until then." After the PR-#643 fix the handler explicitly closes the stream with `APP_ERR_UNSUPPORTED_MESSAGE` (the stream-close-without-ack signal ADR 022 §Schema Evolution requires); the doc now reflects the precise wire behaviour and cites the matching ADR section. Refs #320, addresses PR #642 multi-agent review. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… (PR 2/4 of #320) (#643) * feat(protocol): add cdn/dht/v1 wire types (ADR 022) Introduces `DhtMessage` and the six request/response structs for the Kademlia content DHT specified in ADR 022 §Message Types: `FindValue{Request,Response}`, `Store{Request,Ack}`, `FindNode{Request,Response}`. The variant order is frozen per ADR 013 §Protocol Enums and pinned by per-variant discriminant tests so a reorder fails CI loudly rather than breaking wire compatibility silently. Authentication on `StoreRequest` is by QUIC-bound NodeId equality, not a per-record signature — this depends on records being pushed directly by the holder and never relayed peer-to-peer. The module docs flag the invariant so a future relay scheme reintroduces the signature plus in-scope sender timestamp together (ADR 015 §Replay Safety Analysis). `BatchStoreRequest` / `BatchStoreAck` are deferred to a follow-up issue. ADR 022 specifies them as a bandwidth optimization with a per-hash fallback only useful at C ≥ 10k cached blobs; when added they append after `FindNodeResponse` so existing discriminants are preserved. Wire-cap constants (`MAX_PROVIDERS_PER_HASH = 50`, `MAX_CLOSER_NODES = 20`) bound the max-size `FindValueResponse` under the ~2.3 KB ceiling from ADR 022 §DHT Bandwidth Analysis; the upper bound is asserted by a test so future field additions can't drift past it unnoticed. Refs #320. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(protocol): bound Vec wire fields and reorder DhtMessage to ADR-canonical Addresses PR #642 review feedback (gemini-code-assist + Copilot): - Add `#[serde(deserialize_with = ...)]` field-level hooks enforcing `MAX_PROVIDERS_PER_HASH`, `MAX_CLOSER_NODES`, and `MAX_BATCH_STORE_HASHES` at the wire boundary. Pattern mirrors `ProbeResponseBody::rate_per_mb`: postcard's positional layout stays derive-driven (no mirror struct, no manual `Deserialize` impl), and oversize Vec fields now fail decode rather than allocating an attacker-chosen size up to the 16 MiB framing ceiling. - Reorder `DhtMessage` variants to match ADR 022 §Message Types: the ADR lists `BatchStore`/`BatchStoreAck` at positions 4/5 and `FindNode`/`FindNodeResponse` at 6/7. The original PR put `FindNode` at 4/5; with postcard's sequential discriminant indexing this would have forced a future wire-breaking shuffle once `BatchStore` lands. Define the `BatchStore` wire types now (no handler) so the production ordering matches the ADR and the future BatchStore PR is a pure handler addition. - Replace the inner-struct-only size guard with a framed-size assertion that includes the `DhtMessage` enum discriminant byte AND the `write_frame` length-prefix varint, so the ~2.3 KB ADR 022 wire ceiling can't drift via discriminant or framing-layer changes. - New tests: discriminant pinning for `BatchStore` (4) / `BatchStoreAck` (5) / `FindNode` (6) / `FindNodeResponse` (7); decode-time rejection for oversize `providers`, `closer_nodes`, `BatchStore.hashes`, and `BatchStoreAck.results`; exact-MAX boundary acceptance. Refs #320, addresses #642 review. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test(protocol): add lower bound + align BatchStore module doc Round 2 of PR #642 review (pr-test-analyzer + comment-analyzer). - `find_value_response_max_framed_size_under_ceiling` previously had only `framed_len <= 2_300`. A regression that dropped `providers` or `closer_nodes` from the wire shape would shrink the encoded size well below the ADR's modeled payload (~2.27 KB) and the test would silently pass. Add `framed_len > 2_000` so an accidental field removal fails the test loudly. - Module-level doc for `BatchStore` previously said the runtime "treats inbound BatchStore frames as unsupported until then." After the PR-#643 fix the handler explicitly closes the stream with `APP_ERR_UNSUPPORTED_MESSAGE` (the stream-close-without-ack signal ADR 022 §Schema Evolution requires); the doc now reflects the precise wire behaviour and cites the matching ADR section. Refs #320, addresses PR #642 multi-agent review. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * feat(node): add cdn/dht/v1 handler, routing table, rate limiter (ADR 022) PR 2 of 4 for #320 (Kademlia content discovery). Wires the `cdn/dht/v1` handler skeleton into the runtime and lands the routing table + rate limiter the rest of the DHT machinery will build on. What's in: - `crates/node/src/dht/routing.rs` — k-bucket routing table at K=20, 256 buckets keyed by XOR distance to the node's own NodeId (ADR 022 §Routing Table). LRU eviction on bucket overflow; the ping-then-evict variant is deferred until the FindNode driver lands in PR 4 of #320. Self-id inserts are no-ops so iterative lookup never terminates on the local table. - `crates/node/src/dht/rate_limit.rs` — three-layer token-bucket limiter (per-peer NodeId, per-IP, global) with cheapest-first short-circuit per ADR 022 §DHT Rate Limiting. Trusted-IP exemption bypasses the per-IP layer only; per-peer and global still apply. Each layer can be independently disabled (rate == 0 with burst == 0). Backed by `governor` like `ConnectionLimiter`. - `crates/node/src/handlers/dht.rs` — `ProtocolHandler` implementing the full ADR 013 error-code mapping and the ADR 022 admission order: dispatch limiter → per-stream rate limit → routing-table refresh → dispatch. `FindNode` is fully implemented; `Store` and `FindValue` return safe placeholders (StoreAck{accepted: false}, empty providers) so the wire surface is reachable from upgraded peers. Real handling for those variants lands in PR 3 of #320. - `crates/common/src/config/{types,resolved}.rs` and resolver — `DhtConfig` / `ResolvedDht` with per-layer rate/burst pairs and a parsed trusted-IPs set. Defaults match ADR 022 (20/100/1000 req/s, 40/200/2000 burst). Pairing rules mirror the existing `security.per_source_*` resolver: rate>0 with burst=0 is rejected at config time. - `decdn_dht_rate_limit_rejected_{per_peer,per_ip,global}_total` metrics. ADR 022 §Observability specifies a single labeled counter, but `iroh_metrics::MetricsGroup` doesn't support per-field labels; we follow the existing convention (cf. `dispatch_rejected_*`) and surface one counter per layer. Operators with the ADR-022 alert form do a Prometheus `sum()` to recover the rolled-up rate. - Runtime registers `cdn/dht/v1` on the iroh router alongside `cdn/probe/v1` and `iroh-gossip`. - Loopback integration test (`tests/dht_loopback.rs`) covering a seeded routing table responding to FindNode plus the FindValue placeholder shape (pinned now so a future regression while the record store lands can't pass under the same loopback name). What's deferred (per the issue-320 plan): - Record store + Store/FindValue admission, per-publisher quota, receiver-anchored TTL, iterative lookup — PR 3. - Republish scheduler, bootstrap, on-chain origin fallback — PR 4. - BatchStore variants and prefetch — follow-up issues. Refs #320. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(node): address PR #643 review — routing-table poisoning, recursion, docs Addresses PR #643 review feedback (gemini-code-assist + Copilot): - **HIGH: drop attacker-controlled routing-table refresh.** `handle_find_node` was calling `note_peer_seen(req.requester)` on the unauthenticated wire field, letting an authenticated peer A send `FindNode { requester: B }` to inject any NodeId B into the routing table without owning the matching key (routing-table poisoning). The authenticated peer NodeId from the QUIC handshake is already refreshed once per admitted request in `serve()`, which is the only honest signal we have. Removed the second `note_peer_seen` call; added a regression test that confirms the attacker-supplied `req.requester` is NOT inserted while the authenticated client IS. - **Replace `unreachable_size_mismatch` with `std::array::from_fn`.** The previous helper recursed indefinitely on its own error path — the recursion is unreachable by construction but a future regression would stack-overflow instead of producing a clear diagnostic. `std::array::from_fn` builds the fixed-size array in place so the validation step (and the recursion) go away entirely. - **Fix inverted bucket-index comment.** The code returns bucket 255 for max distance and bucket 0 for the closest peers; the comment said the opposite. Rewrote it (and renamed the two related tests `bucket_index_max_distance_is_top_bucket` / `bucket_index_min_nonzero_is_bucket_zero`) to match the implementation. - **Re-evaluate `peer_ip` per stream.** Iroh paths can switch over a connection's lifetime (relay-only initially, then a direct UDP path becomes selected). Capturing the IP once at accept would permanently disable the per-IP rate-limit layer for any connection that started relay-only. Moved the `peer_ip(&conn)` call inside the per-stream loop so a relay→direct switch engages the layer for subsequent streams. - **Align `rate_limit.rs` doc references with the actual emitted metric names** (`decdn_dht_rate_limit_rejected_{per_peer,per_ip, global}_total` — one Counter per layer, since the metrics backend doesn't support per-field labels). - **`sort_unstable_by_key` in `RoutingTable::closest`.** Computes `xor_distance` once per element instead of twice per pairwise comparison; lower asymptotic XOR cost on fully-populated tables. - **`BatchStore`/`BatchStoreAck` dispatch arms.** PR-1 fix re-introduced these enum variants at their ADR-canonical discriminants; the handler now answers `BatchStore` with a per-hash `accepted: false` ack so publishers fall back to per-hash `Store` per ADR 022 §Schema Evolution. Handler-side admission (two-stage rate limit, holder check, per-hash quota) is the follow-up issue tracking `BatchStore` proper. Deferred to a follow-up issue (raised in PR #643 review): - Per-IP / per-peer keyed-rate-limiter keyspace cap + periodic GC (mirror of `dispatch::ConnectionLimiter::max_tracked_sources` + `retain_recent`). Same DoS shape as the dispatch limiter; meaningful fix but a self-contained chunk of work with its own runtime wiring. Refs #320, addresses #643 review. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(node): apply consolidated review fixes from PR #643 multi-agent review Round 2 of PR #643 review (after the prior poisoning/recursion/comment round). Addresses findings from five specialized review agents (code-reviewer, pr-test-analyzer, silent-failure-hunter, type-design-analyzer, comment-analyzer). CRITICAL - **BatchStore now closes the stream with `APP_ERR_UNSUPPORTED_MESSAGE` instead of replying with an all-`false` `BatchStoreAck`.** ADR 022 §STORE Flow line 138 + §Schema Evolution specify that the unsupported signal MUST be stream-close-without-ack — an all-`false` ack reads to a conformant publisher as "your batch was processed, every hash rejected" and triggers NO fallback to per-hash `Store`. The fix is structural: `read_dht_request` now narrows the wire `DhtMessage` to a new `DhtServerRequest` enum (`FindNode` / `FindValue` / `Store`), rejecting `BatchStore` and response-on-server-stream variants up front. `dispatch` is then exhaustive over the active set without a panic / echo fallback for impossible cases. Loopback test `batch_store_returns_unsupported_code_not_ack` guards the contract. - **`dht.*` wired into the SIGHUP reload pipeline.** `FileSectionSnapshot` gains a `dht` field and `log_ignored_other_sections` emits the "requires restart" warning when `[dht]` changes. Previously an operator who edited `dht.rate_limit.trusted_ips` and SIGHUPed got no feedback that the change wasn't applied. - **`[dht.rate_limit]` is now nested under `[dht]` per ADR 022 §Trusted-IP exemption.** Operator key path is `dht.rate_limit.trusted_ips` (matching the ADR), not the flat `dht.trusted_ips` from the prior commit. All six rate/burst knobs moved with it. IMPORTANT - **`DhtServerRequest` narrowing enum replaces `dispatch`'s match-all-fallback** (code-reviewer #5, silent-failure-hunter Critical #2). The previous arm echoed an empty `FindNodeResponse` if reached — dead code that masked a real protocol violation if the filter ever drifted. Removed entirely. - **`decdn_dht_requests_failed_total` counter added.** Bumps when `handle_one` returns Err after rate-limit admission (frame decode, encode, write, finish, read timeout, etc). Operator running at default `RUST_LOG=info` no longer needs to enable debug logs to see "DHT requests are failing" (silent-failure-hunter Critical #1). - **ADR 013 error-code roundtrip loopback tests** for `APP_ERR_MALFORMED_MESSAGE`, `APP_ERR_UNSUPPORTED_MESSAGE` (response on server stream + `BatchStore`), and `APP_ERR_RATE_LIMITED` (pr-test-analyzer Critical #1, #3). `APP_ERR_MESSAGE_TOO_LARGE` needs a low-level varint writer to exercise; noted in a comment. - **`closest_returns_distance_sorted_results` strengthened** to assert the full vector is monotonically non-decreasing by XOR distance, not just endpoints — catches "first and last correct, middle scrambled" regressions (pr-test-analyzer #4). - **Stale / misleading comments fixed** (comment-analyzer #2, #6, #7): routing.rs no longer claims a non-existent "follow-up PR" lands ping-then-evict; handler module docs now correctly describe the BatchStore stream-close behavior; the dispatch comment reflects the new narrowing-enum shape. DEFERRED (genuine but out of scope for this PR slice) - `NodeId` newtype (type-design-analyzer single biggest recommendation, touches the wire format + multiple crates — file as standalone follow-up). - Per-IP / per-peer keyspace bound (already issue #645). - Read-timeout app code, `FrameError::Io` mapping nuances (silent-failure-hunter MEDIUM, match existing probe handler precedent). Refs #320, addresses PR #643 multi-agent review. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
… of #320) (#646) * feat(protocol): add cdn/dht/v1 wire types (ADR 022) Introduces `DhtMessage` and the six request/response structs for the Kademlia content DHT specified in ADR 022 §Message Types: `FindValue{Request,Response}`, `Store{Request,Ack}`, `FindNode{Request,Response}`. The variant order is frozen per ADR 013 §Protocol Enums and pinned by per-variant discriminant tests so a reorder fails CI loudly rather than breaking wire compatibility silently. Authentication on `StoreRequest` is by QUIC-bound NodeId equality, not a per-record signature — this depends on records being pushed directly by the holder and never relayed peer-to-peer. The module docs flag the invariant so a future relay scheme reintroduces the signature plus in-scope sender timestamp together (ADR 015 §Replay Safety Analysis). `BatchStoreRequest` / `BatchStoreAck` are deferred to a follow-up issue. ADR 022 specifies them as a bandwidth optimization with a per-hash fallback only useful at C ≥ 10k cached blobs; when added they append after `FindNodeResponse` so existing discriminants are preserved. Wire-cap constants (`MAX_PROVIDERS_PER_HASH = 50`, `MAX_CLOSER_NODES = 20`) bound the max-size `FindValueResponse` under the ~2.3 KB ceiling from ADR 022 §DHT Bandwidth Analysis; the upper bound is asserted by a test so future field additions can't drift past it unnoticed. Refs #320. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(protocol): bound Vec wire fields and reorder DhtMessage to ADR-canonical Addresses PR #642 review feedback (gemini-code-assist + Copilot): - Add `#[serde(deserialize_with = ...)]` field-level hooks enforcing `MAX_PROVIDERS_PER_HASH`, `MAX_CLOSER_NODES`, and `MAX_BATCH_STORE_HASHES` at the wire boundary. Pattern mirrors `ProbeResponseBody::rate_per_mb`: postcard's positional layout stays derive-driven (no mirror struct, no manual `Deserialize` impl), and oversize Vec fields now fail decode rather than allocating an attacker-chosen size up to the 16 MiB framing ceiling. - Reorder `DhtMessage` variants to match ADR 022 §Message Types: the ADR lists `BatchStore`/`BatchStoreAck` at positions 4/5 and `FindNode`/`FindNodeResponse` at 6/7. The original PR put `FindNode` at 4/5; with postcard's sequential discriminant indexing this would have forced a future wire-breaking shuffle once `BatchStore` lands. Define the `BatchStore` wire types now (no handler) so the production ordering matches the ADR and the future BatchStore PR is a pure handler addition. - Replace the inner-struct-only size guard with a framed-size assertion that includes the `DhtMessage` enum discriminant byte AND the `write_frame` length-prefix varint, so the ~2.3 KB ADR 022 wire ceiling can't drift via discriminant or framing-layer changes. - New tests: discriminant pinning for `BatchStore` (4) / `BatchStoreAck` (5) / `FindNode` (6) / `FindNodeResponse` (7); decode-time rejection for oversize `providers`, `closer_nodes`, `BatchStore.hashes`, and `BatchStoreAck.results`; exact-MAX boundary acceptance. Refs #320, addresses #642 review. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test(protocol): add lower bound + align BatchStore module doc Round 2 of PR #642 review (pr-test-analyzer + comment-analyzer). - `find_value_response_max_framed_size_under_ceiling` previously had only `framed_len <= 2_300`. A regression that dropped `providers` or `closer_nodes` from the wire shape would shrink the encoded size well below the ADR's modeled payload (~2.27 KB) and the test would silently pass. Add `framed_len > 2_000` so an accidental field removal fails the test loudly. - Module-level doc for `BatchStore` previously said the runtime "treats inbound BatchStore frames as unsupported until then." After the PR-#643 fix the handler explicitly closes the stream with `APP_ERR_UNSUPPORTED_MESSAGE` (the stream-close-without-ack signal ADR 022 §Schema Evolution requires); the doc now reflects the precise wire behaviour and cites the matching ADR section. Refs #320, addresses PR #642 multi-agent review. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * feat(node): add cdn/dht/v1 handler, routing table, rate limiter (ADR 022) PR 2 of 4 for #320 (Kademlia content discovery). Wires the `cdn/dht/v1` handler skeleton into the runtime and lands the routing table + rate limiter the rest of the DHT machinery will build on. What's in: - `crates/node/src/dht/routing.rs` — k-bucket routing table at K=20, 256 buckets keyed by XOR distance to the node's own NodeId (ADR 022 §Routing Table). LRU eviction on bucket overflow; the ping-then-evict variant is deferred until the FindNode driver lands in PR 4 of #320. Self-id inserts are no-ops so iterative lookup never terminates on the local table. - `crates/node/src/dht/rate_limit.rs` — three-layer token-bucket limiter (per-peer NodeId, per-IP, global) with cheapest-first short-circuit per ADR 022 §DHT Rate Limiting. Trusted-IP exemption bypasses the per-IP layer only; per-peer and global still apply. Each layer can be independently disabled (rate == 0 with burst == 0). Backed by `governor` like `ConnectionLimiter`. - `crates/node/src/handlers/dht.rs` — `ProtocolHandler` implementing the full ADR 013 error-code mapping and the ADR 022 admission order: dispatch limiter → per-stream rate limit → routing-table refresh → dispatch. `FindNode` is fully implemented; `Store` and `FindValue` return safe placeholders (StoreAck{accepted: false}, empty providers) so the wire surface is reachable from upgraded peers. Real handling for those variants lands in PR 3 of #320. - `crates/common/src/config/{types,resolved}.rs` and resolver — `DhtConfig` / `ResolvedDht` with per-layer rate/burst pairs and a parsed trusted-IPs set. Defaults match ADR 022 (20/100/1000 req/s, 40/200/2000 burst). Pairing rules mirror the existing `security.per_source_*` resolver: rate>0 with burst=0 is rejected at config time. - `decdn_dht_rate_limit_rejected_{per_peer,per_ip,global}_total` metrics. ADR 022 §Observability specifies a single labeled counter, but `iroh_metrics::MetricsGroup` doesn't support per-field labels; we follow the existing convention (cf. `dispatch_rejected_*`) and surface one counter per layer. Operators with the ADR-022 alert form do a Prometheus `sum()` to recover the rolled-up rate. - Runtime registers `cdn/dht/v1` on the iroh router alongside `cdn/probe/v1` and `iroh-gossip`. - Loopback integration test (`tests/dht_loopback.rs`) covering a seeded routing table responding to FindNode plus the FindValue placeholder shape (pinned now so a future regression while the record store lands can't pass under the same loopback name). What's deferred (per the issue-320 plan): - Record store + Store/FindValue admission, per-publisher quota, receiver-anchored TTL, iterative lookup — PR 3. - Republish scheduler, bootstrap, on-chain origin fallback — PR 4. - BatchStore variants and prefetch — follow-up issues. Refs #320. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(node): address PR #643 review — routing-table poisoning, recursion, docs Addresses PR #643 review feedback (gemini-code-assist + Copilot): - **HIGH: drop attacker-controlled routing-table refresh.** `handle_find_node` was calling `note_peer_seen(req.requester)` on the unauthenticated wire field, letting an authenticated peer A send `FindNode { requester: B }` to inject any NodeId B into the routing table without owning the matching key (routing-table poisoning). The authenticated peer NodeId from the QUIC handshake is already refreshed once per admitted request in `serve()`, which is the only honest signal we have. Removed the second `note_peer_seen` call; added a regression test that confirms the attacker-supplied `req.requester` is NOT inserted while the authenticated client IS. - **Replace `unreachable_size_mismatch` with `std::array::from_fn`.** The previous helper recursed indefinitely on its own error path — the recursion is unreachable by construction but a future regression would stack-overflow instead of producing a clear diagnostic. `std::array::from_fn` builds the fixed-size array in place so the validation step (and the recursion) go away entirely. - **Fix inverted bucket-index comment.** The code returns bucket 255 for max distance and bucket 0 for the closest peers; the comment said the opposite. Rewrote it (and renamed the two related tests `bucket_index_max_distance_is_top_bucket` / `bucket_index_min_nonzero_is_bucket_zero`) to match the implementation. - **Re-evaluate `peer_ip` per stream.** Iroh paths can switch over a connection's lifetime (relay-only initially, then a direct UDP path becomes selected). Capturing the IP once at accept would permanently disable the per-IP rate-limit layer for any connection that started relay-only. Moved the `peer_ip(&conn)` call inside the per-stream loop so a relay→direct switch engages the layer for subsequent streams. - **Align `rate_limit.rs` doc references with the actual emitted metric names** (`decdn_dht_rate_limit_rejected_{per_peer,per_ip, global}_total` — one Counter per layer, since the metrics backend doesn't support per-field labels). - **`sort_unstable_by_key` in `RoutingTable::closest`.** Computes `xor_distance` once per element instead of twice per pairwise comparison; lower asymptotic XOR cost on fully-populated tables. - **`BatchStore`/`BatchStoreAck` dispatch arms.** PR-1 fix re-introduced these enum variants at their ADR-canonical discriminants; the handler now answers `BatchStore` with a per-hash `accepted: false` ack so publishers fall back to per-hash `Store` per ADR 022 §Schema Evolution. Handler-side admission (two-stage rate limit, holder check, per-hash quota) is the follow-up issue tracking `BatchStore` proper. Deferred to a follow-up issue (raised in PR #643 review): - Per-IP / per-peer keyed-rate-limiter keyspace cap + periodic GC (mirror of `dispatch::ConnectionLimiter::max_tracked_sources` + `retain_recent`). Same DoS shape as the dispatch limiter; meaningful fix but a self-contained chunk of work with its own runtime wiring. Refs #320, addresses #643 review. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(node): apply consolidated review fixes from PR #643 multi-agent review Round 2 of PR #643 review (after the prior poisoning/recursion/comment round). Addresses findings from five specialized review agents (code-reviewer, pr-test-analyzer, silent-failure-hunter, type-design-analyzer, comment-analyzer). CRITICAL - **BatchStore now closes the stream with `APP_ERR_UNSUPPORTED_MESSAGE` instead of replying with an all-`false` `BatchStoreAck`.** ADR 022 §STORE Flow line 138 + §Schema Evolution specify that the unsupported signal MUST be stream-close-without-ack — an all-`false` ack reads to a conformant publisher as "your batch was processed, every hash rejected" and triggers NO fallback to per-hash `Store`. The fix is structural: `read_dht_request` now narrows the wire `DhtMessage` to a new `DhtServerRequest` enum (`FindNode` / `FindValue` / `Store`), rejecting `BatchStore` and response-on-server-stream variants up front. `dispatch` is then exhaustive over the active set without a panic / echo fallback for impossible cases. Loopback test `batch_store_returns_unsupported_code_not_ack` guards the contract. - **`dht.*` wired into the SIGHUP reload pipeline.** `FileSectionSnapshot` gains a `dht` field and `log_ignored_other_sections` emits the "requires restart" warning when `[dht]` changes. Previously an operator who edited `dht.rate_limit.trusted_ips` and SIGHUPed got no feedback that the change wasn't applied. - **`[dht.rate_limit]` is now nested under `[dht]` per ADR 022 §Trusted-IP exemption.** Operator key path is `dht.rate_limit.trusted_ips` (matching the ADR), not the flat `dht.trusted_ips` from the prior commit. All six rate/burst knobs moved with it. IMPORTANT - **`DhtServerRequest` narrowing enum replaces `dispatch`'s match-all-fallback** (code-reviewer #5, silent-failure-hunter Critical #2). The previous arm echoed an empty `FindNodeResponse` if reached — dead code that masked a real protocol violation if the filter ever drifted. Removed entirely. - **`decdn_dht_requests_failed_total` counter added.** Bumps when `handle_one` returns Err after rate-limit admission (frame decode, encode, write, finish, read timeout, etc). Operator running at default `RUST_LOG=info` no longer needs to enable debug logs to see "DHT requests are failing" (silent-failure-hunter Critical #1). - **ADR 013 error-code roundtrip loopback tests** for `APP_ERR_MALFORMED_MESSAGE`, `APP_ERR_UNSUPPORTED_MESSAGE` (response on server stream + `BatchStore`), and `APP_ERR_RATE_LIMITED` (pr-test-analyzer Critical #1, #3). `APP_ERR_MESSAGE_TOO_LARGE` needs a low-level varint writer to exercise; noted in a comment. - **`closest_returns_distance_sorted_results` strengthened** to assert the full vector is monotonically non-decreasing by XOR distance, not just endpoints — catches "first and last correct, middle scrambled" regressions (pr-test-analyzer #4). - **Stale / misleading comments fixed** (comment-analyzer #2, #6, #7): routing.rs no longer claims a non-existent "follow-up PR" lands ping-then-evict; handler module docs now correctly describe the BatchStore stream-close behavior; the dispatch comment reflects the new narrowing-enum shape. DEFERRED (genuine but out of scope for this PR slice) - `NodeId` newtype (type-design-analyzer single biggest recommendation, touches the wire format + multiple crates — file as standalone follow-up). - Per-IP / per-peer keyspace bound (already issue #645). - Read-timeout app code, `FrameError::Io` mapping nuances (silent-failure-hunter MEDIUM, match existing probe handler precedent). Refs #320, addresses PR #643 multi-agent review. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * feat(node,cache): record store + Store/FindValue + cache hook (ADR 022) PR 3 of 4 for #320 (Kademlia content discovery). Replaces the PR-2 placeholder responses with the spec-conformant admission pipeline and exposes the cache → DHT republish hook that PR 4 will consume. What's in: - `crates/node/src/dht/records.rs` — receiver-side `RecordStore` enforcing the ADR 022 §Content Records and TTL admission rules: * Per-publisher cap of 200 records — hard reject above cap. * Global cap of 100k records — global LRU eviction when over cap and the inserting publisher is below their per-publisher cap. * Per-hash provider cap of 50 — evict oldest holder for that hash. * Receiver-anchored TTL of 1 hour; refresh-in-place on re-publish (no double-count against the publisher quota). * Periodic GC sweep + on-demand expiry scrub on every providers lookup. - `crates/node/src/dht/staker_set.rs` — `StakerSet` trait + file- config-driven `ConfigStakerSet`. The chain-backed `ChainStakerSet` that reads `StakingRegistry.getActiveNodes()` lives in the on-chain origin-directory follow-up issue; same trait, drop-in swap. - `handlers/dht.rs` — real `Store` admission (holder == authenticated NodeId → active-staker filter → record-store insert) and real `FindValue` (record-store providers + routing-table closer_nodes). Per ADR 022 §Lookup integrity the requester-side filters (XOR- distance check, active-staker filter, negative-probe-cache, randomisation) belong on the iterative-lookup side and land with PR 4 of #320 — the responder is intentionally minimal here. - `crates/cache/src/engine.rs` — `CacheEngine::subscribe_inserts()` broadcast hook. Emits the committed hash from the `pull_through` success arm (the single convergence point for streaming + buffered commits); the local-store-hit short-circuit deliberately does NOT emit (a hit doesn't start a new TTL cycle). - `dht.static_active_nodes` config field — operator-supplied 64-char hex `NodeId` list parsed via the existing `parse_node_id_hex` helper; malformed entries fail config resolution. What's deferred (per the issue-320 plan): - Iterative requester-side `FindValue` lookup (α=3 parallelism, three requester-side filters from ADR 022 §Lookup integrity, provider-set randomisation) — PR 4 of #320, where it pairs naturally with the bootstrap and republish-scheduler call sites. - Republish scheduler that consumes `subscribe_inserts` and pushes `Store` to the K+3 closest peers with jittered (30–50 min) cadence — PR 4 of #320. - Subscribe-to-staker-changes (broadcast channel on `StakerSet`) — the current `ConfigStakerSet` set is immutable post-startup, so the subscriber surface doesn't pay rent yet. Tests: - 11 new `RecordStore` unit tests covering insert / refresh / quota / global LRU / per-hash cap / TTL / GC. - 4 new `ConfigStakerSet` tests. - 2 new `CacheEngine::subscribe_inserts` tests: emit on pull-through success, NO emit on cache hit. - 3 new DHT loopback tests under `store_admission`: round-trip for a staked publisher; rejection for a non-staked publisher; rejection when `holder != authenticated NodeId` (lying-`holder` attack). Refs #320. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(node,common): address PR #646 multi-bot review (TTL drift, eviction, GC) Addresses PR #646 review (Copilot + gemini-code-assist): Correctness: - **TTL no longer drifts with insert volume.** Previously `monotonic_tail` was added directly into `receive_us` and propagated into `expiry_us`, so 1M unrelated inserts shifted a record's expiry forward by ~1s; 1B inserts ~17 min — material against the 1-hour TTL. Per ADR 022 §Content Records and TTL line 122, `expiry_us = receive_us + ttl_us` is the contract. Replaced with a separate `sequence` field that's used only as the second component of the `global_lru` key, never mixed into time-domain values. Regression test: a record inserted at wall-clock 500 with `ttl_us = 1_000` has `expiry_us == 1_500` exact after 10k unrelated prior inserts. - **No more "two evictions for one insert".** The prior order was "global LRU first, then per-hash cap" — when both were full this evicted an unrelated record AND a per-hash holder for one insert, leaving the store under-full by one and dropping an unrelated hash's oldest holder. Per-hash cap now fires first; the global LRU is skipped when the per-hash eviction already nets the store out at the same global count. Regression test pins both invariants. - **Periodic record-store GC task added.** Without it, expired records accumulated against the per-publisher and global caps until any query for the specific hash forced a scrub. A publisher who put one record and stopped requesting it would eventually fill its 200-record quota with stale entries and have every future `Store` rejected. The task runs on the existing `DISPATCH_GC_INTERVAL` (60s) and shuts down via the same `oneshot` shape as `run_dispatch_gc`. - **`RecordStore::gc` now `O(expired × log N)` instead of `O(N)`.** Since `ttl_us` is constant, `global_lru` (ordered by `receive_us`) is also ordered by `expiry_us` — pop the front until non-expired and stop. gemini-code-assist's exact suggestion. Cleanup: - `parse_node_id_hex`'s error message is now field-agnostic ("must be 64 hex chars, got X"). Callers (`gossip.allowlist[idx]` and `dht.static_active_nodes`) already wrap with the field path; the helper no longer hardcodes "gossip.allowlist". - `AllStaked` test stub: `len()` now returns 0 to stay consistent with the empty `active_nodes()` (was `usize::MAX`, an inconsistency the bot flagged). Doc on the helper now spells out that it's not enumerable — tests that need a concrete set use `ConfigStakerSet`. Tests: - 2 new `RecordStore` unit tests pinning the TTL-no-drift and no-double-eviction contracts. - Existing 12 record-store + 4 staker-set + 2 cache subscribe + 10 DHT loopback tests still green (998/998 workspace). Refs #320, addresses PR #646 review. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(node,cache): apply PR #646 round-3 review (correctness + comments + tests) Five-agent review on PR #646 surfaced 4 correctness issues, 6 comment factual errors, and several test gaps. Correctness: - **Empty staker-set startup warning** — `dht.static_active_nodes` missing silently rejects every `Store` (ADR 022 line 140). Runtime now logs `warn!` at startup when the set is empty so the failure mode is one high-signal line, not silent per-request debug rejections. - **`now_us()` clock-broken log** — `SystemTime` before-UNIX-EPOCH used to silently fall back to `receive_us=0`, collapsing every record to the same `expiry_us` and triggering mass eviction at the 1-hour mark when the clock recovered. Now logs `error!` once per affected insert so the operator sees the host-clock fault. Fallback keeps the store functional in the degraded state. - **Refresh corruption-path** — `entries.get_mut(idx)` returning `None` after `position()` returned `Some(idx)` used to surface as `InsertOutcome::Refreshed` → `accepted: true` on the wire, confirming a write that never happened. Now returns `RejectedQuotaExceeded` and logs `error!` with full context. - **Store-rejection metrics** — three new counters (`decdn_dht_store_rejected_holder_mismatch_total`, `decdn_dht_store_rejected_non_staked_total`, `decdn_dht_store_rejected_quota_total`) plus `decdn_dht_store_accepted_total`. Lying-holder + non-staked + quota-exhaustion are operator-actionable security/abuse signals that previously needed `RUST_LOG=debug` to see. Comment factual errors: - `cache/engine.rs:765` line citation 124 → 126 (the quoted "When a node caches blob H" sits at line 126, not the section header at 124). - `handlers/dht.rs:527` "PR-2-of-#320 slice" → "this slice" (the file is now PR 3). - `handlers/dht.rs:530` "§Schema Evolution line 138" was misattributed; line 138 is in §STORE Flow. Now reads "§STORE Flow line 138 + §Schema Evolution". - `handlers/dht.rs:301` dispatch by-value comment referenced `FindValueResponse` (the response shape); the function takes request variants. Now says "request variants whose payloads include Vec fields (e.g. a `BatchStoreRequest::hashes` once the handler-side admission lands)". - `records.rs:451` test comment claimed "receive_us is monotonic- counter-mixed"; that was the pre-fix behaviour. Now asserts exact equality with `receive_us = 200` + `expiry_us = 200 + ttl_us`. - `records.rs:587/600` test internally cited 10k AND 100k AND 1M unrelated inserts; only 10k is real. All references now match. Tests: - `default_config_matches_adr_022` pins the four `RecordStoreConfig` defaults (200 / 100k / 50 / 1h) against the ADR 022 §Content Records and TTL table. Without it, a regression that halved any value would pass the entire existing test suite (all use `small_cfg()`). - `publisher_quota_beats_global_lru` regression-pins the rule that a publisher at their per-publisher cap hard-rejects WITHOUT touching the global LRU — a future refactor that swapped check order would let quota-exceeded publishers displace other publishers' records. - `run_record_store_gc_exits_promptly_on_shutdown` mirrors the `run_dispatch_gc_exits_promptly_on_shutdown` precedent: a regression that reorders the `tokio::select!` arms or drops `biased` would silently extend `SHUTDOWN_DEADLINE` by up to 60s. Pushed back / filed for follow-up: - Extracting `add_entry`/`remove_entry` helpers to make the tri-index `RecordStore` invariant structural rather than convention. Real recommendation; non-trivial refactor that's well-covered by the existing regression tests today. Worth doing but not in this PR. - Stripping unused `StakerSet::{active_nodes, len, is_empty}` (YAGNI). `active_nodes` is the bootstrap surface PR 4 needs, and trait methods are harder to add once an external impl exists. Keep. - `Hash` type alias same fate as `NodeId` (already a filed follow-up). 1001/1001 workspace tests pass. Clippy + fmt + cargo doc + cargo deny + ADR-hygiene hooks all clean. Refs #320, addresses PR #646 round-3 review. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * refactor(node): drop dht.static_active_nodes; wire empty StakerSet pending PR 4 Per review discussion: maintaining a TOML-file mirror of StakingRegistry.getActiveNodes() invites drift (operators omitting stakers, censoring, forgetting to update). Drop the config surface now — the chain-backed StakerSet is what ADR 022 §STORE Flow line 140 specifies, and PR 4 of #320 already needs the same on-chain read for bootstrap, so it's the natural home for ChainStakerSet too. Until PR 4 lands, the runtime wires ConfigStakerSet::empty() with a loud startup warn. The cache → DHT republish hook exposed in this PR has no producer yet (PR 4 brings the scheduler), so no publisher-side traffic is gated either. Tests build StakerSet programmatically via ConfigStakerSet::{new, empty} and are unaffected. The StakerSet trait and ConfigStakerSet remain exported (tests still use them; runtime swap is one line when ChainStakerSet lands). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
crates/protocol/src/dht.rsdefiningDhtMessageand the six request/response structs (FindValue{Request,Response},Store{Request,Ack},FindNode{Request,Response}) per ADR 022 §Message Types.crates/protocol/src/lib.rs.MAX_PROVIDERS_PER_HASH = 50andMAX_CLOSER_NODES = 20bound the max-sizeFindValueResponseunder ADR 022's ~2.3 KB ceiling; the upper bound is asserted by a test.Context
This is PR 1 of 4 for #320 (Kademlia content DHT). Subsequent PRs in the stack:
crates/node).StakerSettrait + file-config impl,CacheEngine::subscribe_insertsbroadcast hook.OriginDirectorytrait + alloysol!placeholders for the on-chain fallback.BatchStoreRequest/BatchStoreAckand the prefetch/popularity surface (ACs 7–8 / 17–20) are deferred to follow-up issues per the approved plan; ACs 17–20 in particular preserve the existing discriminant freezing by appending afterFindNodeResponsewhen added.Design notes
StoreRequesthas no per-record signature. The receiver checksholder == authenticated QUIC NodeId. This depends on records being pushed directly by the holder and never relayed peer-to-peer; the module docs flag the invariant so a future relay scheme reintroduces the signature plus an in-scope sender timestamp together (ADR 015 §Replay Safety Analysis).[u8; 32], matching the existingProbeRequest::hashandNodeAnnounceBody::node_idpattern. The protocol crate stays leaf — no iroh dep needed.Test plan
cargo nextest run -p decdn-protocol— 58/58 pass (15 new tests).cargo clippy -p decdn-protocol --all-targets -- -D warningsclean.cargo fmt -- --checkclean.cargo nextest run— 933/933 pass.pre-commit run --files crates/protocol/src/dht.rs crates/protocol/src/lib.rs— all hooks pass (fmt, clippy, doc, deny).DhtMessagevariants.FindValueResponse(50 providers + 20 closer_nodes) asserted ≤ 2.3 KB.Refs #320.
🤖 Generated with Claude Code