Skip to content

feat(protocol+node): promote NodeId/Hash from aliases to newtypes (#653) - #726

Merged
alpergundogdu merged 3 commits into
mainfrom
feat/653-nodeid-contenthash-newtypes
May 30, 2026
Merged

alpergundogdu merged 3 commits into
mainfrom
feat/653-nodeid-contenthash-newtypes

Conversation

@thiras

@thiras thiras commented May 30, 2026

Copy link
Copy Markdown
Contributor

Summary

Promotes node-identity and content-hash values from raw [u8; 32] (and the node-crate local aliases routing::NodeId, records::Hash, origin::Hash) to distinct #[repr(transparent)] #[serde(transparent)] newtypes decdn_protocol::NodeId and decdn_protocol::ContentHash.

The wire format is byte-for-byte unchanged — postcard sees the same 32 raw bytes, so no discriminant tests move and no ALPN bump is required. A new proof test nodeid_postcard_identical_to_array pins this invariant.

Closes #653.

Security crux: AuthenticatedNodeId

The motivating bug (routing-table poisoning, caught in PR #643) was an authenticated peer A passing req.requester = B and having B inserted into A's routing table — previously prevented only by a hand-written comment.

This PR adds decdn_node::dht::AuthenticatedNodeId (in dht/auth.rs), constructible only from a live QUIC connection's remote_id(). There is no From<NodeId> / From<[u8;32]> impl, so wire data cannot fabricate one. handle_store / handle_batch_store / note_peer_seen now take AuthenticatedNodeId, forcing an explicit .node_id() at every req.holder comparison and at the only handler→routing-table insertion path. A future note_peer_seen(req.requester) is now a compile error.

The legitimate Kademlia path (lookup/bucket-refresh inserting wire-discovered NodeIds as probe candidates) keeps RoutingTable::insert(NodeId) — those are not asserted-live peers.

CloserNodes wrapper

Per the issue's "consider also", closer_nodes fields are now a CloserNodes newtype that enforces the MAX_CLOSER_NODES cap at construction (try_new) as well as at decode (its Deserialize), replacing the old deserialize_closer_nodes hook.

Design notes

  • A ContentHash and a NodeId share the 256-bit XOR keyspace (ADR 022). routing gains xor_distance_bytes(&[u8;32], &[u8;32]), and closest/closest_unbounded take a raw keyspace point so the FindValue (hash) and FindNode (id) paths both fit — no fake-wrapping a hash as a NodeId.
  • Named ContentHash (not Hash) to avoid colliding with the existing decdn_config_types::Hash.
  • No Deref<Target=[u8;32]> — it would re-expose panicking slice indexing under the workspace indexing_slicing lint and dissolve the type boundary. Byte access is the explicit as_bytes()/from_bytes().
  • The issue's ResolvedDht.static_active_nodes bullet was stale — no such field exists (the active-staker set is a runtime StakerSet trait), so it was a no-op.

Verification

  • cargo fmt -- --check ✅
  • cargo clippy --workspace --all-targets ✅ (anti-panic lints clean)
  • cargo nextest run --workspace ✅ 1181 passed, 0 skipped
  • New wire-compat proof: NodeId([0u8;32]) serializes identically to [0u8;32]; all existing roundtrip / *_discriminant_is_* / oversize-reject / max-framed-size / trailing-byte tests pass with assertion logic unchanged.

🤖 Generated with Claude Code

Promote node-identity and content-hash values from raw `[u8; 32]` (and the
node-crate local aliases `routing::NodeId`, `records::Hash`, `origin::Hash`)
to distinct `#[repr(transparent)] #[serde(transparent)]` newtypes
`decdn_protocol::NodeId` and `decdn_protocol::ContentHash`. The wire format is
byte-for-byte unchanged — postcard sees the same 32 raw bytes, so no
discriminant tests move and no ALPN bump is required
(`nodeid_postcard_identical_to_array` pins this).

The security crux is the new node-crate `AuthenticatedNodeId` (in
`dht/auth.rs`), constructible ONLY from a live QUIC connection's
`remote_id()` — there is no `From<NodeId>`/`From<[u8;32]>` impl, so wire data
cannot fabricate one. `handle_store`/`handle_batch_store`/`note_peer_seen` now
take `AuthenticatedNodeId`, forcing an explicit `.node_id()` at the
`req.holder` comparison and making the routing-table-poisoning bug class caught
in PR #643 (inserting a wire-provided `requester`) a compile error.

Also adds the `CloserNodes` wrapper (issue "consider also"): the
`MAX_CLOSER_NODES` cap is now enforced at construction and decode by the type
rather than only by a `deserialize_with` hook.

Notes:
- ContentHash and NodeId share the 256-bit XOR keyspace; `routing` gains
  `xor_distance_bytes(&[u8;32],&[u8;32])` and `closest`/`closest_unbounded`
  take a raw keyspace point so the FindValue (hash) and FindNode (id) paths
  both fit without fake-wrapping a hash as a NodeId.
- Named `ContentHash` (not `Hash`) to avoid colliding with
  `decdn_config_types::Hash`.
- The stale issue bullet about `ResolvedDht.static_active_nodes` was a no-op —
  no such field exists (active-staker set is a runtime `StakerSet` trait).

Verified: `cargo fmt --check`, `cargo clippy --workspace --all-targets`,
`cargo nextest run --workspace` (1181 passed).

Closes #653

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 30, 2026 14:40

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces strongly-typed 32-byte identity newtypes (NodeId and ContentHash) to replace raw [u8; 32] arrays, establishing a compile-time trust boundary that prevents routing-table-poisoning bugs. It also introduces CloserNodes to enforce size limits on the wire and AuthenticatedNodeId to wrap authenticated connection identities. Feedback on the changes highlights a performance improvement opportunity in closest_unbounded, where pre-computing XOR distances instead of using sort_unstable_by_key would avoid redundant key computations on a hot path.

Comment thread crates/node/src/dht/routing.rs Resolved
@github-actions

github-actions Bot commented May 30, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 89.42% (was 89.40%, ▲ +0.02%) — 22095/24710 lines

File Coverage Lines Δ
crates/node/src/dht/auth.rs 100.00% 6/6 new
crates/node/src/dht/batch_fallback.rs 94.12% 112/119 ● 0.00%
crates/node/src/dht/bootstrap.rs 82.35% 84/102 ● 0.00%
crates/node/src/dht/bucket_refresh.rs 57.40% 97/169 ● 0.00%
crates/node/src/dht/chain_staker_set.rs 20.33% 50/246 ● 0.00%
crates/node/src/dht/client.rs 76.95% 197/256 ● 0.00%
crates/node/src/dht/lookup.rs 96.74% 415/429 ▲ +0.03%
crates/node/src/dht/negative_cache.rs 95.42% 125/131 ● 0.00%
crates/node/src/dht/origin.rs 100.00% 40/40 ● 0.00%
crates/node/src/dht/publish.rs 85.89% 213/248 ● 0.00%
crates/node/src/dht/rate_limit.rs 99.67% 602/604 ● 0.00%
crates/node/src/dht/records.rs 98.82% 418/423 ● 0.00%
crates/node/src/dht/routing.rs 97.46% 269/276 ▲ +0.08%
crates/node/src/dht/staker_set.rs 95.31% 61/64 ● 0.00%
crates/node/src/handlers/dht.rs 74.86% 262/350 ▼ 0.43%
crates/node/src/runtime/mod.rs 50.10% 510/1018 ▼ 0.10%
crates/protocol/src/dht.rs 98.96% 379/383 ▼ 0.75%
crates/protocol/src/identity.rs 100.00% 36/36 new
History
Commit Total Δ vs base
29136d1 89.41% ▲ +0.01%
7002167 89.41% ▲ +0.01%
b7615ef (HEAD) 89.42% ▲ +0.02%

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR strengthens DHT identity/content typing by replacing raw 32-byte aliases with protocol newtypes and adding an authenticated-node trust-boundary type for handler-side routing/store decisions.

Changes:

  • Adds NodeId, ContentHash, and bounded CloserNodes protocol types while preserving postcard wire compatibility.
  • Migrates DHT routing, records, lookup, publish, bootstrap, client, handler, and tests to the newtypes.
  • Introduces AuthenticatedNodeId for QUIC-authenticated peer identity and updates handler admission/routing paths to use it.

Reviewed changes

Copilot reviewed 24 out of 24 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
crates/protocol/src/lib.rs Exports identity and DHT wrapper types.
crates/protocol/src/identity.rs Defines NodeId and ContentHash newtypes.
crates/protocol/src/dht.rs Migrates DHT wire structs to newtypes and adds CloserNodes.
crates/node/src/dht/auth.rs Adds authenticated peer identity wrapper.
crates/node/src/dht/mod.rs Exposes the auth module/type.
crates/node/src/handlers/dht.rs Uses authenticated peer identity for handler routing/store paths.
crates/node/src/dht/routing.rs Migrates routing table to NodeId and raw-byte XOR keys.
crates/node/src/dht/records.rs Re-exports ContentHash as record hash type.
crates/node/src/dht/origin.rs Aligns origin hash type with record hash newtype.
crates/node/src/dht/negative_cache.rs Updates tests/helpers for new hash and node types.
crates/node/src/dht/staker_set.rs Updates staker set tests/helpers for NodeId.
crates/node/src/dht/chain_staker_set.rs Converts chain bytes32 node IDs into NodeId.
crates/node/src/dht/rate_limit.rs Updates rate limiter tests/helpers for NodeId.
crates/node/src/dht/client.rs Updates DHT client API to use NodeId/ContentHash.
crates/node/src/dht/lookup.rs Uses cross-domain XOR bytes for content-hash lookup.
crates/node/src/dht/publish.rs Migrates republish scheduling and store fanout to ContentHash.
crates/node/src/dht/bootstrap.rs Uses NodeId for seeds and learned peers.
crates/node/src/dht/bucket_refresh.rs Uses NodeId for refresh targets and referrals.
crates/node/src/dht/batch_fallback.rs Updates test helper for NodeId.
crates/node/src/runtime/mod.rs Bridges cached blob hashes into ContentHash for republish seeding.
crates/node/tests/dht_loopback.rs Updates loopback DHT tests to newtypes.
crates/node/tests/dht_lookup.rs Updates lookup tests to newtypes.
crates/node/tests/dht_integration.rs Updates integration tests to newtypes.
crates/node/tests/dht_bootstrap.rs Updates bootstrap/client tests to newtypes.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread crates/node/src/dht/auth.rs Resolved
Comment thread crates/protocol/src/dht.rs Resolved
Comment thread crates/protocol/src/dht.rs Resolved
thiras and others added 2 commits May 30, 2026 17:50
…e XOR keys

- AuthenticatedNodeId::from_remote_id(&PublicKey) -> from_connection(&Connection):
  a PublicKey can be minted from arbitrary bytes, so the old constructor did not
  actually enforce the "only from a live QUIC connection" boundary. A Connection's
  remote_id is set only by the handshake, so this closes the fabrication path.
- FindValueRequest/FindNodeRequest `requester` docs: stop claiming the responder
  uses the wire value for routing-table updates — it deliberately ignores it and
  refreshes only the authenticated QUIC peer. The old docs could lead a future
  implementer to reintroduce the routing-table-poisoning bug.
- RoutingTable::closest_unbounded: compute xor_distance_bytes once per candidate
  (Schwartzian transform) instead of via sort_unstable_by_key, which does not
  cache its key and would recompute the XOR O(n log n) times on the hot path. The
  old comment claiming the key was cached was incorrect.

Verified: cargo fmt --check, clippy --workspace --all-targets, nextest (396 passed).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Polish from a comprehensive review (no bugs found; all items doc/test accuracy):

- identity.rs: the `from_bytes` const-fn doc claimed it enables a `const fn`
  routing-table construction that doesn't exist (RoutingTable::new is a plain
  fn) — reword to the real reason (const-context + accessor consistency).
- identity.rs test: assert `ContentHash` *decodes* from the bare-[u8;32]
  encoding too (the test pinned NodeId decode but only ContentHash encode; the
  no-ALPN-bump claim needs both directions for both types).
- dht.rs: add `closer_nodes_try_new_enforces_cap` — the construction-time cap
  that the type's docs advertise had no direct test (only the decode path did).
- auth.rs: add a "# Scope" note clarifying the boundary covers the handler's
  requester/holder-substitution decisions, NOT every routing insert — the
  iterative-lookup/bucket-refresh/bootstrap paths legitimately insert
  response-learned NodeIds as probe candidates by design. Mirror that with a
  one-line comment at the two response-learned insert sites.
- routing.rs: correct the `closest` cost comment to match the new Schwartzian
  transform (XOR once + sort over cached distances, not "XOR-compares").

Verified: cargo fmt --check, clippy --all-targets, doc, nextest (397 passed).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@thiras
thiras requested a review from alpergundogdu May 30, 2026 15:13
@alpergundogdu
alpergundogdu merged commit eccb73f into main May 30, 2026
19 checks passed
@alpergundogdu
alpergundogdu deleted the feat/653-nodeid-contenthash-newtypes branch May 30, 2026 17:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Protocol+node: promote NodeId and Hash from type aliases to newtypes

3 participants