Skip to content

feat(payments): implement PayWord hash-chained per-MB meter (protocol + incentive + contracts) - #1770

Merged
thiras merged 10 commits into
mainfrom
feat/1752-payword-hash-chain-meter
Aug 23, 2026
Merged

thiras merged 10 commits into
mainfrom
feat/1752-payword-hash-chain-meter

Conversation

@yigitdot

@yigitdot yigitdot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Closes #1752. Implements the design ADR 003 landed in #1751.

Delivery is metered with a PayWord hash chain instead of a signed voucher per interval. 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. 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_MB makes a chunk price exactly the advertised per-MB rate.

Redemption resolves both axes with one formula, and with no branch for the sealed case:

claimed = amount + chain_index × chunk_price

A sealed voucher (chainRoot = 0, index 0, zero preimage) satisfies that same check with zeros and resolves to exactly cumulative; a real-root voucher settles its own cumulative by passing the root as its own preimage. Nothing anywhere tests chainRoot == 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_LENGTH replace VOUCHER_INTERVAL_BYTES. ChunkPreimage sits at ClientMessage discriminant 4, renumbering the tail; postcard yields the flat 33 bytes ADR 005 specifies, pinned by a golden-bytes test. Voucher and WatermarkBundle carry their chain halves. Four handler-emitted reject reasons: BadPreimage, ChainIndexTooLarge, UnanchoredPreimage, ChunkPriceMismatch.

crates/incentive — a new chain module 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. LaneState tracks the live epoch and, across an under-folding rollover, the retired-but-stronger claim.

contracts — LaneVoucher gains chainRoot, preimage, and a packed chainMeter word (chunkPrice << 8 | chainIndex), keeping the struct static at 8 words / 256 calldata bytes. _resolveClaim hashes the submitted preimage forward to chainRoot — 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 reverts BadPreimage, 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 PayWord landing 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.

Issue said Here Why
add a ChainRootReuse reject reason none; ChunkPriceMismatch in its place §One chain per lane: root reuse pays the node, so a rejection rule protects nobody who would choose to run without it, and enforcing it needs an unbounded never-expiring set of every root ever seen. The payer's seed derivation is the whole defence.
LaneVoucher +4 fields, 288 calldata bytes packed chainMeter, 8 words / 256 bytes §Voucher signatures are compact. The packing is invisible to signers — the contract widens chunkPrice back to uint256 before rebuilding the digest.
on-chain require(chainIndex <= MAX_CHAIN_LENGTH) no index bound; the reserved span is guarded instead A uint8 extraction caps the index by construction. ADR 003 lines 317/574 now name that revert ChainMeterReservedNonZero.

Tests

Named cases from the issue, at the layer that can actually decide them:

  • Contract — sealed voucher settles exactly amount and reverts at any index above 0; real-root voucher at index 0 settles exactly amount; 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.
  • Wire — two concurrent streams on one lane with interleaved, out-of-order and skipped indexes converge on the deepest index and the lane's claim is a maximum, never a sum; a reveal before its epoch voucher is UnanchoredPreimage; index 0 is ChainIndexTooLarge; a chain opened below the quoted rate is ChunkPriceMismatch; a reveal pays for a chunk and reopens the credit window.
  • Lane state — deepest-wins hashes nothing at or below the frontier; a correct fold loses nothing; an under-folding rollover retains the stronger claim and a slower sibling keeps extending it.
  • Chain primitive — ladder round-trips at 1/128/255; sibling lanes commit disjoint roots; the master reproduces from the key alone; nothing verifies against a zero root.

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; WindowPacer then 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 whole CHUNK_BYTES of 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_pays hit, 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_FLOOR carries 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

alpergundogdu reviewed 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_price back 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 on MAX_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_epoch was 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_presigned refuses an over-cap voucher; advance_preimage refused nothing, and a chain advances the claim without a signature. The contract clamps at cap − spent rather 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 — SpendingCapExhausted is 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_price is 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_epoch plumbing, 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_reject rewound committed → prev on 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 — clean
  • forge test — 843 passed, including 16 new PayWord cases
  • FOUNDRY_PROFILE=ci forge build --sizes --deny warnings, forge fmt --check, solhint — clean
  • aderyn 0 high; slither introduces no PaymentPool finding
  • gas re-pinned: the sealed path moves ~+853 gas/lane (three mostly-zero calldata words plus _resolveClaim); .gas-snapshot regenerated
  • anvil, against a live chain: decdn-node settlement + bring-up 5 passed, journeys 49 passed

