Repository navigation
feat(protocol+node): promote NodeId/Hash from aliases to newtypes (#653) - #726
Conversation
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]>
There was a problem hiding this comment.
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.
Coverage reportTotal: 89.42% (was 89.40%, ▲ +0.02%) — 22095/24710 lines
History
|
There was a problem hiding this comment.
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 boundedCloserNodesprotocol types while preserving postcard wire compatibility. - Migrates DHT routing, records, lookup, publish, bootstrap, client, handler, and tests to the newtypes.
- Introduces
AuthenticatedNodeIdfor 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.
…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]>
Summary
Promotes node-identity and content-hash values from raw
[u8; 32](and the node-crate local aliasesrouting::NodeId,records::Hash,origin::Hash) to distinct#[repr(transparent)] #[serde(transparent)]newtypesdecdn_protocol::NodeIdanddecdn_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_arraypins this invariant.Closes #653.
Security crux:
AuthenticatedNodeIdThe motivating bug (routing-table poisoning, caught in PR #643) was an authenticated peer A passing
req.requester = Band having B inserted into A's routing table — previously prevented only by a hand-written comment.This PR adds
decdn_node::dht::AuthenticatedNodeId(indht/auth.rs), constructible only from a live QUIC connection'sremote_id(). There is noFrom<NodeId>/From<[u8;32]>impl, so wire data cannot fabricate one.handle_store/handle_batch_store/note_peer_seennow takeAuthenticatedNodeId, forcing an explicit.node_id()at everyreq.holdercomparison and at the only handler→routing-table insertion path. A futurenote_peer_seen(req.requester)is now a compile error.The legitimate Kademlia path (lookup/bucket-refresh inserting wire-discovered
NodeIds as probe candidates) keepsRoutingTable::insert(NodeId)— those are not asserted-live peers.CloserNodeswrapperPer the issue's "consider also",
closer_nodesfields are now aCloserNodesnewtype that enforces theMAX_CLOSER_NODEScap at construction (try_new) as well as at decode (itsDeserialize), replacing the olddeserialize_closer_nodeshook.Design notes
ContentHashand aNodeIdshare the 256-bit XOR keyspace (ADR 022).routinggainsxor_distance_bytes(&[u8;32], &[u8;32]), andclosest/closest_unboundedtake a raw keyspace point so theFindValue(hash) andFindNode(id) paths both fit — no fake-wrapping a hash as aNodeId.ContentHash(notHash) to avoid colliding with the existingdecdn_config_types::Hash.Deref<Target=[u8;32]>— it would re-expose panicking slice indexing under the workspaceindexing_slicinglint and dissolve the type boundary. Byte access is the explicitas_bytes()/from_bytes().ResolvedDht.static_active_nodesbullet was stale — no such field exists (the active-staker set is a runtimeStakerSettrait), 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 skippedNodeId([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