Repository navigation
feat(payments): implement PayWord hash-chained per-MB meter (protocol + incentive + contracts) - #1770
Conversation
There was a problem hiding this comment.
Pull request overview
This PR implements the "PayWord" hash-chained per-MB payment meter from ADR 003 (#1751), replacing per-interval signed vouchers with a keccak hash chain. The payer commits chain_root = keccak^255(seed) in a signed voucher and releases one preimage per delivered chunk, so a metering tick costs one keccak instead of one signature. It also halves the metering granularity by making CHUNK_BYTES == BYTES_PER_MB (1 MiB), so a chunk prices exactly to the advertised per-MB rate. The change is a single coordinated wire + EIP-712 + Solidity ABI cut, consistent with the pre-launch "no compatibility shims" convention.
Changes:
- protocol: adds
ChunkPreimage(discriminant 4, 33 flat bytes),chain_root/chunk_priceonVoucher/WatermarkBundle,CHUNK_BYTES/MAX_CHAIN_LENGTH(retiringVOUCHER_INTERVAL_BYTES), and four newVoucherRejectReasonvariants. - incentive/contracts: new
chainmodule (keccak ladder + per-lane seed derivation) andLaneVoucher.chainRoot/preimage/packedchainMeter, with_resolveClaimwalking the preimage to the root; new revertsBadPreimage,ChainMeterReservedNonZero,ClaimOverflow. - node/client-pull: seller places a preimage reveal against the receiving stream's anchor; buyer keeps signed anchor and chain accrual separate and rolls to a fresh root when folding accrual.
Reviewed changes
Copilot reviewed 62 out of 62 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/protocol/src/client.rs | Defines CHUNK_BYTES/MAX_CHAIN_LENGTH, ChunkPreimage, chain fields on Voucher/WatermarkBundle, new reject reasons |
| crates/protocol/src/lib.rs | Re-exports updated for the renamed/added protocol constants and types |
| crates/protocol/tests/snapshots/public_api__public_api.snap | Public-API snapshot regenerated for the new surface |
| crates/node/src/handlers/client/dispatch.rs | Ramp-floor reservation reworded to CHUNK_BYTES; comment still says "4 MiB" (should be 1 MiB) |
| crates/e2e/tests/cli_bundle_pull_pool_id.rs | Interval rename applied, but blob sizes (3/2 MiB) now violate the < CHUNK_BYTES (1 MiB) assertion |
| crates/e2e/tests/cli_fetch_topup.rs | Interval identifier swapped, but "4 MiB"/"8 USDC floor" narrative comments are now stale |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Replaces the 4 MiB signed-voucher meter with the PayWord hash chain from
ADR 003. The payer commits `chain_root = keccak^255(seed)` inside a signed
voucher, then releases `keccak^(255-k)(seed)` after each delivered chunk. A
tick costs one keccak — no signature, no acknowledgement, nothing durable to
write before the node sends the next chunk. Signatures drop to O(1) per
transfer plus one per 255-chunk rollover, and the meter gets four times finer
(1 MiB instead of 4 MiB) because `CHUNK_BYTES == BYTES_PER_MB` makes a chunk
price exactly the advertised per-MB rate.
Redemption resolves both axes with one formula, with no branch for the sealed
case: `claimed = amount + chain_index * chunk_price`.
One straight wire/ABI cut — no shims, no dual readers, no version negotiation.
protocol
- `CHUNK_BYTES` / `MAX_CHAIN_LENGTH` replace `VOUCHER_INTERVAL_BYTES`
- `ChunkPreimage { preimage, index }` at `ClientMessage` discriminant 4,
renumbering the tail; 33 flat bytes, pinned by a golden-bytes test
- `Voucher` gains `chain_root` + `chunk_price`; `WatermarkBundle` gains the
chain half so a re-seeding signer folds the frontier back in
- four handler-emitted reject reasons: `BadPreimage`, `ChainIndexTooLarge`,
`UnanchoredPreimage`, `ChunkPriceMismatch`
incentive
- new `chain` module: the keccak ladder, plus per-lane seed derivation
domain-separated on `(pool_id, signer, provider, epoch)` under a master
secret derived deterministically from the signing key — so no two chains a
payer opens are inter-derivable, and nothing secret is written to disk
- EIP-712 `Voucher` and its `sol!` mirror gain both signed fields
- `LaneState` holds a live epoch and, over an under-folding rollover, the
retired-but-stronger claim; `advance_preimage` implements deepest-wins
- lane + buyer rows persist the chain frontier and the epoch counter
contracts
- `VOUCHER_TYPEHASH` gains `chainRoot` + `chunkPrice`
- `LaneVoucher` gains `chainRoot`, `preimage`, and a packed `chainMeter`
word (`chunkPrice << 8 | chainIndex`), keeping the struct static at 8 words
- `_resolveClaim` walks the preimage to `chainRoot` and extends the anchor;
the soft rate floor now clamps the CHAIN-EXTENDED pair
- new reverts `BadPreimage`, `ChainMeterReservedNonZero`, `ClaimOverflow`
node + client-pull
- the seller reads either proof through one reader, places a reveal against
the receiving stream's own anchor, and credits it exactly as a voucher
- the buyer's ledger keeps the signed anchor and the chain accrual apart: a
voucher that folds accrual always rolls to a fresh root, or the node would
count the same chunks twice
- credit-window floor becomes one chunk; #1669's ramp is untouched
- the redeem planner submits the lane's strongest claim, so a lane sitting on
unredeemed reveals is no longer invisible to the redemption floor
Deviations from the issue checklist, reconciled against the ADR (which landed
six hours after the issue was filed):
- no `ChainRootReuse` reject reason — ADR 003 §One chain per lane states that
root reuse pays the node, so no node-side rule protects anyone; the payer's
seed derivation is the whole defence. `ChunkPriceMismatch` takes its place.
- `LaneVoucher` uses the packed `chainMeter` word (256 bytes), not four
separate fields (288)
- no on-chain `chainIndex` bound: a `uint8` extraction caps it by
construction. ADR 003 lines 317/574 are updated to name the reserved-span
revert `ChainMeterReservedNonZero` instead.
Out of scope, filed as #1769: `serve_leg` hoists its credit window once and
never re-ramps, unlike its cache-hit twin.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… replaced Follow-up to the PayWord cut: the constant is gone, so the prose that named it should go too. A comment that still says "one voucher interval (4 MiB)" beside a one-chunk floor is worse than no comment — it reads as a live invariant. Also loosens the zero-credit proof bound from 4 to 8. Three messages is the worst case a well-behaved payer sends before a reveal (re-anchor, roll, reveal), but a duplicate or out-of-order reveal is ordinary once several streams share one lane and credits nothing either, so 4 sat right on the boundary. Every read inside the bound still carries its own timeout, so this is about slack, not about capping any single wait. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… sizes `cli_bundle_pull_pool_id` asserts each entry's wire length stays under one `CHUNK_BYTES` while their aggregate crosses it — that straddle is the whole premise, since it is what makes the shared lane watermark cross a boundary only across the two entries. The blobs were sized 3 MiB / 2 MiB for a 4 MiB quantum, so against a 1 MiB one the first assertion aborts the journey before it starts. The test is `anvil-e2e`-gated, so it compiled clean and the workspace run never executed it. At 768 KiB / 512 KiB the wire lengths are 789,440 and 526,272 against a 1,048,576-byte chunk, summing to 1,315,712 — both bounds hold with margin. The rest is prose that still described a 4 MiB quantum: the pre-serve floor arithmetic in both `cli_fetch_topup` sizing blocks, the floor-bound blob's lower bound, the `dispatch.rs` cold-request guard, two wall-clock re-check comments, and several `client_loopback` setup notes. None of it was load-bearing — those tests compute cost from real wire bytes or from absolute deposits — but a comment that states an invariant the code no longer holds is worse than none. `INGEST_CHECKPOINT_BYTES` keeps its 4 MiB cadence and gains an honest doc. It is a fsync-amortization knob whose old text claimed alignment to the payment quantum; a fault can re-pay up to four chunks, and narrowing that would cost 4× the fsync rate for a storage tradeoff, not a payment-correctness one. Also drops changelog voice from the comments this branch added, per the present-tense canon rule: gas pins state what the figure covers rather than what it was, and the buyer row's golden explains why its epoch is non-zero rather than narrating the field's arrival. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…c gate The buy-side gate and the `PayWord` meter both land in the candidate-setup block: the gate replaces the static rate ceiling with the economic one, while deriving a lane's chain master is a signing operation and so makes `lane_ledger` fallible. Both belong — the ceiling comes from the gate, the ledger through a fault path. Three identical `classify_pull_failure` arms collapse into one `local_miss` closure. The duplication predates this branch, but adding a fourth is what pushed the function past the line limit, and every one of those faults is the same statement: it is ours, not the candidate's, so it folds into the walk as a miss without scoring the peer. The new `node_origin_pull` fixtures carry the lane chain and the buyer's epoch counter, and `.gas-snapshot` is regenerated over the vote-weight-cap entries. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
3649eb4 to
cac76fe
Compare
Contracts coverageLine coverage: 89.69% (2575/2871 lines) |
Gas snapshotNo gas changes vs base. |
Coverage reportTotal: 81.58% (was 81.32%, ▲ +0.26%) — 62828/77018 lines
History
|
…nnot wedge The pull leg paces in CONTENT bytes against the frontier the serve leg publishes, which `content_paid_frontier` derives from PAID WIRE by flooring to a chunk-group boundary; `WindowPacer` then floors its own room to whole groups. Two group-sized roundings therefore sit between what a client has paid for and what the pull may fetch next, while the client releases its next preimage only once a whole `CHUNK_BYTES` of WIRE has arrived. At a one-chunk window those roundings cost more than the wire's interleaved proof bytes hand back, so the pull parks with the client a few KiB short of the chunk it must complete to pay — and that payment is the only thing that would widen the window. `PULL_WINDOW_FLOOR` carries both roundings on top of the chunk, which closes the gap at every window size because the ramp only widens from there. The floor applies to the pacer alone. The pre-flight reservation and the serve loop both meter in wire on both sides and need no such allowance, so they keep metering against one chunk. Three fixtures priced against the old floor move with it: the window-pause span boundary now follows the real window rather than a chunk, and the floor-credit journey measures a withheld lane against the floor itself and derives its deposit slack from the floor instead of a constant tuned to a 4 MiB one. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A lane no longer settles in one redemption. The chain meter advances a chunk at a time and the closing sealed voucher folds the sub-chunk tail, so the first claim to reach the chain carries only a prefix of the blob — under the old 4 MiB quantum a 2 MiB blob produced exactly one voucher, and reading the watermark after any advance was the same as reading it after the last. The rate-bounds journey prices the WHOLE sale, so it now polls the settled watermark until it covers the blob rather than reading whatever the first redemption left behind. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… the chain's The second delivery on the settlement journey's lane continued from the on-chain watermark, read by polling until any redeem landed. That was the same thing as the full first delivery when a 1.5 MiB blob produced one voucher; under the chunk meter it is a prefix, because the chain advances a chunk at a time and the closing sealed voucher folds the tail. Resuming from a prefix opens the next chain behind the lane's own watermark, which the node refuses to anchor — so the reveals that follow fold nothing and the serve leg cuts the stream. A real buyer never resumes from the chain; it resumes from its own ledger, which is what `LaneState::owed` mirrors here. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alpergundogdu
left a comment
There was a problem hiding this comment.
Reviewed the full diff, tracing each finding through the PR head (a385276) — contract _resolveClaim/_verifyVoucher, incentive::chain/lane state, the node's credit path, and the buyer ledger. The contract-side chain resolution, lane rollover/deepest-wins folding, wire format, and settlement planner all check out.
The five inline findings are concentrated on the buyer side of the new meter, ranked by severity:
- Watermark-bundle reseed drops the chain half → a client resuming against a mid-chain node frontier wedges the lane permanently (
client-pull/src/lib.rs). - Shared-lane re-anchor: Keep→Roll escalation plus a stale
anchored_epochread collapse the hash-chain fast path to a signature + fresh keccak ladder per chunk, and strand a sibling stream's in-flight reveals (client-pull/src/lib.rs). stream_fetch_tracked_with_progressnever surfaces the epoch counter → seed reuse on retry after an unclean death, stalling the transfer (client-pull/src/lib.rs).- Preimage-path audit receipt logs raw
delta_bytesinstead of the cappedcredited_bytesthe voucher path was switched to (node/src/handlers/client/voucher.rs). - Duplicated
.with_chain_epoch(prior_epoch)call (cli/src/commands/fetch.rs).
1–3 are recovery/concurrency paths the happy-path suites don't exercise; I'd treat them as blocking.
Generated by Claude Code
Design: drop the epoch machinery — derive the seed from the anchor insteadProposal (from review discussion): replace the persisted per-lane epoch counter with where Why this is strictly stronger than the counter
Why
|
Review of the PayWord meter found four defects on the payer's side of the new chain, all on recovery paths the happy-path suites never walk. A fifth, found while confirming them, is on the node's. **A resume dropped the chain half of the watermark.** A node that rejects mid-chain reports its signed anchor AND the frontier its chain has proved, and the payer's side of the bargain is to fold `verified_index x chunk_price` back in (ADR 005 §Watermark bundle) — which no client code did. Re-seeding from the anchor alone opened a fresh root beside a frontier the node was still metering: the node keeps the old chain, because one with reveals under it is worth more than the anchor a lagging voucher offers for it, so every reveal that followed folded nothing and the stream died on `MAX_PROOFS_PER_CHUNK`. Every resume repeated it identically. `Cumulative::from(&WatermarkBundle)` now folds, which makes it impossible to reseed without the chain half, and `reseed` retires the chain it just folded — the same rule that makes a folding voucher roll. **A stream re-anchored on every chunk.** `StreamMeter::anchor` stored an epoch id read BEFORE the send, but the send can itself roll the lane, so the id was the retired one and the stream re-anchored forever after — a signature plus a fresh 256-keccak ladder per chunk, which is the whole cost the chain exists to avoid. It reads the epoch after the send now, as its sibling branch already did. **The tracked-fetch API never surfaced the epoch.** It copied its ledger back through `from_cumulative`, which reports `next_epoch = 0`; the stores max-merge and ignore 0, so a caller persisting it never advanced the counter and a retry after an unclean death re-derived the seed of a chain the node still meters. It uses `from_ledger` now, like the two sibling persist paths — which also switches the cumulative to `settlement`, correct here for the same reason it is there: a voucher left armed by an ambiguous send is owed, and the error arm is where that happens. **The preimage receipt logged the wrong bytes.** A reveal walks from the LANE's frontier, so one arriving ahead of a sibling's pays for more than its own stream's delta, while `credit_advance` caps it below that delta when the watermark does not reach. The audit log now records what the lane charged. **And the chain walked past the spending cap.** `advance_presigned` refuses a voucher over the capability's cap; `advance_preimage` refused nothing, and a chain advances the claim without a signature. The contract clamps payment at `cap - spent` rather than reverting, so the node would have gone on crediting deliveries against a claim it could never collect and eaten the difference. A reveal answers for the cap now, and — since `SpendingCapExhausted` is the one recoverable reason this path can raise — its rejection carries the watermark bundle the payer needs to raise the cap and resume. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ction by proof kind Two changes from review, landed together because the first is what makes the second safe. **The chain's seed comes from its anchor, not a counter.** A chain is now seeded `keccak(TAG | master | lane | anchor | chunk_price)`, where `anchor` is the cumulative amount in the chain's own opening voucher. The lane's cumulative is monotone for its whole life and rolling a chain is DEFINED as folding its frontier into a new signed amount — so the anchor already counts chains, in a number the protocol maintains and both sides can read. That makes the double-pay the counter guarded against unrepresentable rather than merely guarded: the fold is exactly what moves the amount, `A -> A + k*p` for `k >= 1`, so every chain after a fold derives a different seed. Re-deriving at an UNCHANGED anchor is not a collision but chain resumption — the anchor is unchanged precisely because nothing folded, so the root is the one the node still meters. `chunk_price` is in the derivation because a reveal is priced by the voucher that redeems it: a reprice at an unchanged anchor would otherwise redeem old preimages at the new rate, which the counter only avoided by happening to roll. So the counter is gone — persistence, max-merge, allocation, `with_chain_epoch` / `prior_epoch` plumbing, and the lane row's column. The payer now stores nothing for the chain: its cumulative already says which chain it resumes on, and the signing key reproduces the rest. Wire and ABI are untouched; the root was always an opaque commitment. A retired chain whose opening anchor is forgotten can never be re-derived — nothing needs one, and ADR 003 now says so. **A rejection undoes the proof that was actually refused.** `resolve_reject` rewound `committed -> prev` on every rejection, which was exact when only vouchers could be refused. The chain broke that: the refused proof is often a REVEAL, and rewinding the anchor then un-commits a voucher the node accepted — the payer's anchor sits permanently below the node's, every later voucher regresses, and a re-anchor states a cumulative the node passed long ago. The ledger now records which kind of proof it last put on the wire. A refused reveal gives back one chunk of accrual AND the index it released — both, because the index IS the accounting (`anchor + index * chunk_price`), so returning the money while letting the next reveal go deeper would leave the node pricing a gap the payer never accrued. A refused voucher rewinds the anchor as before, and now also restores the chain it displaced: a rollover swaps the chain in before the send, so a refusal would otherwise leave the payer metering a chain the node never adopted. With that fixed, the non-folding re-anchor from the review lands too: `PoolLedger::reanchor` re-states the signed anchor under the live root and folds nothing, where routing it through `issue` would escalate it to a rollover and retire the chain it meant to join. Two scripted-upstream fixture bugs surfaced and are fixed: it reset the chain index on every voucher rather than only on a root change, and it applied a voucher before the deposit check — keeping the amount of one it then refused. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Anchor-derived seeds: adopted, in this PRVerified the reasoning against the code before taking it, and it holds. Two points worth recording: The reprice hole is real, not hypothetical. The scope was smaller than the sketch. The wire and ABI are untouched, as expected — but the NODE stores no epoch either. One consequence the sketch does not mention, which fell out while wiring it:
The "one loss" is recorded in ADR 003 §One chain per lane along with the rest of the derivation, in the terms you put it: a retired chain whose opening anchor is forgotten cannot be re-derived, and nothing needs one, because retiring a chain is what folds its frontier into a signed amount. |
|
Addendum to the anchor-seeding proposal, on what happens to "reuse protection" — three different things wear that name and they have different fates: Same-lane reuse protection (the epoch machinery) — deleted without replacement. Reuse at an unchanged anchor is either a no-op (nothing released below the root) or chain resumption (the same root is the correct root against an unfolded frontier); reuse after a fold cannot happen because the fold changed the derivation input. There is no residual invariant to maintain and no state to protect — lane-amount monotonicity does all the work, and it is already load-bearing for the voucher scheme itself. Cross-lane reuse protection — still needed, but it was never machinery. The reuse with real teeth is one root committed on two lanes: a preimage is a bearer proof, so provider B can claim chunks provider A delivered, out of the payer's pool. The defence is, and remains, the derivation itself — the lane triple domain-separated into the seed. The discipline is "seeds are always derived, never chosen or stored", a property of having exactly one code path, not a runtime check. (The PR is already right that a node-side check is pointless here: reuse pays the node, so the party able to check has no incentive to.) Node-side and contract-side guards — untouched, because determinism is a promise nobody else can verify. Suggested framing for the ADR 003 edit: reuse safety stops being an enforced property and becomes a derived one. The honest client cannot reuse dangerously because the derivation will not let it; the dishonest client was never constrained by client-side machinery anyway, and is exactly as constrained by node and contract checks as before. The epoch counter protected honest clients from their own state management — deleting the state deletes the threat. One caution: the derivation becomes the single safety-critical function on the client. A bug that makes two lanes or two anchors collide silently reintroduces everything above. The existing sibling-lanes-commit-disjoint-roots test should survive the redesign, plus two new cases: same lane, pre-fold vs post-fold anchors derive distinct roots; and the same anchor at two Generated by Claude Code |
alpergundogdu
left a comment
There was a problem hiding this comment.
Second review round, on 4e714d8 — covering the buyer-side recovery fixes and the anchor-seeding redesign. The redesign itself verified clean: anchor-derived seeds, fold-must-roll, the chain-extended floor clamp, per-stream anchors, and the wire/ABI surfaces all held up, and the first round's findings are addressed.
Six inline findings, ranked:
- Same-root price refresh strands the lane's claim —
adopt_chainrefresheschunk_pricewithout the refreshing voucher's signature, so the live claim revertsInvalidVoucherSignatureon-chain and takes the wholeredeemManybatch down with it (incentive/src/lane.rs). - Shared-ledger rejection rewind can un-commit a sibling stream's accepted voucher, permanently desyncing the lane (
client-pull/src/ledger.rs). master_secretassumes deterministic ECDSA theSignerSyncbound doesn't guarantee — suggested detect-and-degrade shape in the comment: startup double-sign check, plus root-vs-bundle comparison at resume with fold-and-roll on mismatch; never persist the master (incentive/src/chain.rs).- A full signing operation runs per cache-miss pull attempt and is usually discarded (
node/src/node_origin/mod.rs). settle_residual's doc contradicts the forced Keep→Roll on close — siblings get superseded and a never-used ladder is built (client-pull/src/lib.rs).- Stale
get_or_seeddocstring still describes the deleted epoch counter (node/src/buyer_ledgers.rs).
1–3 are the blocking ones: a node revenue-loss bug with batch-wide revert blast radius, and two lane-desync/wedge recovery bugs.
Generated by Claude Code
| if !refresh_price && !adopt_anchor { | ||
| return None; | ||
| } | ||
| next.chain.chunk_price = signed.voucher.chunk_price; |
There was a problem hiding this comment.
Same-root price refresh leaves the lane's live claim unredeemable on-chain.
The already-satisfied arm of adopt_chain updates chain.chunk_price from a re-asserting voucher without adopting that voucher's signature — last_signature stays the old voucher's, signed over the old chunkPrice.
Trigger: the node's quoted rate changes (governance floor move, or a config change across a restart with a persisted lane). A payer re-asserts the live chain_root at the new price; the voucher passes the quote match and signature recovery, lands here as already-satisfied, and the price is refreshed in place. live_claim()/strongest_claim() now pair the old signature with the new price: _verifyVoucher rebuilds the EIP-712 digest with the new chunkPrice, recovers the wrong signer, and reverts InvalidVoucherSignature. Because that's a revert rather than a zero-pay skip, every redeemMany batch that includes this lane fails wholesale — the node permanently loses the ability to collect this lane's anchor.
Fix: refresh the price only together with the refreshing voucher's own signature (and only at the exact watermark), or refuse the mismatched re-assert.
Generated by Claude Code
There was a problem hiding this comment.
Fixed. The same-root arm no longer refreshes the price at all.
You are right that the trigger is reachable: the handler gates on chunk_price_matches_quote(&wire, rate_per_mb) — the node's live quote, not the lane's chain price — so a re-assert at a moved rate passes and lands here already-satisfied. And live_claim() pairs last_signature with self.chain wholesale, so the refresh handed the redeem planner a claim whose digest carried a price the signature never covered.
Of the two options you named I took the second, refuse the mismatched re-assert, because it is the one that needs no new authority: an already-satisfied voucher pays for nothing, so it has no standing to reprice a frontier the lane already proved. adopt_chain's same-root arm now returns None whenever the lane holds a signature — the anchor-adoption case (no signature yet) still takes the voucher whole, price and signature together. A payer that wants a new price rolls, and a rollover advances the money and goes through advance_presigned, where the price and its signature are adopted from the same voucher.
Regression test: a_re_asserting_voucher_cannot_reprice_the_lane rebuilds the EIP-712 digest from the surviving claim and verifies it recovers to the signer, which is the property that was actually broken.
Worth noting the redesign makes this unreachable for an honest payer twice over now — a chain's root is drawn at random per chain, so an honest re-assert never carries a different price than the root was opened at. The guard stays because a malicious payer can put that voucher on the wire regardless, and the cost of accepting it is a batch-wide revert.
| match pipeline.prev.take() { | ||
| Some(prev) => { | ||
| pipeline.committed = prev; | ||
| match pipeline.last_proof.take() { |
There was a problem hiding this comment.
Shared-ledger rejection rewind can undo a sibling stream's accepted proof.
resolve_reject picks its rewind target from the lane-global last_proof, but rejections arrive per stream. On a shared PoolLedger (stream_fetch_shared, or the node's BuyerLedgers Arc), the interleaving:
- Stream A releases a reveal.
- Stream B issues a rollover voucher — accepted;
last_proof = Voucher,prev = old anchor. - A's
VoucherRejectedfor step 1 is processed → the Voucher arm rewindscommittedtoprev, un-committing B's accepted voucher and restoring the displaced chain.
The payer's anchor now sits permanently below the node's watermark: every later voucher either regresses or double-folds, and the accrual B's voucher folded gets re-added on top of an anchor that never advanced. The lane diverges from the node for the rest of its life.
The rewind needs to be keyed to the proof the rejection was actually for (per-stream proof identity), not to whatever the lane issued last.
Generated by Claude Code
There was a problem hiding this comment.
Fixed, keyed to per-stream proof identity as you describe.
The interleaving is reachable exactly as written — voucher_rejection runs on the stream that read the StreamError, and Pipeline.last_proof was lane-global, so on a shared PoolLedger the Voucher arm could rewind committed → prev for a rejection that was about a sibling's reveal. The docstring even stated the assumption it was resting on ("the rejected voucher is the LATEST committed one"), which holds only for a single-stream inline-await loop.
What landed:
LastProofnow names the proof rather than classifying it:Voucher { amount }andReveal { chain_root, index, chunk_price }. Both names are unique on a lane by construction — issuance is serialized so cumulative amounts strictly increase, and indices strictly deepen per chain.StreamMeterrecords the proof it sent (last_proof: Option<StreamProof>), stamped by the reveal, the opening voucher, the rollover, and the residual.reanchordeliberately does not stamp: it claims nothing, so there is nothing to rewind.resolve_reject(rejected: StreamProof)rewinds only while the named proof is still the last thing the lane did.
The part I want to flag, because it was not obvious to me until I wrote it down: a stale rejection rewinding nothing is not merely the safe answer, it is the correct one. For the lane to have moved on, a later proof must have been accepted — the node kept delivering, and continued delivery is acceptance. A later voucher folded the refused reveal's accrual into a signed amount the node took; a later reveal proved a depth that pays for everything below it. Either way the money a rewind would claw back has since been granted by a proof the node did not refuse, so clawing it back is what would put the payer below the node. That reasoning is in the docstring.
One extra fix while in there: the ambiguous-send case is now resolved by amount too. A rejection naming the armed voucher disarms it (the anchor never advanced, so disarming is the whole rewind); a rejection naming anything else leaves armed alone, where the old unconditional armed = None could have dropped a voucher whose fate was still open.
Regression test: a_stale_rejection_cannot_uncommit_a_siblings_accepted_voucher runs your exact interleaving.
| /// | ||
| /// Propagates a signer failure (a remote or hardware signer refusing the | ||
| /// request); a local key cannot fail here. | ||
| pub fn master_secret<S: SignerSync>(signer: &S) -> Result<B256, alloy::signers::Error> { |
There was a problem hiding this comment.
master_secret assumes deterministic ECDSA, but the SignerSync bound admits randomized signers — and the assumption should be checked, not held.
Anchor-based resumption rests on sign_hash_sync being RFC 6979-deterministic. That holds for local keys, but the generic bound admits KMS/HSM signers with randomized nonces (the codebase explicitly contemplates remote signers — pull_leg.rs handles a signer refusing a request). With such a signer, a restart after an unclean death signs MASTER_TAG differently → different master → a different root at the unchanged anchor than the one the node still meters. The client then attempts to resume, adopt_chain refuses the new root over the live frontier (verified_index > 0), every reveal resolves SUPERSEDED with zero credit, and the recoup loop bails at MAX_PROOFS_PER_CHUNK — identically on every retry.
Suggested shape: detect and degrade, never assume and never persist.
- Startup: sign
MASTER_TAGtwice and compare. Unequal ⇒ the signer is randomized: log that chain resumption is unavailable and skip resume attempts entirely. (Cheap, but only proves determinism within this process, not across restarts — an HSM can be stable per session and drift on firmware update or replica failover.) - Resume — the authoritative check: derive the root at the unchanged anchor and compare it to the root in the node's watermark bundle. Match ⇒ determinism held, resume. Mismatch ⇒ don't attempt
adopt_chainwith a root the node will refuse: fold the frontier via signed voucher (amount = A + k × chunk_price, which needs no seed — only the key) and open a fresh chain at the new anchor. This heals every mismatch cause, including ones no startup check can see. - Don't persist the master — that reintroduces a secret at rest to save one signature per restart.
The underlying observation that makes this safe: correctness never depended on determinism — only resumption efficiency does. A payer with a randomized signer degrades to "every restart rolls instead of resumes" (one extra signature and one fresh ladder per restart), which is exactly the right failure mode for an unverifiable assumption.
Generated by Claude Code
There was a problem hiding this comment.
Retracting step 1 (the startup double-sign check) — skip it. With the resume-time root-vs-bundle comparison in place it buys nothing functional: the resume path performs the same comparison at the only moment it matters, against actual evidence rather than a heuristic, and self-heals via fold-and-roll. The startup check adds a signing operation on every startup (a network roundtrip for exactly the remote signers it targets) to produce a log line slightly earlier, and it can false-negative anyway, since per-session stability does not prove cross-restart stability. Emit the "chain resumption unavailable with this signer" warning from the mismatch path when it actually fires.
So the recommendation reduces to: on resume, derived root ≠ bundle root at an unchanged anchor ⇒ fold-and-roll instead of attempting adopt_chain; and never persist the master. One mechanism, evidence-based, no precheck.
Generated by Claude Code
There was a problem hiding this comment.
Superseded — see the "resumption always folds" design comment on the PR. If a client never restarts an old chain (every resume folds the bundle frontier into a fresh voucher and opens a fresh chain), nothing ever re-derives a seed across a restart, and this finding's premise disappears along with the detect-and-degrade machinery: no determinism assumption, no root-vs-bundle mismatch handling, and master_secret itself can go (random per-chain seeds suffice). The one piece that transfers: the fold must verify the bundle's verified_index against the echoed tip before signing money over it.
Generated by Claude Code
There was a problem hiding this comment.
Taken as superseded, and the always-fold design is in.
chain.rs is now the ladder primitives plus random_seed(). master_secret, derive_seed, MASTER_TAG/SEED_TAG, and the anchor/price binding are gone, along with PoolContext::chain_master and PoolLedger's lane/master fields. A chain draws 32 bytes at open, holds them in memory, and drops them with the chain. The determinism question disappears with the re-derivation requirement, so there is no startup check, no root-vs-bundle mismatch path, and nothing to degrade — a KMS or HSM signer is now indistinguishable from a local key as far as chains are concerned.
Two things worth recording from wiring it:
Always-fold needed no new mechanism, only the deletion. A fresh process already seeds its ledger from the persisted cumulative and opens a fresh chain on first Open; reseed already retires the live chain because a bundle's cumulative folds its own frontier. What made a restart resume was solely that the seed re-derived to the same root. Remove the derivation and the same code paths fold. The one place that must not fold — a sibling joining a chain still in memory — was already reanchor, which folds nothing by construction, so your "if the seed is in memory, join it; if it is not, fold" rule fell out rather than had to be imposed.
unmetered died with it. It existed to build a ledger with no identity and no master; with random seeds it was new under another name, so there is one constructor, PoolLedger::new(seed). The unpaid legs are expressed by their rate-0 quote, which is where that fact belonged anyway.
The one piece that transfers is in — see the tip thread. Worth noting it survives the redesign only because resumable_watermark reconstructs the full seven-field voucher including chain_root and verifies the payer's own signature over it. I checked this specifically, because if chain_root were unauthenticated the tip check would be forgeable end to end (pick a tip, hash it up 255 times, present both) and random seeds would have left the payer with no way to recognise its own root after a restart. It is authenticated, so the check holds under every seeding scheme, as you said.
ADR 003 §One chain per lane is rewritten and there is a new §Resumption folds stating the rule, the fold arithmetic, the tip obligation, and the in-memory carve-out.
| signer: ctx.client_signer.address(), | ||
| provider: provider_addr, | ||
| }, | ||
| ctx.chain_master()?, |
There was a problem hiding this comment.
Full ECDSA signing operation on every cache-miss pull attempt.
lane_ledger calls ctx.chain_master() — whose own doc says "once per process" — on every pull candidate walk, and get_or_seed discards the result whenever the lane's ledger is already live. With a local key that's wasted CPU on the hot miss path; with a remote signer it's a blocking network roundtrip per candidate per pull.
Derive the master once (e.g. a OnceCell in NodeOriginDeps, or on the PoolContext factory) and reuse it.
Generated by Claude Code
There was a problem hiding this comment.
Gone entirely rather than cached — the always-fold redesign removed the caller.
lane_ledger no longer signs anything: there is no master to derive, so it is now infallible and both call sites lose their classify_pull_failure arms. PoolLedger::new(seed) takes no key material at all, so there is nothing for a OnceCell to hold.
You were right about the shape of the waste either way — get_or_seed discarded the derived master on every live-ledger hit, so the signature was pure loss on the common path, and on a remote signer it was a blocking round trip per candidate per pull.
| /// | ||
| /// A preimage always advances the claim by a *whole* chunk, so a partial | ||
| /// trailing chunk cannot be priced by one — it settles through a signature, | ||
| /// exact to one token base unit. The voucher re-asserts the live root rather |
There was a problem hiding this comment.
settle_residual's doc contradicts the forced Keep→Roll on close.
The doc claims the closing voucher "re-asserts the live root so sibling streams keep metering against it", but issue() (ledger.rs:500) overrides Keep→Roll whenever accrual is nonzero — which is the common case for any transfer that released at least one reveal. So the typical close retires the chain, materializes a brand-new 256-keccak ladder that is usually never used, and lands sibling streams' in-flight reveals under the old root as SUPERSEDED, forcing them to re-anchor — the exact behavior the comment says this path avoids.
Either the comment should describe the forced roll, or the close should be exempt from the fold-must-roll override via an explicit design for a folding-without-roll close (the fold-must-roll rule exists to prevent an amount that folded a frontier from coexisting with that frontier's root — a closing voucher that supersedes the chain it folds doesn't obviously need a replacement ladder built at all).
Generated by Claude Code
There was a problem hiding this comment.
Confirmed and fixed by correcting the comment, not the code.
The doc was wrong: pay() releases reveals before it settles, so any transfer that carried at least one whole chunk reaches settle_residual with nonzero accrual, and issue's fold-must-roll override turns the Keep into a Roll. The typical close does retire the chain and does land siblings' in-flight reveals as superseded.
I took the first option. The exemption you sketched is real but I do not think it is safe to take here: the fold-must-roll rule exists so that an amount which folded a frontier never coexists with the root that proved it, and "this voucher supersedes the chain it folds" is a property of the payer's intent, not of anything the node can check. The node sees a voucher naming a root at an amount that folded that root's frontier — and cannot distinguish a cooperative close from a payer double-counting, precisely because a closing voucher is not marked as one on the wire. Building the replacement ladder is 256 keccaks once per transfer; the alternative is a wire-visible close flag and a node-side rule to go with it, which is a larger change than the saving justifies.
So the doc now says what happens: Keep is asked for and usually not granted, the roll is the correct trade because the fold is what makes the residual exact, and Keep is what a sub-chunk transfer gets — nothing accrued, nothing to fold, and the sealed section, since such a lane never opened a chain.
| /// The ledger to issue this pull's vouchers through: the live one for `key`, or a fresh | ||
| /// one seeded from `seed` if there is none. | ||
| /// | ||
| /// `master` and `epoch` seed the lane's hash chain — the payer's derived master secret |
There was a problem hiding this comment.
Stale docstring describes the deleted epoch counter.
get_or_seed's doc still describes a master-and-epoch parameter pair and a persisted counter ("the counter its next chain opens at", "a live ledger has the authoritative epoch, because a concurrent pull may already have rolled past the persisted counter") — but the signature is get_or_seed(key, master, seed) and no counter is persisted anywhere after the anchor-seeding change. A reader will hunt for a nonexistent parameter and column.
Per CLAUDE.md's present-tense-canon rule, rewrite the paragraph to describe the anchor-derived seeding as it now is.
Generated by Claude Code
There was a problem hiding this comment.
Rewritten. get_or_seed(key, seed) now takes no master, and the paragraph describes what actually seeds a fresh ledger: the lane's persisted cumulative, and nothing else. The precedence paragraph below it (live entry wins over seed) was still accurate and stayed.
The stale text outlived two changes rather than one — the anchor-seeding change deleted the counter, and this round deleted the master too.
Design: resumption always folds — and then seeds can just be randomFollow-up to the anchor-seeding thread, collapsing several open questions into one rule: A client never restarts an old chain. Resumption leads with a fresh folding voucher ( Mid-chain resumption across a process or device boundary is the only consumer of seed re-derivability, and it buys one signature and one ladder per restart. Dropping it deletes, in order:
The anchor-seeding design in The boundary that stays: within a live process, a sibling stream joining a shared lane still re-anchors to the live chain with the delta-0 voucher ( What this does NOT remove:
Net: Generated by Claude Code |
alpergundogdu
left a comment
There was a problem hiding this comment.
Two findings from a simplification-focused pass, both connected to the "resumption always folds" design comment: the WatermarkBundle.tip check the fold must gate on (a real theft vector while verified_index is unauthenticated), and the retained-claim → rejection proposal for under-folding rollovers.
Generated by Claude Code
| /// bargain (ADR 005 §Watermark bundle). A bundle carrying no chain | ||
| /// (`verified_index == 0`, the sealed or never-metered case) folds nothing | ||
| /// and decodes to the anchor alone. | ||
| /// | ||
| /// Infallible: the fold is computed in `U256`, so the `u64` inputs cannot | ||
| /// overflow it and a caller can re-seed from a bundle without a `Result`. | ||
| fn from(bundle: &WatermarkBundle) -> Self { | ||
| let proved = U256::from(bundle.verified_index); | ||
| Self { | ||
| bytes: U256::from(bundle.bytes_delivered), | ||
| amount: U256::from(bundle.amount), | ||
| bytes: U256::from(bundle.bytes_delivered) | ||
| .saturating_add(proved.saturating_mul(U256::from(CHUNK_BYTES))), |
There was a problem hiding this comment.
The fold trusts an unauthenticated verified_index — a malicious node can inflate it and the client signs the theft. Verify the bundle's tip before folding.
Cumulative::from(&WatermarkBundle) folds verified_index × chunk_price into the amount the resuming client will re-sign. But verified_index is covered by no signature: the bundle's last_signature is the payer's own, over the old voucher, which contains no index. A malicious node can report verified_index = 255 when the client released 3, and the resuming client signs away up to 255 × chunk_price per resume for chunks never delivered.
The bundle already carries the antidote: tip — currently written by the node and read by nothing but test fixtures. The tip is the deepest preimage the client actually released, and preimages are unforgeable, so the node can only present a tip as deep as what it was genuinely given. The client must gate the fold on
keccak^verified_index(tip) == chain_root
— pure local hashing against a root the client already knows. With the check, verified_index is provable delivery depth; without it, the fold is an unauthenticated invoice. This applies under every seeding scheme, including the always-fold design where it becomes the only trust question left in resumption.
(If the check is added, tip earns its 32 wire bytes; if it is not, the field is dead weight and should be deleted — but the check is the right option.)
Generated by Claude Code
There was a problem hiding this comment.
Correct, and the check is in — gating resumable_watermark rather than the From impl, so every consumer of a bundle is covered by one gate (driver.rs's reseed, fetch_inner's self-heal, and genuine_exhaustion's desync test all go through it).
fn frontier_is_proved(bundle: &WatermarkBundle) -> bool {
bundle.verified_index == 0
|| verify_forward(B256::from(bundle.tip), bundle.verified_index,
B256::from(bundle.chain_root))
}verified_index == 0 folds nothing and carries an all-zero tip, so it is exempt; everything else must hash forward to the root.
The thing I checked before implementing, and that the finding depends on without saying so: chain_root has to be authenticated too, or the check is forgeable end to end. A node free to choose both values picks a random tip, hashes it up 255 times, and presents the pair — the equation holds and the payer signs. It is safe here because resumable_watermark rebuilds the full seven-field Voucher — chain_root and chunk_price included — and verifies the payer's own signature over it before anything else. So the root is one the payer demonstrably committed, and hashing an unforgeable preimage forward to it is a real proof of depth. Worth stating explicitly, since the anchor half's signature gate is documented as being about amount/bytes_delivered and it is easy to read it as not reaching the chain fields.
A bundle failing the check is not resumable at all (None), rather than folding the anchor alone. Folding the anchar alone would leave the payer below the node's frontier and walk straight into the under-fold rejection on the next voucher; refusing surfaces the fault and lets the walk try another candidate.
tip therefore earns its 32 bytes. Tests: resumable_watermark_rejects_a_frontier_the_tip_does_not_prove (released 3, node claims 255) and its positive twin. ADR 005 §Watermark bundle now carries it as a third gate alongside the two signature gates, and ADR 003 §Resumption folds states it as a MUST.
| /// redeem planner keeps submitting it — no on-chain sequencing rule is | ||
| /// needed, because payment is cumulative and the weaker claim simply pays | ||
| /// `0` (ADR 003 §Rollover). Read via [`Self::retained`]. | ||
| retained: Option<RedeemClaim>, |
There was a problem hiding this comment.
Proposal: replace the retained-claim machinery with a watermark-gated rejection of under-folding rollovers.
The retained slot — this field, the retention arm in advance_presigned, the retained branches in chain_slot/advance_preimage, strongest_claim's max logic, and roughly half the new persisted columns in channel_store.rs — exists for one trigger: a rollover voucher whose folded amount is below what the displaced chain's frontier already proved.
An honest payer cannot produce that trigger: issuance is serialized under the client's issuance lock and fold-must-roll makes the folded amount cover the frontier by construction. Cross-stream reordering on the node side can only land a late old-root reveal as SUPERSEDED, never as an under-fold. So the machinery fires only for a buggy or malicious payer — and for those, the simpler shape is the one every other payer fault already takes: reject the under-folding voucher, watermark-gated, with the bundle (which this PR already extended with the chain half for exactly this purpose) telling the payer the correct fold. Nothing accepted, nothing displaced, lane state unchanged.
Consequences of the swap, stated fully:
- Honest payers: unreachable either way — no change.
- Node's money: safe either way — retention keeps the stronger claim; rejection never accepts the weaker one.
- Buggy payer: a loud reject-and-recover instead of silently continuing on a weaker claim; surfaces the bug rather than masking it, at the cost of one round-trip on a path only broken clients hit.
- Malicious payer: delivery stops until a properly folded voucher arrives.
- If the "honest payers can't reach this" analysis has a hole: the failure mode is a rejection with a built-in recovery route (self-healing liveness stutter), not lost money — a benign way to be wrong.
The guard itself cannot be deleted outright — a malicious payer can put an under-folding voucher on the wire under any seeding scheme, so the choice is retention vs rejection, not vs nothing. But rejection deletes the field, the match arms, strongest_claim, and the persistence surface, and it is the last large block of state in the PR whose trigger no honest participant can produce. (Minor, if retention is kept anyway: strongest_claim's (None, kept) arm is unreachable — retention is only ever set alongside last_signature and the store persists both from one state.)
Generated by Claude Code
There was a problem hiding this comment.
Adopted — rejection, not retention.
advance_presigned's different-root arm now returns PoolError::AmountRegression { last: live.value(), got: voucher.amount } when the fold is short, before anything is adopted. That deletes retained, the retention arm, the retained branches in chain_slot/advance_preimage, strongest_claim, and all seven retained_* columns in channel_store. chain_slot collapses to a one-liner and advance_preimage loses its two-arm claim computation, which was the part where the retained frontier and the live one had to be advanced through different paths.
On the reason: I reused AmountRegression rather than adding a variant. It is watermark-gated already, which is the property the recovery needs, and the payer's existing self-heal for it is exactly right — reseed from the bundle, fold, retry. The variant's doc now says last is what the amount had to beat: the signed watermark on the ordering check, the full claim on the fold check. That avoids a wire append for a case no honest payer reaches.
Your unreachability argument checks out against the code — issue holds the issuance lock across compute → sign → send, and the fold-must-roll override makes the folded amount cover the frontier by construction, so an honest payer cannot emit the trigger. And cross-stream reordering on the node side lands a late old-root reveal in chain_slot's miss branch as a zero-value fold, never as an under-fold.
Your minor note was right too, and it is moot now: (None, kept) was unreachable because retention was only ever set alongside last_signature, and the store persisted both from one state.
payment_settlement's "strongest claim" comment is rewritten — the first half (a lane's worth is anchor plus frontier, or the redemption floor never sweeps a lane sitting on unredeemed reveals) still holds and stayed; the second half no longer exists to justify. ADR 003 §Rollover and §Concurrent Streams updated: the lane meters exactly one chain, and the only way one is retired is by a signature that already paid for everything it proved.
Test: an_under_folded_rollover_is_refused asserts the error names the fold owed and that the lane is untouched, plus a small one pinning that the reason is watermark-gated — since the rejection's value is entirely in the bundle it carries.
alpergundogdu
left a comment
There was a problem hiding this comment.
Small cleanups from the simplification pass — a dead enum variant, a single-value parameter, epoch-era doc residue, and a constants/naming nit. All mechanical; some may be subsumed if the always-fold redesign reshapes these files, in which case fold them into that change rather than fixing twice.
For completeness, what the pass checked and deliberately did not flag as overengineered: the ladder primitives, the materialized 256-entry ladder (documented perf tradeoff), reanchor as a separate path from issue(0) (required by fold-must-roll), the one-step chain history and proof-kind rewind (both reachable and load-bearing), PULL_WINDOW_FLOOR, PoolLedger::unmetered, the per-stream anchor machinery, and the contract's chainMeter packing and reserved-span revert.
Generated by Claude Code
| enum LastProof { | ||
| /// A signed voucher. Rewinding it restores the previous anchor and hands | ||
| /// back the accrual that voucher folded. | ||
| Voucher, |
There was a problem hiding this comment.
EpochAction::Seal is dead — zero callers.
Grep across all crates and tests finds exactly one occurrence: the Seal => Some(None) arm in commit_epoch. The doc calls it "the cooperative close", but the actual close path (StreamMeter::settle_residual) uses Keep, and sealed vouchers already arise naturally — Keep on a lane with no chain yields ChainCommit::SEALED. Delete the variant and its arm; the sealed wire shape is untouched.
Generated by Claude Code
There was a problem hiding this comment.
Deleted. Confirmed zero callers — the only occurrence was its own match arm.
The variant's doc was also the misleading part: EpochAction now says outright that there is no "seal" statement because sealing is not a decision a caller makes. Keep on a lane metering nothing already commits ChainCommit::SEALED, which is every voucher a sub-chunk transfer sends. The sealed wire shape is untouched, as you said.
| /// nothing. | ||
| async fn anchor( | ||
| &mut self, | ||
| send: &mut SendStream, |
There was a problem hiding this comment.
anchor's open: EpochAction parameter has one caller passing one value.
The doc says "open distinguishes the two callers", but the only call site is release_chunk, always passing EpochAction::Open, so the open == EpochAction::Open guard is always true — the claimed second caller (residual settlement) goes through send_voucher directly and never calls anchor. Drop the parameter and the comparison.
Generated by Claude Code
There was a problem hiding this comment.
Dropped, parameter and comparison both.
Verified before cutting: .anchor( has exactly one call site, in release_chunk, always EpochAction::Open. settle_residual goes through send_voucher directly and never calls anchor — the doc described a caller that does not exist.
The doc now says what the single caller is and why residual settlement is not one: it commits to whatever the lane already meters against, so it has nothing to anchor.
| // Read the whole ledger, not just a cumulative. Two things ride on that. The | ||
| // epoch: `VoucherProgress::from_cumulative` cannot see one and reports `0`, | ||
| // which the store's max-merge then ignores — so a caller persisting | ||
| // `next_epoch()` would never advance it, and a retry after an unclean death | ||
| // would re-derive the seed of a chain the node still meters, releasing | ||
| // preimages at indices it has already covered. And the cumulative: `settlement` |
There was a problem hiding this comment.
Epoch-era doc residue (present-tense-canon violations), four sites in the client crate.
This comment justifies from_ledger with "The epoch: VoucherProgress::from_cumulative cannot see one and reports 0… a caller persisting next_epoch() would never advance it" — but VoucherProgress carries no epoch field and next_epoch() no longer exists anywhere on the tree. The other three:
lib.rs:348—VoucherProgress's doc claims it holds the pair "plus the lane's chain epoch"; the struct is{bytes_delivered, amount, advanced}.lib.rs:7andcrates/node/src/handlers/client/mod.rs:6— module docs still name the deletedVOUCHER_INTERVAL_BYTES.
All four should describe the anchor-derived (or, if the always-fold redesign lands, random-seed) scheme as it is.
Generated by Claude Code
There was a problem hiding this comment.
All four fixed, plus two more the sweep turned up.
lib.rs:1357— thefrom_ledgerrationale. The epoch half is gone; what remains is the reason that outlived it,settlementrather thancommitted, matching the two sibling persist paths.lib.rs:348—VoucherProgress's "plus the lane's chain epoch" removed; the struct is the pair.lib.rs:7andhandlers/client/mod.rs:6— both now describe the meter as it is: one preimage per deliveredCHUNK_BYTESchunk, with a signed voucher to open a chain, roll one, and settle a sub-chunk residual.
The two you did not list:
ledger.rs:91—ChainEpoch's own doc still said the seed isderive_seed(master, lane, epoch)with "onlyepochpersisted", which was the most misleading of the six: it named a function signature that had already changed once.e2e/src/client.rs:118— a comment about carrying the chain epoch forward across fetches on a session, explaining a stale-counter failure mode that no longer has a counter.
All six are rewritten for the always-fold scheme rather than the anchor-derived one, since that landed in the same push.
Worth noting for future sweeps: grepping next_epoch found two of these, but ledger.rs:91 and the e2e comment only surfaced on a prose grep for "epoch" — the identifier had already been renamed out of them while the explanation stayed.
| impl PreimageApplied { | ||
| /// The reveal was at or below the tracked frontier: already covered, and | ||
| /// nothing was hashed to find that out. | ||
| pub const ALREADY_COVERED: Self = Self { | ||
| amount_delta: U256::ZERO, | ||
| bytes_delta: U256::ZERO, | ||
| }; | ||
|
|
||
| /// The reveal named an epoch the lane no longer tracks — a signature has | ||
| /// since folded a frontier at least as deep. Real, but worth nothing. | ||
| pub const SUPERSEDED: Self = Self { | ||
| amount_delta: U256::ZERO, | ||
| bytes_delta: U256::ZERO, | ||
| }; |
There was a problem hiding this comment.
PreimageApplied::ALREADY_COVERED and ::SUPERSEDED are byte-identical constants.
Callers only ever consult advanced(), so the distinction lives solely in the constant names; one ZERO constant with a doc sentence naming both cases would do.
Related naming nit while here: VoucherRejectReason::ChainIndexTooLarge can only ever fire for index == 0 — an over-large index is unencodable in the u8 — so the variant is named for its unreachable half; something like ChainIndexZero would describe the case that actually occurs.
Generated by Claude Code
There was a problem hiding this comment.
Both done.
ALREADY_COVERED and SUPERSEDED collapse into one PreimageApplied::ZERO, with a doc sentence naming both cases and why callers cannot tell them apart: the answer is the same in both, so the only thing the split bought was two names for one value.
ChainIndexTooLarge → ChainIndexZero. This one is decdn-protocol, so it took a public-api snapshot regen (INSTA_UPDATE=always cargo nextest run -p decdn-protocol --features public-api-test) alongside the call sites, plus the three ADR tables that named it — ADR 003 §Off-chain Voucher Rejections, ADR 005 (the wire enum listing and the retry-semantics table), and ADR 016's redeemMany row. The variant doc now leads with zero being the whole of it, rather than explaining away a half that cannot occur.
Discriminant position is unchanged, so the postcard encoding is untouched.
…cted under-folds Review round 3 on the PayWord meter. Three correctness fixes, two design simplifications the review argued for, and the doc/dead-code sweep behind them. Chains draw a random 32-byte seed instead of deriving one. The seed is held in memory for the life of the chain and never reproduced, because a chain is never reopened across a process or device boundary: every resume folds the frontier the node proved into a fresh signed amount and opens a fresh chain. That deletes `master_secret`, `derive_seed`, the anchor/price binding, and the ECDSA signature `lane_ledger` was taking per pull candidate — reuse safety stops being a derived property and becomes one 2^-256 makes unreachable. The fold is now authenticated. A `WatermarkBundle`'s `verified_index` carries no signature — the voucher it echoes has no index field — so a node could report 255 where the payer released 3 and have the payer sign for the difference itself. `resumable_watermark` now gates on `keccak^verified_index(tip) == chain_root`, against the root the payer's own signature covers, which is what turns the index from a claim into a proof. An under-folding rollover is refused rather than salvaged. The retained-claim slot, `strongest_claim`, and seven `channel_store` columns existed for a case no honest payer can produce (issuance is serialized and a folding voucher must roll), so the node now rejects with the watermark-gated reason that carries the bundle stating the fold owed. Nothing accepted, nothing displaced, and the lane's claim is as strong after as before. Two rejections were also rewound against the wrong thing: - `adopt_chain` refreshed `chunk_price` on a re-asserting voucher without adopting that voucher's signature, pairing a new price with a signature over the old one. Redemption rebuilds the EIP-712 digest from both, so it recovered the wrong signer and reverted the whole `redeemMany` batch. An already-satisfied voucher pays for nothing and now reprices nothing. - `resolve_reject` picked its rewind from the lane-global last proof, but a rejection is read on the stream that earned it. On a shared ledger a reveal refused on stream A could un-commit stream B's accepted voucher. The stream now names the proof it sent, and a proof the lane has moved past rewinds nothing — provably the right answer, since the lane only moves on when a later proof was accepted. `EpochAction::Seal` (no callers), `StreamMeter::anchor`'s single-valued `open` parameter, and `PreimageApplied`'s two byte-identical constants are gone; `ChainIndexTooLarge` is `ChainIndexZero`, which is the only case it can report. Closes the review threads on ADR 003 §One chain per lane, §Resumption folds, §Rollover, and ADR 005 §Watermark bundle. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01JjiDQL7FuB8UHGBBpG1PjH
|
All twelve unresolved threads addressed in Three correctness fixes, all verified reachable against the code before implementing:
Both redesigns landed. Chains draw random seeds and every resume folds, which deletes Net: 893 insertions, 899 deletions. Two of the three bugs and both redesigns removed more code than they added. Verification: One thing left open, outside these threads: the PR still has no |
Closes #1752. Implements the design ADR 003 landed in #1751.
Delivery is metered with a
PayWordhash chain instead of a signed voucher per interval. The payer commitschain_root = keccak^255(seed)inside a signed voucher, then releaseskeccak^(255−k)(seed)after each delivered chunk. A tick costs one keccak — no signature, no acknowledgement, nothing durable to write before the node sends the next chunk. Preimage resistance makes the release self-proving, so a deeper preimage is the receipt for every chunk below it.Signatures become O(1) per transfer plus one per 255-chunk rollover, and the meter is four times finer (1 MiB rather than 4 MiB) because
CHUNK_BYTES == BYTES_PER_MBmakes a chunk price exactly the advertised per-MB rate.Redemption resolves both axes with one formula, and with no branch for the sealed case:
A sealed voucher (
chainRoot = 0, index 0, zero preimage) satisfies that same check with zeros and resolves to exactlycumulative; a real-root voucher settles its owncumulativeby passing the root as its own preimage. Nothing anywhere testschainRoot == 0.Pre-launch, so this is one straight wire/ABI cut — no shims, no dual-format readers, no version negotiation.
Layers
crates/protocol—CHUNK_BYTES/MAX_CHAIN_LENGTHreplaceVOUCHER_INTERVAL_BYTES.ChunkPreimagesits atClientMessagediscriminant 4, renumbering the tail; postcard yields the flat 33 bytes ADR 005 specifies, pinned by a golden-bytes test.VoucherandWatermarkBundlecarry their chain halves. Four handler-emitted reject reasons:BadPreimage,ChainIndexTooLarge,UnanchoredPreimage,ChunkPriceMismatch.crates/incentive— a newchainmodule holds the keccak ladder plus the per-lane seed derivation, domain-separated on(pool_id, signer, provider, epoch)under a master secret derived deterministically from the signing key. No two chains a payer opens are inter-derivable, and nothing secret is written to disk — only the epoch counter is persisted.LaneStatetracks the live epoch and, across an under-folding rollover, the retired-but-stronger claim.contracts—LaneVouchergainschainRoot,preimage, and a packedchainMeterword (chunkPrice << 8 | chainIndex), keeping the struct static at 8 words / 256 calldata bytes._resolveClaimhashes the submitted preimage forward tochainRoot— never from a stored intermediate, so the contract keeps no chain state — and extends the anchor. The soft rate floor clamps the chain-extended pair, so bytes proved by preimage carry the same per-byte price obligation as bytes proved by signature. New revertsBadPreimage,ChainMeterReservedNonZero,ClaimOverflow.crates/node+crates/client-pull— the seller reads either proof through one reader and places a reveal against the receiving stream's own anchor, which is what makes an unanchored reveal decidable per stream rather than ambiguously lane-wide. The buyer's ledger keeps the signed anchor and the chain accrual apart, and a voucher that folds accrual always rolls to a fresh root — otherwise the node holds the old root's frontier beside an amount that already folded it in, and the same chunks are counted twice. The credit-window floor becomes one chunk; #1669's ramp is untouched. The redeem planner submits the lane's strongest claim, so a lane sitting on unredeemed reveals is no longer invisible to the redemption floor.Deviations from the issue checklist
#1752 was filed at 08:41 UTC on 2026-08-19; ADR 003's
PayWordlanding merged at 14:56 UTC the same day. Where they disagree the ADR wins — the issue itself names it as canon — and ADR 003 is edited here where it disagreed with itself.ChainRootReusereject reasonChunkPriceMismatchin its placeLaneVoucher+4 fields, 288 calldata byteschainMeter, 8 words / 256 byteschunkPriceback touint256before rebuilding the digest.require(chainIndex <= MAX_CHAIN_LENGTH)uint8extraction caps the index by construction. ADR 003 lines 317/574 now name that revertChainMeterReservedNonZero.Tests
Named cases from the issue, at the layer that can actually decide them:
amountand reverts at any index above 0; real-root voucher at index 0 settles exactlyamount; full-depth walk at index 255; rollover old-then-new collects the same total as new-only; a superseded chain pays 0 and is skipped, not reverted; the floor clamp reads the extended pair (both directions: ceiling rises with the chain, and still bites when the extended claim cannot justify the extended bytes); a bad preimage reverts the whole batch where a zero-paying lane is merely skipped.UnanchoredPreimage; index 0 isChainIndexTooLarge; a chain opened below the quoted rate isChunkPriceMismatch; a reveal pays for a chunk and reopens the credit window.Not covered: an anvil e2e that redeems across a live rollover. Rollover is covered at contract and lane-state level; the cross-layer version is the gap.
The window floor the finer meter needed
The pull leg paces in CONTENT bytes against the frontier the serve leg publishes, and that frontier comes from PAID WIRE through
content_paid_frontier, which floors to a chunk-group boundary;WindowPacerthen floors its own room to whole groups. Two group-sized roundings therefore separate what a client has paid for from what the pull may fetch next, while the client releases its next preimage only once a wholeCHUNK_BYTESof wire has arrived.At a 4 MiB quantum the wire's interleaved proof bytes covered those roundings. At 1 MiB they do not: the pull parks with the client a few KiB short of the chunk it must complete to pay, and that payment is the only thing that would widen the window. Both sides then wait forever — which is what
two_clients_coalesce_one_upstream_pull_each_payshit, stalling on a 4 MiB blob at 2,088,960 wire bytes with 1,040,384 unproved against a 1,048,576 chunk.PULL_WINDOW_FLOORcarries both roundings on top of the chunk, so the gap closes at every window size — the ramp only ever widens from there. It binds the pacer alone: the pre-flight reservation and the serve loop meter in wire on both sides and need no allowance, so they keep pricing one chunk. Two pacer unit tests pin the invariant directly, so it fails at the arithmetic rather than as a 30-second e2e timeout.Review round 2
alpergundogdureviewed the buyer side of the meter and found five defects, all on recovery paths the happy-path suites never walk, plus a design proposal. All six are in.A resume dropped the chain half of the watermark. A node that rejects mid-chain reports its anchor AND the frontier its chain has proved, and the payer's side of the bargain is to fold
verified_index × chunk_priceback in — which no client code did. Re-seeding from the anchor alone opened a fresh root beside a frontier the node was still metering, so every reveal that followed folded nothing and the stream died onMAX_PROOFS_PER_CHUNK, identically on every retry.Cumulative::from(&WatermarkBundle)now folds, which makes it impossible to reseed without the chain half.A stream re-anchored on every chunk, because
anchored_epochwas read before a send that could itself roll the lane — a signature plus a fresh 256-keccak ladder per chunk, which is the whole cost the chain exists to avoid.The tracked-fetch API never surfaced the epoch, so a retry after an unclean death re-derived a seed the node was still metering. Moot now (below), but the call site was also the only one not reading
settlement, and it is fixed either way.The preimage receipt logged the wrong bytes — the stream's delta rather than what the lane charged.
And the chain walked past the spending cap.
advance_presignedrefuses an over-cap voucher;advance_preimagerefused nothing, and a chain advances the claim without a signature. The contract clamps atcap − spentrather than reverting (PaymentPool.sol:833), so the node would have kept crediting deliveries against a claim it could never collect. A reveal answers for the cap now, and its rejection carries the watermark bundle —SpendingCapExhaustedis the one recoverable reason that path can raise.The seed comes from the anchor now
The review proposed replacing the per-lane epoch counter with
seed = keccak(TAG ‖ master ‖ lane ‖ anchor ‖ chunk_price), and it is strictly stronger. The anchor is the cumulative in the chain's own opening voucher; the lane's cumulative is monotone and rolling a chain is defined as folding its frontier into a new signed amount, so the anchor already counts chains — in a number the protocol maintains and both sides can read. The fold is what moves the amount, so every chain after a fold derives a different seed by construction; re-deriving at an unchanged anchor is not a collision but chain resumption.chunk_priceis in there because a reveal is priced by the voucher that redeems it: a same-anchor reprice would otherwise redeem old preimages at the new rate, a hole the counter only dodged by happening to roll.So the counter is deleted — persistence, max-merge, allocation,
prior_epochplumbing, and the lane row's column. The payer stores nothing for the chain. Wire and ABI are untouched.And a rejection undoes the proof that was actually refused
Landing the review's non-folding re-anchor exposed a deeper bug it was masking.
resolve_rejectrewoundcommitted → prevon every rejection, exact when only vouchers could be refused; under the chain the refused proof is often a reveal, and rewinding then un-commits a voucher the node accepted, dropping the payer's anchor permanently below the node's. The ledger now records which kind of proof it last sent. A refused reveal gives back one chunk of accrual and the index it released — both, because the index is the accounting. A refused voucher rewinds the anchor and restores the chain it displaced, since a rollover swaps the chain in before the send.Two scripted-upstream fixture bugs surfaced and are fixed: it reset the chain index on every voucher rather than only on a root change, and it applied a voucher before the deposit check.
Verification
cargo nextest run --workspace— 2888 passed, 0 failed (two consecutive full runs)cargo clippy --workspace --all-targets --all-features,cargo fmt --check,cargo doc --document-private-items— cleanforge test— 843 passed, including 16 newPayWordcasesFOUNDRY_PROFILE=ci forge build --sizes --deny warnings,forge fmt --check,solhint— cleanaderyn0 high;slitherintroduces noPaymentPoolfinding_resolveClaim);.gas-snapshotregenerateddecdn-nodesettlement + bring-up 5 passed, journeys 49 passedReview round
Copilot found a genuine break the workspace run could not have caught:
cli_bundle_pull_pool_idasserts each blob's wire length stays under oneCHUNK_BYTESwhile their sum crosses it, and the blobs were sized for the 4 MiB quantum — so the premise assertion aborts the journey. It isanvil-e2e-gated, so it compiled clean and never ran. Resized to 768 KiB / 512 KiB, with the straddle verified against the real encoder (789,440/526,272, summing to1,315,712, against a1,048,576chunk) rather than by eye.The same staleness in comment arithmetic is corrected across both
cli_fetch_topupsizing blocks,pool_floor_credit_bound,dispatch.rs, and severalclient_loopbackfixtures. None of it was load-bearing — those tests price from real wire bytes or absolute deposits — but a comment asserting an invariant the code no longer holds is worse than none.INGEST_CHECKPOINT_BYTESkeeps its 4 MiB cadence with an honest doc instead. It is a fsync-amortization knob whose text claimed alignment to the payment quantum; a fault can re-pay up to four chunks, and narrowing that costs 4× the fsync rate for a storage tradeoff, not a payment-correctness one.Out of scope
#1769 —
serve_leghoists its credit window once and never re-ramps, unlike its cache-hit twin, so a paying client served through a miss stays at stop-and-wait. Pre-existing since #1669.🤖 Generated with Claude Code