Review round

Copilot found a genuine break the workspace run could not have caught: cli_bundle_pull_pool_id asserts each blob's wire length stays under one CHUNK_BYTES while their sum crosses it, and the blobs were sized for the 4 MiB quantum — so the premise assertion aborts the journey. It is anvil-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 to 1,315,712, against a 1,048,576 chunk) rather than by eye.

The same staleness in comment arithmetic is corrected across both cli_fetch_topup sizing blocks, pool_floor_credit_bound, dispatch.rs, and several client_loopback fixtures. 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_BYTES keeps 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_leg hoists 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

@alpergundogdu
alpergundogdu requested a balanced review from Copilot August 20, 2026 16:37

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR 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_price on Voucher/WatermarkBundle, CHUNK_BYTES/MAX_CHAIN_LENGTH (retiring VOUCHER_INTERVAL_BYTES), and four new VoucherRejectReason variants.
  • incentive/contracts: new chain module (keccak ladder + per-lane seed derivation) and LaneVoucher.chainRoot/preimage/packed chainMeter, with _resolveClaim walking the preimage to the root; new reverts BadPreimage, 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.

Comment thread crates/e2e/tests/cli_fetch_topup.rs Resolved
yigitdot and others added 4 commits August 21, 2026 15:12
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]>
@yigitdot
yigitdot force-pushed the feat/1752-payword-hash-chain-meter branch from 3649eb4 to cac76fe Compare August 21, 2026 12:18
@github-actions

github-actions Bot commented Aug 21, 2026 •

Copy link
Copy Markdown

Contracts coverage

Line coverage: 89.69% (2575/2871 lines)
▲ +0.04pp vs base (89.65% → 89.69%)
Run: 32669068759

@github-actions

Copy link
Copy Markdown

Gas snapshot

No gas changes vs base.

@github-actions

github-actions Bot commented Aug 21, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 81.58% (was 81.32%, ▲ +0.26%) — 62828/77018 lines

