Repository navigation
feat(node): cdn/client/v1 paid-delivery handler + node-to-node requester (#317) [3/3] - #733
Conversation
There was a problem hiding this comment.
Code Review
This pull request implements the cdn/client/v1 paid-delivery protocol handler (ClientHandler) and its client-side requester (stream_fetch), along with configuration updates and loopback tests. The review feedback highlights several critical security and robustness issues: stream_fetch incorrectly assumes a zero-state channel which breaks on reused channels; a lack of verification on bound_addr allows unauthenticated clients to leech data; performing expensive cryptographic signatures on overloaded streams introduces a DoS risk; a potential OOM vulnerability exists if a server sends infinite chunk data; and the voucher withholding mechanism can cause client timeouts. Additionally, the range check for voucher_interval_mb should use a minimum of 1 instead of the default constant.
There was a problem hiding this comment.
Pull request overview
Adds the cdn/client/v1 paid-delivery server (ClientHandler) and a node-to-node stream_fetch requester, wires the handler into the runtime with EIP-712 domains derived from payment_channel_address / staking_registry_addr, introduces the payment.voucher_interval_mb config field (1..=1024), and ships five loopback integration tests covering happy-path, byte-offset resume, #252 zero-rate, unknown-channel rejection, and not-found refusal.
Changes:
- New
handlers/client.rsALPNcdn/client/v1handler: per-connection stream cap, hydrated channel store, signedStreamResponse+ chunk/voucher/ack lifecycle, clean voucher-rejection close, 0-RTT refused per ADR 015. - New
client_requester.rs::stream_fetchperforming the receive-side validation (#252zero-rate,slash_sigrecovery, echo checks) and cumulative voucher payment. payment.voucher_interval_mbplumbed throughPaymentConfig/ResolvedPayment/ runtime, with handler registered on the iroh router andTODO(#317)removed.
Reviewed changes
Copilot reviewed 13 out of 13 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| crates/node/src/handlers/client.rs | New ClientHandler implementing the paid-delivery server lifecycle. |
| crates/node/src/client_requester.rs | New reusable node-to-node stream_fetch requester. |
| crates/node/src/runtime/mod.rs | Constructs/registers ClientHandler; removes TODO(#317). |
| crates/node/src/handlers/mod.rs | Exports the new client handler module. |
| crates/node/src/lib.rs | Exposes client_requester as a public module. |
| crates/node/src/runtime/reload.rs | Threads voucher_interval_mb through reload-state fixtures. |
| crates/node/tests/client_loopback.rs | Five loopback integration tests for the new handler/requester. |
| crates/node/tests/sighup_signal.rs | Updates the resolved-config fixture for the new field. |
| crates/common/src/config/types.rs | Adds voucher_interval_mb to PaymentConfig. |
| crates/common/src/config/resolved.rs | Adds voucher_interval_mb to ResolvedPayment. |
| crates/common/src/config/mod.rs | Resolver default + range validation; new unit tests. |
| crates/cli/src/commands/probe.rs | Adds a validate_rejects_zero_rate_response test and clarifies the comment. |
| crates/cli/tests/config_validate.rs | Updates the resolved-config fixture for the new field. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Introduce `crates/protocol/src/client.rs` with the `ClientMessage` enum and
all `cdn/client/v1` payload types per ADR 005 §`cdn/client/v1` and ADR 014 §1:
- `StreamRequest` (frozen base fields only) plus `StreamRequestExt` for
voucher-interval negotiation and the ephemeral client NodeId↔Ethereum
binding. The ext is carried as separate trailing bytes via the ADR 005
two-phase deserialization pattern (`encode_stream_request` /
`parse_stream_request_ext`) — keeping the base frozen so a future ext field
stays Tier-1 backward-compatible (old senders emit fewer trailing bytes; new
optional fields are appended and old receivers skip them).
- `StreamResponse` (signed `StreamResponseBody` + unsigned `error` /
`voucher_interval_mb` + 65-byte `slash_sig`)
- `ChunkData`, `Voucher` (wire `{signature, amount, nonce}` with u256 fields as
big-endian bytes — the leaf crate has no `U256`), `VoucherAck`, `StreamEnd`
- `StreamError` / `VoucherRejectReason` (frozen variant order, mirroring
`decdn_incentive::ChannelError` ∪ `VoucherError`)
`StreamResponse::validate()` and `ProbeResponse::validate()` both reject
`rate_per_mb == 0` on receive (#252) via a shared `MessageValidationError::
RateIsZero`; the rate-decode hook is shared (`pub(crate)`). Validation error
text is response-type-neutral so it reads correctly for both probe and stream
responses. Adds constants (`CHUNK_SIZE`, `MB_BYTES`, voucher-interval bounds,
`VOUCHER_SIG_LEN`) and a full test suite: per-variant discriminant pins,
roundtrips, fixed-byte wire-stability, two-phase ext (incl. forward-compat),
validation, and a full framing-stack roundtrip.
Leaf crate only — no behavior. Handler (node) and voucher logic (incentive)
follow in stacked PRs.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
de4a504 to
5454a3a
Compare
fb7dbb6 to
352d56a
Compare
|
Addressed the automated review across the stack (all three PRs force-pushed after a clean rebase; workspace builds, Fixed
Pushed back (verified false positive): the |
… seam Address PR review findings on the cdn/client/v1 wire types: several real invariants lived only in doc comments. Convert them into enforced checks on MessageValidationError-returning validate() methods. - Enforce voucher_interval_mb ∈ 1..=MAX_VOUCHER_INTERVAL_MB on both StreamResponse and the new StreamRequestExt::validate, closing the unbounded unvouchered-byte window (and interval * MB_BYTES u64 overflow). - Add StreamResponse ok/error consistency rules (ok=true ⇒ no error; ok=false ⇒ exactly one delivery-side error; never mid-stream-only VoucherRejected) via StreamErrorWithOk / MissingStreamError / VoucherRejectedInResponse. - Group StreamRequestExt.ethereum_address + binding_signature into Option<ClientBinding> so a half-populated binding is unrepresentable, add BINDING_SIG_LEN + ClientBinding::validate length check. - Add ClientMessage::validate dispatcher as the single decode-then-validate seam, and StreamError::is_delivery_side/is_mid_stream to express the error-domain split in code. - Fix docs: drop the non-existent decdn_incentive::StreamSlashData references (3 sites) for an analogous-to-ProbeSlashData forward note; relabel MAX_VOUCHER_INTERVAL_MB as the hardcoded ceiling, not governable. - Tests (+18): malformed ext remainder rejection, interval bounds, decode roundtrip in variant-order loops, empty ChunkData, non-zero byte_offset, ok/error consistency, ClientBinding, dispatcher, domain-split accessors. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…idge (#317) Adds the off-chain crypto/conversion layer the `cdn/client/v1` handler and requester need (#317), all mirroring the existing `probe_sig`/`voucher` patterns: - `stream_sig.rs` — `StreamSlashData`, the EIP-712 signed view of a `StreamResponse` (`{hash, ok, ratePerMb, totalBytes, channelId, timestampUs, redirect}`) over the shared `SlashJudge` domain (ADR 014 §1). Includes a `from_response_body` helper (`redirect: Option<NodeId>` → `bytes32(0)`/bytes) and an independent EIP-712 digest reconstruction test, plus type-hash and per-field tamper guards. - `bind_sig.rs` — `verify_binding` for the ephemeral client `BindNodeId(nodeId, nonce=0)` binding (ADR 003 §Off-Chain Ephemeral Binding), EOA `ecrecover` against the `CapacityBond` domain. ERC-1271 (ADR 024) deferred. - `client_bridge.rs` — `wire_voucher_to_signed` / `signed_to_wire_voucher` (reconstructing `channel_id`/`token`/`bytes_delivered` from stream context, u256 as big-endian bytes) and `voucher_reject_reason`, an exhaustive `ChannelError` → `VoucherRejectReason` map (no wildcard, so a new variant fails to compile) with `Store(_)` → `RetrySignal` (transient, never a wire rejection — #527). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
5454a3a to
0e243d3
Compare
…ter (#317) Wire the revenue path end to end on top of the protocol types (PR1) and the incentive sig/bridge layer (PR2). Server (`handlers/client.rs`): - `ClientHandler` (`ProtocolHandler` for `cdn/client/v1`): per-connection stream cap (`Semaphore`, default 100), concurrent streams driven on one task via `FuturesUnordered` (the trait borrows `&self`), connection-scoped verified `BindNodeId` cache, and a per-channel `tokio::Mutex` map hydrated from the persisted `ChannelStateStore` (#527 replay guard). - A verified client binding must match the channel's authorized client before any bytes are delivered (the binding is now enforced, not just recorded); unbound peers fall back to the voucher-signature gate. - Stream lifecycle: signed `StreamResponse` -> `ChunkData` in the negotiated `voucher_interval_mb` batches (the client's interval proposal is honored) -> cumulative voucher per boundary (rate-checked via `verify_rate`, applied via `apply_voucher` on `spawn_blocking` so the redb fsync never blocks a runtime worker) -> `StreamEnd`. Voucher rejections are sent as `StreamError` and the stream closed cleanly; underpayment / transient store failure fail the stream rather than deadlocking the client on a never-arriving `VoucherAck`. The stream-cap-exhausted path resets cheaply (no per-reject ECDSA signature). Always rejects 0-RTT (ADR 015). Unknown channel => `VoucherRejected{WrongChannel}`. - Two-phase `StreamRequestExt` parsing (ADR 005) via the protocol helpers. Requester (`client_requester.rs`): - `stream_fetch` performs a full node-to-node pull: validates the response (slash_sig + #252 zero-rate reject), verifies `slash_sig` against the delivering node's address, pays cumulative vouchers (each voucher's delta covers its own bytes; resumes a reused channel from `ChannelContext.prior_*`), caps received bytes at the promised total (OOM guard) and per-chunk size, and whole-blob BLAKE3-verifies on a full fetch. Wiring + config: - Runtime constructs and registers `ClientHandler` (voucher domain <- StablePaymentChannel, binding domain <- CapacityBond); removes the TODO(#317). - New `payment.voucher_interval_mb` (default 1, range 1..=1024). - `probe.rs` documents the #252 zero-rate receive check now enforced by `ProbeResponse::validate()`. Tests: 6 loopback integration tests (two-voucher roundtrip with channel-state advance, reused-channel resume, byte-offset resume, #252 zero-rate, unknown-channel rejection, not-found refusal) plus config validation. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
352d56a to
b1e7019
Compare
alpergundogdu
left a comment
There was a problem hiding this comment.
Review — ADR consistency (PR 733, reviewed together with #732)
Reviewed the handler + requester against the wire types in #732 and the ADRs. The end-to-end revenue path is well-built and matches the ADRs on the things that matter most. Verified as consistent:
- 0-RTT:
on_acceptingalways takes the full handshake and the requester never callsinto_0rtt()— exactly ADR 015 §0-RTT Eligibility (cdn/client/v1= No). - Clean voucher rejection:
write_rejectsends an in-bandStreamError { VoucherRejected }thenfinish()s with no QUIC reset / no app-error code — matches ADR 005 §VoucherRejected semantics ("closed cleanly … no QUIC stream reset and no application-error close code"). - App error codes:
frame_err_code(TooLarge→0x02,Io→0x00,Varint|Decode→0x03) and the wrong-message-type0x01map exactly to ADR 013 §Application Error Codes. - #527 replay guard: per-channel state is hydrated from the persisted store at construction,
apply_voucheris committed to in-memory state only onOk, and the per-channel mutex is held across the await — persist-before-ack is correct (ADR 003 §Off-chain voucher state persistence). - Unknown channel →
WrongChannelwith the #327 boundary documented;BlobTooLarge/EvictedSinceProbe/NotFoundride in the signedok:falseresponse per ADR 005 §Error handling.
Finding 1 (notable) — transient persist failure isn't surfaced as an in-band wire rejection (ADR 003 §332)
collect_voucher, on the RetrySignal (transient ChannelError::Store) branch, does:
// Transient store failure (#527, `RetrySignal`): no wire retry signal exists, so fail the stream …
anyhow::bail!("channel store write failed: {e}")That bail! propagates up through deliver → serve_stream → serve → accept into an AcceptError, tearing the stream/connection down with no in-band reason. ADR 003 §Off-chain voucher state persistence says:
A failed persist write MUST surface as a voucher-acceptance failure — the node returns a transient-failure rejection through the [Off-chain Voucher Rejections (Wire Encoding)] channel, and MUST NOT send
VoucherAck. The specific wire code … is left to thecdn/client/v1handler implementation; the existingStaleNonce/InsufficientDepositcodes are NOT appropriate substitutes …
and ADR 003 §Off-chain Voucher Rejections stresses the in-band form precisely so the client gets a diagnosable reason "without burning ADR 013 application-error-code numbers" and "rather than an opaque connection drop."
So: the "MUST NOT VoucherAck" half is satisfied, but the "surface as an in-band wire rejection" half is not — the implementation produces exactly the opaque transport teardown the ADR says to avoid. (And #732 deliberately provides no transient VoucherRejectReason to express it.) The code comment's rationale — "the client is blocked awaiting VoucherAck and cannot resend mid-stream" — is partly valid, but the ADR's intent is that the client receive a clean retry-the-same-voucher signal on a new stream, distinguishable from a network error.
Reconcile one of two ways: (a) add a transient/RetryLater wire code (a VoucherRejectReason variant in #732, sent via write_reject before failing the stream), or (b) update ADR 003 §332 / §Off-chain Voucher Rejections to state that transient store failures fail the stream with no in-band code. Either is fine, but right now code and ADR 003 disagree.
Finding 2 (minor) — StreamResponse rate clamp is silent (ADR 005 §Rate bounds)
serve_stream/respond_error apply .clamp(self.delivery_floor, self.delivery_ceiling) before signing. ADR 005 §Rate bounds says the node "MUST verify bounds compliance before signing [a StreamResponse], with the same clamp-and-warn behavior," and SHOULD increment rate_bounds_clamp_events. The clamp is here, but the warn log and the metric are absent, so a misconfigured rate is silently corrected (the probe path is the reference for the clamp-and-warn behavior). Borderline missing-feature, but the ADR frames the warn as part of the required behavior.
Finding 3 (very minor — please confirm) — bind-domain verifyingContract
Runtime wires bind_domain = bind_node_id_domain(chain_id, staking_registry_addr) while the domain name is hardcoded "CapacityBond". There's no separate capacity_bond_address in the config (only staking_registry_address), so this is correct only if blockchain.staking_registry_address is the CapacityBond deployment (per ADR 003 the NodeId↔address registry lives in CapacityBond). Given the contract inventory that's almost certainly the same contract under a legacy field name — just worth confirming, since a mismatch would make every client-signed ephemeral BindNodeId fail ecrecover against the wrong verifyingContract.
Findings 2 and 3 are nits; Finding 1 is the one I'd want resolved (in tandem with #732) before this closes #317, since it's a direct MUST-level divergence from ADR 003.
Generated by Claude Code
…esponses (#317) Two delivery-path fallbacks in the cdn/client/v1 handler swallowed a CacheError::Store and produced a signed response that misrepresented state: - has().unwrap_or(false) turned a transient store fault into a signed NotFound, which a paying client treats as authoritative. - inspect().ok()...unwrap_or(0) collapsed an inspect error or a None size into total_bytes=0; for a non-empty blob the node then signed total_bytes:0, streamed the real bytes, and the receiver (expecting 0) aborted on the first chunk. Both now log at warn and return StreamError::InternalError. Only a genuinely complete, zero-length blob yields total_bytes==0. Tests: add 5 loopback cases closing the highest-value coverage gaps — the client-binding authorization subsystem (mismatch reset + binding does-not-own-channel NotFound, driven by a small raw_request client since the honest requester never sends a binding), the BlobTooLarge and EvictedSinceProbe delivery gates, and per-channel voucher serialization under concurrency (exactly one voucher accepted, no double-spend). Remaining hostile-client gaps documented in the test module header. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…with code (#317) ADR-vs-code reconciliations from Alper's #732 review; the code is canonical, the prose was stale. - ADR 005 §Voucher wire format listed the typed data as the 4-field {channelId, amount, nonce, token}, omitting bytesDelivered. Corrected to the 5-field VOUCHER_TYPEHASH (ADR 003 §598) and noted bytesDelivered as a third stream-context-derived field (node's per-channel counter). - ADR 003 §904 had the inverse error — it claimed bytesDelivered is transmitted on the wire. The protocol Voucher struct carries only {signature, amount, nonce}; corrected to mark bytesDelivered derived. - ADR 005 §Mirror obligation: return type updated to Result<VoucherRejectReason, RetrySignal>, excluded the transient ChannelError::Store variant, and flagged the handler-side wire surfacing of transient store failures as an open reconciliation with ADR 003 §Off-chain voucher state persistence (deferred to #733). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Coverage reportTotal: 89.49% (was 89.83%, ▼ 0.34%) — 23783/26577 lines
History
|
… on rate clamp (#317) Addresses Alper's ADR-consistency review on PR #733. Finding 1 (ADR 003 §332): a transient persist-write failure (ChannelError::Store / RetrySignal) in collect_voucher previously bailed, tearing down the stream with no in-band reason — the opaque teardown ADR 003 says to avoid. It now sends a new RetryLater wire reason in-band and finishes the stream cleanly, so the client resends the same voucher on a fresh stream. RetryLater is the 9th VoucherRejectReason, appended to preserve the frozen wire order; it has no ChannelError counterpart (the handler emits it from the RetrySignal arm, not the mirror conversion). Resolves the §144 (eight reasons) vs §332 (transient code required) conflict by documenting RetryLater as the off-chain-only exception in both ADR 003 and ADR 005. Finding 2 (ADR 005 §Rate bounds): the two StreamResponse signing sites clamped rate_per_mb silently. Added clamped_rate() mirroring the probe handler — clamp + warn + rate_bounds_clamp_events metric. Finding 3: confirmed correct, no change — staking_registry_address is the CapacityBond deployment (no StakingRegistry.sol exists), so the bind_domain wiring and "CapacityBond" domain name are consistent. Adds a client_transient_store_failure_is_retry_later loopback test. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
@alpergundogdu — addressed in de89664. Finding 1 (ADR 003 §332) — fixed. You're right that the On the §144-vs-§332 conflict you flagged: One boundary: the node-to-node Finding 2 (ADR 005 §Rate bounds) — fixed. Both Finding 3 — confirmed, no change. Correct that it's the same contract under a legacy field name. There is no
|
# Conflicts: # adr/005-protocol.md # crates/incentive/src/client_bridge.rs # crates/protocol/src/client.rs
Stacked PR 3 of 3 for #317 — base
feat/317-incentive-vouchers(#732). Review/merge after [1/3] #731 and [2/3] #732. This is the PR that closes #317.What
Wires the revenue path end to end on top of the protocol types (#731) and the incentive sig/bridge layer (#732).
Server (
handlers/client.rs) —ClientHandler(ProtocolHandlerforcdn/client/v1):Semaphore, default 100); concurrent streams driven on one task viaFuturesUnordered(the trait borrows&self); connection-scoped verifiedBindNodeIdcache; per-channeltokio::Mutexmap hydrated from the persistedChannelStateStore(incentive: no replay-protection window enforced on incoming voucher nonces, allowing a client to resubmit a previously accepted voucher after a node restart and receive a second byte-delivery for the same payment #527 replay guard).StreamResponse→ChunkDatainvoucher_interval_mbbatches → cumulative voucher per boundary (rate-checked viaverify_rate, applied viaapply_voucher) →StreamEnd. Delivery faults ride inok:false; voucher rejections are sent asStreamErrorand the stream is closed cleanly (no QUIC reset). Always rejects 0-RTT (ADR 015).Requester (
client_requester.rs) —stream_fetchperforms a full node-to-node pull: validates the response (slash_sig + #252 zero-rate reject), verifiesslash_sigagainst the delivering node's address, pays cumulative vouchers, and whole-blob BLAKE3-verifies on a full fetch.Wiring + config — runtime constructs/registers
ClientHandler(voucher domain ← StablePaymentChannel, binding domain ← CapacityBond), removes theTODO(#317); newpayment.voucher_interval_mb(default 1, range 1..=1024);probe.rsdocuments the #252 receive check.Scope boundaries (documented in code)
VoucherRejected { WrongChannel }— the handler serves only already-persisted channels until on-chain channel-open (Implement on-chain CapacityBond and PaymentChannel contract integration #327).ecrecoveronly.Tests
5 loopback integration tests: 1.5 MiB two-voucher roundtrip with channel-state advance, byte-offset resume, #252 zero-rate, unknown-channel rejection, not-found refusal. Full gate: workspace builds,
clippy --all-targets -D warningsclean, 979 tests pass.Closes #317.
🤖 Generated with Claude Code