Repository navigation
Conversation
|
Important Review skippedDraft detected. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Free Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
Note 🎁 Summarized by CodeRabbit FreeYour organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login. Comment |
There was a problem hiding this comment.
Pull request overview
Updates the deCDN design documentation to switch per-MB metering to a PayWord-style hash-chain model (voucher opens an epoch; preimages pay per chunk) and to decouple off-chain lane persistence from the payment acceptance path (best-effort async persistence with lazy on-chain seeding as the floor). This is an ADR/documentation-only PR intended to specify a single pre-launch wire cut with no shims.
Changes:
- Specify hash-chain per-chunk payments: remove
VoucherAck, introducePreimage([u8; 32]), replacevoucher_interval_mbwith node-advertisedchunk_bytes, and revise rejection reasons and redeem signature. - Redefine off-chain lane state persistence as best-effort with a value-bounded flush policy and lazy per-lane seeding from on-chain
watermark. - Sweep downstream docs (architecture, glossary, client/AA rationale, observability appendix, related ADRs) to match the new payment and wire model.
Reviewed changes
Copilot reviewed 17 out of 17 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| README.md | Updates top-level project description and crate inventory to reference hash-chain payments. |
| CHANGELOG.md | Records the planned (design-only) wire-breaking shift to preimage payments and best-effort persistence. |
| adr/003-payments.md | Core payment model rewrite: epochs + preimages, bounded chain walk, best-effort persistence + chain floor seeding. |
| adr/005-protocol.md | Wire protocol updates: Preimage replaces VoucherAck, chunk_bytes replaces voucher_interval_mb, updated reject reasons and semantics. |
| adr/012-client.md | Updates client cadence and session-key justification to reflect epoch signatures vs per-interval signing. |
| adr/013-schema-evolution.md | Documents the pre-launch exception for removing/replacing a mid-enum variant (VoucherAck → Preimage) and field removals. |
| adr/014-on-chain-verification.md | Updates the StreamResponse field listing (chunk_bytes?). |
| adr/016-contract-interactions.md | Updates PaymentPool.redeem signature and adds lane watermark read usage for lazy seeding. |
| adr/024-account-abstraction.md | Reframes AA/session-key motivation around unattended signing and lane fan-out rather than per-MB signature volume. |
| adr/036-served-bytes-voting-weight.md | Updates rate-floor discussion to account for resolved-claim arithmetic under epochs + chain index. |
| adr/037-regional-proxy-warming.md | Updates payment pacing language from vouchers/acks to preimages/epochs and chunk cadence. |
| adr/038-bao-verified-range-streaming.md | Updates envelope/payment message names and framing language to chunk_bytes + Preimage. |
| adr/039-multi-source-parallel-fetch.md | Updates “self-enforcing delivery” description to preimage-based pacing. |
| adr/architecture.md | Updates architecture narrative to reflect preimage payments and epoch vouchers; updates reading-order payment chapter summary. |
| adr/glossary.md | Adds/updates payment glossary terms: voucher epoch, preimage, credit window (new semantics). |
| adr/appendix-observability.md | Adds planned metrics for preimages and lane persistence/seeding; adjusts existing voucher metric semantics. |
| adr/appendix-operator-key-rotation.md | Updates hot-signing rationale wording to match new payment signature cadence assumptions. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Addresses review on #1652. The flush-bound units comment surfaced a real inconsistency in ADR 003, not just in the metric description. `credit_window` is a byte quantity, but the persistence rule bounded "un-flushed accepted **value**" by it — comparing USDC against bytes — while the next sentence concluded the replay surface is "one credit window of re-delivered bytes", which only holds on the bytes reading. The bound is now stated in bytes, and `decdn_lane_flush_lag_bytes` matches its own `_bytes` suffix. Preimage verification cost is now stated precisely in both ADR 005 and the glossary: it costs as many hashes as the index advances (one in steady state), rather than an unconditional "one hash" that the first-of-epoch case contradicted. Glossary also calls the preimage a per-chunk instrument settling per-MB-priced delivery, rather than a "per-MB" one. README no longer claims shipped behaviour that does not exist: `VoucherAck` is still the wire (crates/protocol/src/client.rs:103) and no preimage-chain code exists. The crate line drops "+ preimage chains", and the payment prose is stated at a level true of both the current wire and the ADR, so it overstates nothing while still not contradicting ADR 003. Verified: make -C adr check-refs (1685 anchors resolve); `cargo nextest run -p decdn-node -E 'test(/metric/)'` — 39 passed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Coverage reportTotal: 80.88% (was 80.88%, ● 0.00%) — 60163/74382 lines No Rust files changed in this PR. History
|
Two stacked ADR decisions that keep per-MB metering while removing the machinery built to make a signed per-interval voucher fast. The fsync-before-VoucherAck rule in ADR 003 put a ~3.18 ms durable commit on the acknowledgement path. That forced the credit window to cover `RTT + commit_interval`, which forced group-commit batching, which forced voucher-interval negotiation and the concurrent-stream lane-arbitration rules. Both decisions dismantle that tower from the base. 1. Persistence is best-effort; the chain is the floor. Accept on verification and persist asynchronously, flushing on a value bound so the post-crash replay surface is at most one credit window — the credit a node already extends by serving. An unknown lane seeds its floor from `watermark[poolId][signer][provider]` with one eth_call; the lane floor is `max(local, chain)`. Seeding is lazy and per-lane, so a pool naming no provider never needs to be node-enumerable. A persist failure becomes a metric, not a wire rejection. 2. The voucher becomes a chain-epoch anchor; preimages meter the chunks. PayWord on each lane: one signed Voucher opens an epoch (default 1024 x 64 KiB) carrying chainRoot/chainLength/chunkBytes/chunkPrice, and each chunk is paid by a bare 32-byte Preimage — one keccak, no signature, no ack, no round trip, nothing to persist. `redeem` walks at most MAX_CHAIN_LENGTH (1024) hashes and the contract stores no chain state, so the pool, per-signer cap, sharded register, min(delta, remaining) and FeeRouter routing are untouched. The meter gets 64x finer rather than coarser, and the withholding bound tightens with it. Wire (pre-launch cut, no shim): VoucherAck removed and Preimage takes its slot; voucher_interval_mb replaced by node-advertised chunk_bytes; WatermarkBundle and the VoucherRejected bundle field removed, since a signer derives its own chain index; VoucherRejectReason drops StaleNonce/AmountRegression/BytesRegression/ RetryLater and adds BadChainParams/StaleEpoch/BadPreimage/ChainExhausted. ADR 003 Concurrent Streams rules 1 and 3 are deleted rather than deferred — they were specified but never implemented, and a lane-wide chunk size makes them unnecessary. Corrects two downstream claims the chain invalidates: ADR 024 and ADR 012 both motivated session keys with "a 100 MB download needs 100 signatures", which is now about two. The session-key case is rewritten to rest on unattended operation (nodes sign slash_sig per response; payer signatures scale with lanes and have nobody to confirm them), which the chain does not weaken. Stacked on #1650. Docs only — implementation follows as separate issues. Verified: make -C adr check-refs (1685 anchors resolve), check-book-list, adr-ref-hygiene + adr-book-list + trailing-whitespace + end-of-file-fixer pre-commit hooks, and `cargo nextest run -p decdn-node -E 'test(/metric/)'` (39 passed) for the appendix-observability registry check. markdownlint fails only on .github/workflows/issue-triage.md, identical before this branch. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Addresses review on #1652. The flush-bound units comment surfaced a real inconsistency in ADR 003, not just in the metric description. `credit_window` is a byte quantity, but the persistence rule bounded "un-flushed accepted **value**" by it — comparing USDC against bytes — while the next sentence concluded the replay surface is "one credit window of re-delivered bytes", which only holds on the bytes reading. The bound is now stated in bytes, and `decdn_lane_flush_lag_bytes` matches its own `_bytes` suffix. Preimage verification cost is now stated precisely in both ADR 005 and the glossary: it costs as many hashes as the index advances (one in steady state), rather than an unconditional "one hash" that the first-of-epoch case contradicted. Glossary also calls the preimage a per-chunk instrument settling per-MB-priced delivery, rather than a "per-MB" one. README no longer claims shipped behaviour that does not exist: `VoucherAck` is still the wire (crates/protocol/src/client.rs:103) and no preimage-chain code exists. The crate line drops "+ preimage chains", and the payment prose is stated at a level true of both the current wire and the ADR, so it overstates nothing while still not contradicting ADR 003. Verified: make -C adr check-refs (1685 anchors resolve); `cargo nextest run -p decdn-node -E 'test(/metric/)'` — 39 passed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The data-withholding attack vector still described the retired ack model ("the
last acknowledged voucher") and did not answer the question the chain epoch
raises: the node now holds a signed voucher before it delivers anything.
It grants no new claim. The voucher's `cumulative` is the epoch base — value
the lane already earned — and everything above it needs a preimage, which the
signer releases only for a received, hash-verified chunk. A node that delivers
nothing redeems at `chainIndex = 0` and claims exactly that base: zero on a
fresh lane (reverts `NothingToRedeem`), and on an established lane only what
the previous epoch's preimages already covered.
Payer exposure stays at zero despite signing first; node exposure stays at one
chunk.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The chain-root reuse attack vector only reasoned about the client trying to cheat nodes, concluded "not possible", and called reuse "equally useless to the attacker". That is right for that direction and wrong about the one that matters. A preimage carries no payee — it is a bearer token for its chain. So a signer that opens two lanes on the same `chainRoot` makes every preimage it releases to one node a valid claim on the other's lane. Node A hands preimage k to node B, and B redeems at index k having delivered a fraction of it. The signer pays for chunks it never received, bounded only by `chainLength × chunkPrice` per extra lane and ultimately by its own cap. No node can detect this: each sees only its own lane and cannot know another voucher shares its root. That is the zero-exposure property being given away, and the ADR described it as harmless. Adds the missing requirement — a signer MUST derive an independent chain per `(provider, epoch)` from a fresh seed, and chains for two lanes MUST NOT be derivable from each other — in both the Chunk Cadence section and the attack vector. Qualifies the "payer's exposure stays at zero" claim in Credit Window, which silently depended on it. Corrects the EIP-712 section, which credited the signed `provider` field with confining preimages; it confines the voucher, and only per-lane chain independence confines the preimages. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ures The ADR asserted the redemption chain walk costs "roughly 60k gas in the worst case" and framed that as negligible against a whole-epoch settlement. Both halves were wrong. Measured on this repo's Foundry setup (solc 0.8.28, optimizer, 200 runs), by instrumenting the existing PaymentChannel harness: redemption today, cold lane 277,517 redemption today, warm lane 113,618 walk of 1024, scratch-space assembly (~97/step) 99,390 walk of 1024, naive abi.encodePacked (~224/step) 239,580 walk of 256, assembly 24,886 So a full-depth walk adds ~99k gas to a ~114k warm redemption — an 87% increase in the worst case, not noise. The estimate was 1.7x low against an optimal implementation and 4x low against a naive one. Records the measured table, states the trade plainly (on-chain gas rises to buy a one-hash off-chain payment path, and holds only because redemption is rare and one call settles every prior epoch), and adds the implementation requirement the numbers imply: hash from scratch space in assembly, because round-tripping through abi.encodePacked costs 2.4x more for the same result. Adds the matching Negative consequence, which previously named only the audit surface and not the gas. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The claim that justified deleting the watermark self-heal — "a signer derives
its own chain index from the preimages it has released, so it always knows its
position" — silently assumed the signer still HAS its state. A client that
crashed and lost it knows nothing, and had no way to place itself on a lane or
choose a correct base for its next epoch. The rejection carried no data either,
so the node could not tell it.
Adds ADR 003 § Client Restart and Lane Resume:
- A signer SHOULD derive each epoch's chain seed as
KDF(signer_secret, pool_id, provider, epoch_nonce) rather than persist it, so
it keeps no per-lane secret and can regenerate any chain from its long-term
key. `provider` is in the derivation because chains must stay independent per
lane; `epoch_nonce` makes re-derivation reproduce the same chain and a new
epoch never reuse one.
- The node supplies the position the signer cannot derive, as a `LanePosition
{ epoch_nonce, chain_index, preimage }` on `StaleEpoch`.
- It authenticates itself with one hash: claiming index k requires exhibiting
preimage k, which the node can only hold if the signer released it and cannot
compute from a lower one. Understating is possible and self-harming.
This is strictly stronger than the bundle it replaces, which needed two
signature gates because a bare cumulative number carries no proof of itself.
The payload shrinks and the gates disappear.
Also records what was already true and unstated: a client that never comes back
owes nothing, having paid only for chunks it received, and abandons at worst an
unspent chain holding no money.
Wire: `VoucherRejected` goes from one field to two (`reason`, `position`).
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
0375b00 to
8abcc2b
Compare
The naive-walk row said 239,580 gas (~224/step). Re-measured on the stated setup (solc 0.8.28, optimizer on, 200 runs) it is 193,306 (~189/step), and `abi.encode` and `bytes.concat` measure the same, so the saving comes from staying in scratch space rather than from the spelling. The assembly rows reproduce within 1%, so the 87% worst-case increase over a warm redemption is unchanged; only the penalty for the naive form drops from 2.4x to ~1.95x. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Discussion note (not a blocker) — two economic floors under the finer meter that the ADR does not currently state, and that interact: 1. USDC-precision payability floor. USDC is 6-decimal, so the smallest non-zero payment is $0.000001. Against the ADR 009 price band the default 64 KiB chunk is sub-precision:
So 2. Settlement-gas floor — which this PR raises. Per the ADR’s own Consequences, a full-depth walk adds ~99k gas to a ~114k redemption (+87% worst case). That lifts the minimum cumulative delivery worth an on-chain redeem (rough, current spot):
Why they belong together. Both bound the same region — value that moves off-chain but is uneconomic to settle on-chain, i.e. the dust / free-ride surface a non-paying lane sits in. Floor (1) caps how fine the meter is actually allowed to go; the walk widens floor (2). Note the direction: making chunks payable pushes Discussion questions:
|
|
Follow-up — voucher schema slimming. Calldata is the dominant L2 redeem cost, so invariant fields re-posted on every redemption are pure waste (same bytes, over and over). Hoist invariant policy fields to constants — drop from the signed voucher:
Net of the two real cuts: ~2 signed fields removed ≈ ~20% less redeem calldata → proportionally smaller dust floor on calldata-dominated chains (Arbitrum). Negligible where calldata is already near-free (Optimism). |
|
Closing in favour of a narrower split — thanks for the deep work here, the reasoning is being carried forward, not dropped. PayWord lands on its own in ADR 003 (Payment Model) — where the payment model lives, not a new ADR — tracked in #1670. Both review notes on this PR are folded into that issue:
Decision 1 (best-effort / async voucher persistence, chain-as-floor) is not being silently dropped — it's flagged in #1670 as needing its own home (fold the Two related follow-ups spun out of the same discussion:
Reopen if you'd rather iterate here instead. |
Rebased onto
mainnow that #1650 has merged. ADR-only — no Rust or Solidity. Implementation follows as separate issues.Why
Per-MB metering is the product, so the goal was not to coarsen the meter but to make the per-interval claim free. The cost sits in one requirement in ADR 003 § Off-chain voucher state persistence: the node must durably commit the lane watermark before sending
VoucherAck. That is ~3.18 ms/voucher and caps a lane at ~313 MiB/s at the 1 MB wire cadence (measured in #1490). Everything above it exists to hide it:Two independent, stackable decisions dismantle it from the base.
Decision 1 — persistence is best-effort, the chain is the floor
Accept on verification and persist asynchronously, flushing on a value bound so the post-crash replay surface is at most one credit window — exactly the credit a node already extends, knowingly, every time it serves. An unknown lane seeds its floor from
watermark[poolId][signer][provider]with oneeth_call; the lane floor ismax(local, chain). A persist failure becomes a metric, not a wire rejection.Seeding is lazy and per-lane, which is what makes ADR 016's "a pool names no provider, so it is not node-enumerable" a non-issue rather than a blocker.
The win is decoupling, not fsync count: group commit already amortised the writes. What cost was that the commit sat on the acknowledgement path.
Decision 2 — the voucher becomes a chain-epoch anchor
PayWord (Rivest–Shamir, 1996) on each
(poolId, signer, provider)lane. One signedVoucheropens an epoch (default 1024 × 64 KiB) carryingchainRoot/chainLength/chunkBytes/chunkPrice. Each chunk is paid by a bare 32-bytePreimage.VoucherAck)The meter gets 64× finer, not coarser, while signatures drop 16×.
chunkBytesis a lane property advertised by the node, not a per-stream negotiation. That is what lets ADR 003 § Concurrent Streams rules 1 and 3 be deleted: they were specified but never implemented (no lane-wide minimum is computed anywhere, and the credit-window pause is per-stream).Measured cost, not estimated
Both halves were measured against this repo rather than guessed.
CPU per GiB, one lane (release build, real
decdn-incentivesigning path):Client 3.1× cheaper, node accept path 15.7× cheaper. The client's win is modest because the chain adds 16,384 hashes/GiB it never had — it trades signatures for hashing and comes out ahead, not for free.
Gas (Foundry, solc 0.8.28, optimizer 200 runs, measured on the existing
PaymentChannelharness):abi.encodePacked(~189/step)A full-depth walk adds ~99k gas to a ~114k warm redemption — an 87% increase in the worst case, not noise. So this design moves cost from off-chain to on-chain: the per-chunk path loses a signature, an ack and an fsync; redemption gets up to 87% more expensive. That holds because redemption is rare and one call settles every prior epoch.
MAX_CHAIN_LENGTHprices it, and the ADR carries a MUST to hash from scratch space in assembly — the naive form costs ~1.95× more for the same result.The naive row was re-measured after the rebase and corrected from 239,580 (~224/step) to 193,306 (~189/step);
abi.encodeandbytes.concatmeasure identically, so the saving comes from staying in scratch space rather than from the spelling. The assembly rows reproduce within 1%, so the 87% figure is unchanged.Two correctness rules added during review
Chains MUST be independent per lane. A preimage carries no payee — it is a bearer token for its chain. A signer that opens two lanes on one
chainRootlets either node spend the other's preimages, at the signer's expense, bounded only by its cap. No node can detect it, since each sees only its own lane. The ADR originally called this reuse "harmless"; it voids the zero-exposure property. Rivest and Shamir specify a chain per vendor in the 1996 paper — this was a regression against the source scheme, not a novel edge case.A client that lost its state can resume. The claim that justified deleting the watermark self-heal — "a signer derives its own chain index from the preimages it has released" — assumed the signer still has its state. A crashed client knows neither its epoch nor its index. ADR 003 § Client Restart and Lane Resume specifies deriving the chain seed as
KDF(signer_secret, pool_id, provider, epoch_base, chunk_bytes, chunk_price, chain_length)— no per-lane secret is persisted at all — plus a self-authenticating position exchange.Reconciled with #1650 during the rebase
#1650 landed three changes after this branch forked, so the chain design is layered on top of them rather than reverting them:
nonceand notoken. Both are gone from the field list, the EIP-712 typehash and digest, the wire format and the glossary. § Voucher ordering is rewritten: epochs are ordered by their cumulative base, and within an epoch by the self-proving chain index.WrongTokenis dropped fromVoucherRejectReason(nine mirrored variants, not ten).LanePositionno longer names the epoch by a counter. With no nonce, the node echoes back the signer's own signed voucher:LanePosition { voucher, chain_index, preimage }. Everything the seed derivation needs is inside it, and the "no signature gate" property is unaffected — a preimage still proves its own index. Keying the KDF on the epoch's signed terms also closes a hole a bare cumulative base would open: two epochs sharing a base but repriced would otherwise derive the same chain.Mis kept over this branch's older "redemption credit window", including in the chunk-risk table, the partial-redemption paragraph, the Negative consequences and the glossary.Wire changes (pre-launch cut, no shim)
ClientMessage::VoucherAckremoved;Preimage([u8; 32])takes its slot (discriminant 4, renumbering the tail)voucher_interval_mbremoved fromStreamRequest/StreamResponse; node-advertisedchunk_bytesreplaces itWatermarkBundlereplaced byLanePosition { voucher, chain_index, preimage }, carried onStaleEpoch. It needs no signature gates — the old bundle needed two, because a bare cumulative number carries no proof of itself, whereas claiming indexkrequires exhibiting preimagek, which a node can only hold if the signer released itVoucherRejectReason: dropsAmountRegression,BytesRegression,RetryLater; addsBadChainParams,StaleEpoch,BadPreimage,ChainExhaustedDownstream claims corrected
ADR 024 and ADR 012 both motivated session keys with "at the default 1 MB voucher cadence, a 100 MB download needs 100 EIP-712 signatures." Under the chain that is about two, so the premise no longer holds. Rewritten to rest on unattended operation instead: nodes still sign a
slash_sigper response, and payer signatures scale with lanes rather than bytes with nobody present to confirm them. The session-key case survives; the arithmetic behind it did not.Files
003(payment model, chunk cadence, credit window, client restart, redemption, persistence, attack vectors, EIP-712 type) ·005(wire) ·013(ClientMessageenum, frozen fields) ·016(redeem signature,watermarkread row) ·012014024036037038039appendix-observabilityappendix-operator-key-rotationarchitectureglossaryREADMECHANGELOG.New observability rows (
decdn_preimages_received_total,decdn_preimages_rejected_total,decdn_lane_seed_from_chain_total,decdn_lane_flush_lag_bytes) are all Statusplanned, since nothing emits them yet.README deliberately does not describe preimages:
VoucherAckis still the shipped wire and no preimage code exists, so its payment prose is phrased to be true of both the current implementation and the ADR.Verification
pre-commiton every commit: markdownlint,adr reference hygiene(links, anchors, section spacing) andadr book list in syncall passVoucherRejectReasonset in 005 matches the rejection table in 003 and the mirror obligation; nononce,token,WrongToken,WatermarkBundle,RetryLaterorepoch_noncereferences survive outsideadr/_history/main, soci.ymltriggersKnown gap (pre-existing, worth a follow-up)
ADR 003's detailed
redeembehavior block still spells the old signatureredeem(poolId, signer, provider, cumulative, bytesDelivered, voucherSig, capability), while the summary, the function table and ADR 016 useredeem(voucher, sig, chainIndex, preimage, cap). That block was never updated when the chain landed.Follow-up issues to file
collect_voucher_batch,BufferedVoucherReader,parse_frame, staged-candidate/swap,voucher_commit_interval_ms,RetryLater; add lazy chain-seeded lane hydrationPaymentPoolchain fields + walk verification (assembly, scratch space) + anchor typehash; regenerate.gas-snapshot(a gas change failssolidity build+testand is invisible to localforge test)crates/protocolmessage set,VARIANT_COUNT,public-apisnapshot regenLanePositionresume; collapseledger.rs'soutstanding/resolve_ack/resolve_rejectFIFO and thecommitted()-vs-settlement()hazard into one frontiersol!incrates/incentive/src/payment_channel.rsandcrates/e2e/src/bindings.rs; ABI drift here is caught only by theanvil e2ejob🤖 Generated with Claude Code