File Coverage Lines Δ
crates/cli/src/commands/config.rs 86.53% 546/631 ● 0.00%
crates/cli/src/commands/fetch.rs 39.40% 470/1193 ▲ +0.18%
crates/client-pull/src/ledger.rs 97.03% 752/775 ▼ 2.39%
crates/client-pull/src/lib.rs 89.09% 1649/1851 ▲ +0.14%
crates/client-pull/src/pacer.rs 99.06% 210/212 ▲ +0.09%
crates/client-pull/src/ranged_store.rs 90.10% 974/1081 ● 0.00%
crates/client-pull/src/source.rs 90.34% 262/290 ● 0.00%
crates/common/src/config/mod.rs 97.11% 6865/7069 ● 0.00%
crates/common/src/config/resolved.rs 100.00% 42/42 ● 0.00%
crates/e2e/src/client.rs 0.00% 0/455 ● 0.00%
crates/incentive/src/buyer_pool.rs 90.17% 376/417 ● 0.00%
crates/incentive/src/buyer_pool_table.rs 90.18% 817/906 ● 0.00%
crates/incentive/src/capability.rs 98.92% 184/186 ▲ +0.01%
crates/incentive/src/chain.rs 100.00% 111/111 new
crates/incentive/src/client_bridge.rs 98.05% 201/205 ▼ 0.36%
crates/incentive/src/credit.rs 100.00% 29/29 ● 0.00%
crates/incentive/src/lane.rs 94.54% 849/898 ▼ 1.69%
crates/incentive/src/payment_pool.rs 98.75% 79/80 ● 0.00%
crates/incentive/src/rate.rs 96.17% 176/183 ● 0.00%
crates/incentive/src/store.rs 91.64% 263/287 ● 0.00%
crates/incentive/src/voucher.rs 99.30% 284/286 ▲ +0.03%
crates/node/src/admin.rs 93.13% 976/1048 ● 0.00%
crates/node/src/buyer_ledgers.rs 100.00% 79/79 ● 0.00%
crates/node/src/channel_store.rs 85.73% 1087/1268 ▲ +0.18%
crates/node/src/handlers/client/delivery.rs 95.69% 244/255 ▼ 0.27%
crates/node/src/handlers/client/dispatch.rs 85.80% 441/514 ● 0.00%
crates/node/src/handlers/client/mod.rs 92.06% 1205/1309 ▼ 0.21%
crates/node/src/handlers/client/serve_leg.rs 83.91% 146/174 ▼ 2.07%
crates/node/src/handlers/client/voucher.rs 91.46% 482/527 ▼ 0.62%
crates/node/src/handlers/client/window.rs 75.38% 300/398 ▲ +0.12%
crates/node/src/handlers/client/wire.rs 97.73% 129/132 ● 0.00%
crates/node/src/node_origin/backend_source.rs 75.97% 196/258 ▲ +0.19%
crates/node/src/node_origin/mod.rs 91.26% 1128/1236 ▼ 0.01%
crates/node/src/node_origin/pull_leg.rs 85.59% 576/673 ▲ +0.51%
crates/node/src/payment_settlement.rs 51.75% 621/1200 ▲ +0.41%
crates/node/src/receipt_log.rs 91.06% 489/537 ● 0.00%
crates/protocol/src/client.rs 99.12% 787/794 ▲ +0.08%
History
Commit Total Δ vs base
cac76fe 81.49% ▲ +0.17%
93d327c 81.49% ▲ +0.17%
a385276 81.49% ▲ +0.17%
51eee94 81.50% ▲ +0.18%
4e714d8 81.58% ▲ +0.26%
b87cffb (HEAD) 81.58% ▲ +0.26%

yigitdot and others added 3 commits August 21, 2026 16:27
…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 alpergundogdu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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:

  1. 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).
  2. Shared-lane re-anchor: Keep→Roll escalation plus a stale anchored_epoch read 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).
  3. stream_fetch_tracked_with_progress never surfaces the epoch counter → seed reuse on retry after an unclean death, stalling the transfer (client-pull/src/lib.rs).
  4. Preimage-path audit receipt logs raw delta_bytes instead of the capped credited_bytes the voucher path was switched to (node/src/handlers/client/voucher.rs).
  5. 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

Comment thread crates/client-pull/src/lib.rs Resolved
Comment thread crates/client-pull/src/lib.rs Resolved
Comment thread crates/client-pull/src/lib.rs Resolved
Comment thread crates/cli/src/commands/fetch.rs Resolved

Copy link
Copy Markdown
Contributor

Design: drop the epoch machinery — derive the seed from the anchor instead

Proposal (from review discussion): replace the persisted per-lane epoch counter with

seed = keccak256(SEED_TAG ‖ master ‖ pool_id ‖ signer ‖ provider ‖ anchor_amount ‖ chunk_price)

where anchor_amount is the signed cumulative the chain's own voucher carries at open. The lane's cumulative is monotone for its lifetime, and rolling a chain is defined as folding its frontier into a new signed amount — so the amount already is an epoch counter, one the protocol maintains for free and both sides can always see.

Why this is strictly stronger than the counter

  • Fold-then-reuse becomes impossible by construction. The double-pay hazard the counter guards against is a root recommitted beside an amount that already folded its frontier (claimed = amount + index × chunk_price re-pays released preimages, which are bearer proofs). But the fold is what changes the amount: A → A + k·chunk_price, k ≥ 1, so every post-fold chain derives a different root, always. The (amount, root) pairing is rigid; the bug class cannot be expressed, rather than being prevented by correctly-babysat mutable state.
  • Re-derivation at an unchanged anchor is exactly chain resumption. Same anchor ⇒ nothing folded ⇒ the same root against the node's live frontier, continuing from verified_index + 1. A zero-release chain re-opened at the same anchor is a harmless no-op (no preimage below the root exists).
  • The safety-critical client state disappears. Today the counter must settle high in the store, and its durable bump must be ordered before any folding voucher reaches the node — a crash-consistency discipline that exists nowhere else in the scheme. Two current findings are bugs in exactly that babysitting: the set_from_cumulative path that hardcodes next_epoch = 0 (seed reuse → transfer wedges on retry), and half of the watermark-bundle reseed gap. With anchor-derived seeds there is nothing to persist and those failure modes have no state to corrupt.
  • Device portability falls out. A second device holding the key reads the anchor from the node's signed watermark bundle (or the on-chain anchor), derives the root directly, and either resumes the chain or folds — the fold moving the amount is itself what freshens the next root. No counter sync, no epoch-recovery scan.
  • Even the forgetful/adversarial-node edge improves. A stale counter lets a node re-claim folded chunks. Under anchor-seeding, an unfolded frontier a node surfaces corresponds to bytes it delivered and the client consumed — paying it settles a real debt, not a double charge, bounded as before by MAX_CHAIN_LENGTH × chunk_price.

Why chunk_price must be in the derivation

Preimages are bearer proofs and redemption prices them from the voucher. If a chain opened at anchor A with price p₁ releases k, and a later voucher carries the same anchor with p₂ > p₁ (a reprice with nothing folded), the same root under a higher price lets the node redeem the old preimage for k·(p₂ − p₁) extra. The counter design only dodges this because a reprice happens to roll. Binding the price into the seed closes it structurally: a reprice is a different chain.

Assumptions and the one loss

  • Leans on lane-cumulative monotonicity and pool_id never being reused — both already load-bearing for cumulative-voucher replay safety.
  • "Amount at open" must be pinned to the signed anchor in the chain's opening voucher, not a live in-memory figure; the voucher is the natural definition.
  • The one capability lost: a retired chain whose open-anchor is forgotten can never be re-derived (a small counter space can be scanned; U256 amounts cannot). No current flow appears to need a retired chain's seed; worth one sentence in ADR 003 either way.

Scope

This deletes rather than adds: next_epoch persistence and its max-merge rule, PoolLedger's epoch-id allocation, with_chain_epoch/prior_epoch plumbing, and the epoch half of LaneState — with derive_seed's inputs changing from (lane, epoch) to (lane, anchor, chunk_price). Wire and ABI are untouched (the root stays an opaque commitment). Pre-launch, so a clean cut per repo policy, plus an ADR 003 edit for §One chain per lane. Findings #1 (bundle fold) and #2 (Keep→Roll re-anchor) stand independently of this change.


Generated by Claude Code

yigitdot and others added 2 commits August 22, 2026 23:55
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]>
@yigitdot

Copy link
Copy Markdown
Contributor Author

Anchor-derived seeds: adopted, in this PR

Verified the reasoning against the code before taking it, and it holds. Two points worth recording:

The reprice hole is real, not hypothetical. LaneState::advance_presigned does next.chain.chunk_price = signed.voucher.chunk_price on a same-root voucher, and redemption prices reveals from the voucher — so a same-anchor reprice would redeem old preimages at the new rate. As you say, the counter only dodges it by happening to roll. It is in the derivation now, and there is a test asserting the price moves the seed.

The scope was smaller than the sketch. The wire and ABI are untouched, as expected — but the NODE stores no epoch either. LaneState carries LaneChain (root/index/tip/price), which stays; the counter was purely buyer-side. So the deletion is: derive_seed(lane, anchor, chunk_price), ChainEpoch re-keyed on the anchor, PoolLedger's counter and allocation, VoucherProgress::next_epoch/with_epoch, PoolContext::prior_epoch/with_chain_epoch, the BuyerLaneProgress column and its max-merge, and the plumbing through buyer_channel, node_origin, the CLI, and four test files. No node lane-state or store-schema change.

One consequence the sketch does not mention, which fell out while wiring it: issue now computes the voucher BEFORE drawing the chain it commits. A rollover's anchor is the FOLDED amount, so seeding from the pre-fold figure would tie the new chain to the retired one's anchor — exactly the (amount, root) pair that must never repeat.

ChainEpoch also gets a small win: the ledger keeps one step of displaced-chain history so a rejected rollover can be undone, which is what finally let the non-folding re-anchor land (see the thread on that finding).

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.

Copy link
Copy Markdown
Contributor

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. adopt_chain refusing a new root over an unfolded frontier, anchor monotonicity in _resolveClaim, ChunkPriceMismatch, the reserved-span revert: none of these are payer reuse protection. They protect the node's revenue and the contract's ledger from arbitrary counterparties. The seed derivation is secret and client-internal; from the node's seat a client is just a source of signed vouchers and 33-byte reveals from any implementation, honest or not. Determinism simplifies the honest client; it can never shrink what the honest node must check.

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 chunk_prices derives distinct roots.


Generated by Claude Code

@alpergundogdu alpergundogdu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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:

  1. Same-root price refresh strands the lane's claim — adopt_chain refreshes chunk_price without the refreshing voucher's signature, so the live claim reverts InvalidVoucherSignature on-chain and takes the whole redeemMany batch down with it (incentive/src/lane.rs).
  2. Shared-ledger rejection rewind can un-commit a sibling stream's accepted voucher, permanently desyncing the lane (client-pull/src/ledger.rs).
  3. master_secret assumes deterministic ECDSA the SignerSync bound 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).
  4. A full signing operation runs per cache-miss pull attempt and is usually discarded (node/src/node_origin/mod.rs).
  5. 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).
  6. Stale get_or_seed docstring 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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread crates/client-pull/src/ledger.rs Outdated
match pipeline.prev.take() {
Some(prev) => {
pipeline.committed = prev;
match pipeline.last_proof.take() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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:

  1. Stream A releases a reveal.
  2. Stream B issues a rollover voucher — accepted; last_proof = Voucher, prev = old anchor.
  3. A's VoucherRejected for step 1 is processed → the Voucher arm rewinds committed to prev, 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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:

  • LastProof now names the proof rather than classifying it: Voucher { amount } and Reveal { 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.
  • StreamMeter records the proof it sent (last_proof: Option<StreamProof>), stamped by the reveal, the opening voucher, the rollover, and the residual. reanchor deliberately 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.

Comment thread crates/incentive/src/chain.rs Outdated
///
/// 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> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

  1. Startup: sign MASTER_TAG twice 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.)
  2. 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_chain with 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.
  3. 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread crates/node/src/node_origin/mod.rs Outdated
signer: ctx.client_signer.address(),
provider: provider_addr,
},
ctx.chain_master()?,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread crates/client-pull/src/lib.rs Outdated
///
/// 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread crates/node/src/buyer_ledgers.rs Outdated
/// 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor

Design: resumption always folds — and then seeds can just be random

Follow-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 (amount = A + verified_index × chunk_price, from the watermark bundle) and a fresh chain — always.

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 whole determinism question. master_secret's RFC 6979 assumption, the randomized KMS/HSM signer hazard, and the resume-time root-vs-bundle mismatch handling all exist to make an old chain reconstructible. If no chain is ever reconstructed, none of it is needed.
  • The derivation machinery itself. With no re-derivation requirement, a chain's seed can be 32 random bytes drawn at open and held only in memory. No master secret, no derive_seed, no anchor/price binding, no signing operation on the pull path (also resolving the per-candidate chain_master() cost). Same-lane and cross-lane reuse both vanish because 256-bit random values do not collide — the no-reuse property stops being derived and becomes trivial. Nothing secret is at rest, same as today.
  • The device-portability special case. A second device holds the key, reads the bundle, verifies it, folds, opens a fresh chain. Identical to a restart. No shared state of any kind.

The anchor-seeding design in 4e714d8 is sound — its safety argument (a fold always moves the derivation input) is exactly what makes it safe to simplify past: once every boundary crossing folds, the derivation input no longer needs to exist.

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 (reanchor). That is a stream joining a chain the ledger still holds in memory — not a reconstruction — and folding there would supersede siblings' in-flight reveals. The rule is: if the chain's seed is in memory, join it; if it is not, fold.

What this does NOT remove:

  • The fold must be authenticated — see the WatermarkBundle.tip finding: verified_index is signed by nobody, and the client signs money over it. keccak^verified_index(tip) == chain_root must gate the fold. This is required under every seeding scheme.
  • The node-side under-fold guard — a malicious payer can still send an under-folding voucher regardless of how honest clients derive seeds; per the retained-claim thread, a watermark-gated rejection is the simpler shape for it.
  • Node-side and contract checks generally — client-side simplicity is invisible to the node, as before.

Net: chain.rs shrinks to the ladder primitives (root_from_seed, preimage_at, verify_forward, pack_chain_meter) plus B256::random(), and the client's chain state becomes purely ephemeral. ADR 003's §One chain per lane reduces to one sentence: every chain opens on a fresh random seed, and every resume folds.


Generated by Claude Code

@alpergundogdu alpergundogdu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Comment on lines +59 to +69
/// 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))),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread crates/incentive/src/lane.rs Outdated
/// 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>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 alpergundogdu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Comment thread crates/client-pull/src/ledger.rs Outdated
enum LastProof {
/// A signed voucher. Rewinding it restores the previous anchor and hands
/// back the accrual that voucher folded.
Voucher,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread crates/client-pull/src/lib.rs Outdated
Comment on lines +1352 to +1357
// 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`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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:7 and crates/node/src/handlers/client/mod.rs:6 — module docs still name the deleted VOUCHER_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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

All four fixed, plus two more the sweep turned up.

  • lib.rs:1357 — the from_ledger rationale. The epoch half is gone; what remains is the reason that outlived it, settlement rather than committed, 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:7 and handlers/client/mod.rs:6 — both now describe the meter as it is: one preimage per delivered CHUNK_BYTES chunk, 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 is derive_seed(master, lane, epoch) with "only epoch persisted", 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.

Comment on lines +810 to +823
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,
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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
@thiras

thiras commented Aug 23, 2026

Copy link
Copy Markdown
Contributor

All twelve unresolved threads addressed in b87cffb8, with per-thread replies inline.

Three correctness fixes, all verified reachable against the code before implementing:

  • adopt_chain no longer refreshes chunk_price under a signature that never covered it — the node's price gate is against its live quote, not the lane's chain price, so a quote move made this reachable and cost the whole redeemMany batch, not just the lane.
  • resolve_reject is keyed to per-stream proof identity. A stale rejection now rewinds nothing, which is provably correct rather than merely safe: the lane only moves on when a later proof was accepted, so the money a rewind would reclaim has since been granted by a proof the node did not refuse.
  • The resume fold is authenticated: keccak^verified_index(tip) == chain_root, against the root the payer's own signature covers.

Both redesigns landed. Chains draw random seeds and every resume folds, which deletes master_secret/derive_seed, the anchor/price binding, and the per-candidate ECDSA signature. The retained-claim machinery becomes a watermark-gated rejection, deleting the slot, strongest_claim, and seven channel_store columns.

Net: 893 insertions, 899 deletions. Two of the three bugs and both redesigns removed more code than they added.

Verification: cargo nextest run --workspace 2888 passed; cargo clippy --workspace --all-targets -D warnings, cargo test --doc --workspace, RUSTDOCFLAGS=-D warnings cargo doc, and pre-commit run on the changed files all clean. ADR 003 (§One chain per lane rewritten, new §Resumption folds, §Rollover), ADR 005 (§Watermark bundle third gate, reject tables), and ADR 016 updated.

One thing left open, outside these threads: the PR still has no CHANGELOG.md entry, and this branch now carries several wire/API-breaking changes that the file's own conventions ask to be called out — ChainIndexZero, the EpochAction::Seal removal, and the dropped StoredLaneState columns, on top of the meter itself. Flagging rather than writing one, since it should probably cover the whole PR rather than just this round.

@thiras
thiras merged commit d5a18c5 into main Aug 23, 2026
26 checks passed
@thiras
thiras deleted the feat/1752-payword-hash-chain-meter branch August 23, 2026 22:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(payments): implement PayWord hash-chained per-MB meter (protocol + incentive + contracts)

4 participants