Skip to content

docs(adr): land PayWord (hash-chained per-MB meter) into ADR 003 - #1751

Merged
alpergundogdu merged 8 commits into
mainfrom
docs/1670-payword-hash-chain-meter
Aug 19, 2026
Merged

alpergundogdu merged 8 commits into
mainfrom
docs/1670-payword-hash-chain-meter

Conversation

@yigitdot

@yigitdot yigitdot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Closes #1670. Implementation follow-up: #1752.

Lands PayWord alone into ADR 003, where the payment model lives. No new ADR. The two split-out siblings — credit slow-start (#1669 → #1691) and async voucher persistence (#1672 → #1706) — are already merged and are not touched here.

The model

One voucher, whose cumulative amount is the settlement anchor. The hash chain is an optional, signature-free way to advance that anchor between signatures. Redemption is one formula:

claimed = amount + chain_index × chunk_price

chain_index = 0 settles exactly amount and walks nothing — identical in shape to the pre-PayWord voucher. chain_index > 0 exhibits a preimage for the chunks streamed past the last signature, and the contract walks ≤ MAX_CHAIN_LENGTH hashes. A closing voucher sets chain_root = 0, which seals it at amount with no contract branch and no optional field.

A tick costs one keccak, not one secp256k1 signature — which is the CPU cost the original PR set out to remove.

Settled parameters

Parameter Value Why
chunk_bytes 1 MiB, protocol constant USDC's 6 decimals: a chunk must price to ≥ 1 base unit. 1 MiB is ~10 units at the $0.01/GB target and still 1 unit at the $0.001/GB floor; 100 KB is unpayable at the floor
chunk_price ≡ the advertised rate_per_mb CHUNK_BYTES == BYTES_PER_MB, so no second price unit and no new governance knob — the payability floor is the existing deliveryFloor. Stays signed, so redemption never depends on a rate that moved after signing
MAX_CHAIN_LENGTH 255 Releasable indices 1..=255 encode directly in the one wire byte with no offset, so no off-by-one can exist. Index 0 is the redeem-time settlement case and never travels the wire
Signed voucher {pool_id, signer, provider, amount, bytes_delivered, chain_root, chunk_price} chain_length and chunk_bytes stay out as protocol constants (the calldata saving the issue asked for)

Deviation from the issue body, flagged for review: the issue says MAX_CHAIN_LENGTH = 256. This PR writes 255. 256 needs indices 1..=256, which does not fit one byte without encoding index − 1 — reintroducing exactly the off-by-one a fixed-width tag is meant to design out. Happy to switch if you prefer the literal 256.

Answers the concurrency constraint (@alpergundogdu's comment on #1670)

The comment asked for an explicit decision between (a) a single ordered payment stream per lane and (b) index-carrying ticks. This lands (b), plus a second rule the trilemma implies but the earlier draft never wrote down:

  1. Deepest preimage wins. index ≤ verified is ignored without hashing; index > MAX_CHAIN_LENGTH is rejected before any hashing; otherwise keccak^(index − verified)(preimage) must reach the deepest preimage held. Placement is by index, never arrival order, so cross-stream interleaving is free within an epoch.
  2. Each stream anchors its own epoch. A bare preimage does not name its chain and index is one byte, so the invariant is: on each stream, the epoch's chain_root voucher precedes that stream's preimages for that epoch — sent at stream open and again on each rollover, never before every preimage. Resends are cumulative and signed, so dedup is free.

ADR 005's "voucher on any active stream" rule survives for vouchers (self-describing cumulative amount) and is explicitly scoped away from preimages. One chain per lane is kept; per-stream chains would multiply rollovers and therefore signatures.

Gas, honestly

The walk is fallback-only. A sweep redeems the latest signed voucher (rollover or close), both of which redeem at index 0 and walk nothing. A preimage walk happens only when the payer vanishes mid-chain — at most once per abandoned stream, ≤ 255 keccaks (~16k gas), where the alternative is collecting nothing. What is genuinely additive is calldata: LaneVoucher widens from 160 to 288 static bytes, but a closing voucher's added bytes are zeros and compress to almost nothing on an L2, so a cooperative redemption stays near baseline.

Files

  • adr/003-payments.md — new Chunk Cadence and Hash-chain metering (PayWord) sections (payment resolutions, sealed voucher, payability floor, one-chain-per-lane, chain length and rollover); Concurrent Streams gains the two rules; Redemption and Close gains claim resolution while preserving current redeemMany(PoolBatch[]) grouping and skip-not-revert semantics; new Chain walk and redemption cost and Cross-lane preimage spend sections; EIP-712 typehash, rejection table, persistence tuple, and consequences updated.
  • adr/005-protocol.md — ChunkPreimage { preimage, index }, CHUNK_BYTES / MAX_CHAIN_LENGTH, VOUCHER_INTERVAL_BYTES retired, lanes section rewritten, four new VoucherRejectReason variants with retry semantics.
  • adr/016, adr/architecture.md, adr/glossary.md, adr/013, adr/038, adr/039 — redeem description, payment one-liners, new glossary rows, ClientMessage renumbering, framing size, renamed anchor.
  • Truth-preserving one-liners: adr/012, adr/024, adr/appendix-operator-key-rotation.md all argued for session keys from "25 signatures per 100 MB" — PayWord makes that two, so the arithmetic is corrected while the conclusion is left intact (the residual stream-open/rollover/close signatures and per-response slash_sig still rule out hardware-wallet-only operation). adr/017 P-0x volume inference now counts 1 MiB chunks. Worth a look if you'd rather ADR 024 re-argue its premise properly in a separate PR.

Docs only — no Rust, no Solidity. Implementation is #1752, filed as one issue rather than the three (#1693 / #1694 / #1695) that were split and closed.

🤖 Generated with Claude Code

yigitdot and others added 2 commits August 19, 2026 11:28
Replace the 4 MiB signed-voucher interval with a 1 MiB payment chunk metered
by a PayWord hash chain. One voucher keeps its cumulative `amount` as the
settlement anchor; `chain_root` heads an optional chain that advances that
anchor with no signature, and redemption resolves both with one formula:

    claimed = amount + chain_index * chunk_price

A tick costs one keccak instead of one secp256k1 signature, so signatures are
O(1) per transfer (stream open, each 255 MiB rollover, close) rather than one
per interval. A zero `chain_root` seals a closing voucher at exactly `amount`
with no contract branch.

Resolves the concurrency constraint raised on #1670 as option (b): preimages
travel as `preimage || index` (33 bytes, MAX_CHAIN_LENGTH = 255 so the byte is
the index), are placed deepest-first rather than by arrival order, and each
stream re-sends the epoch's `chain_root` voucher before its first preimage of
that epoch. One chain per lane stays shared across concurrent streams.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@yigitdot

Copy link
Copy Markdown
Contributor Author

Review of this PR — 30 findings

Three independent reviews (project-convention, documentation-accuracy, adversarial design), de-duplicated. Five findings are design-breaking. Everything below is in text this PR adds.

[V] marks a claim verified directly against the code rather than taken on trust.


Blocking — the design does not work as written (5)

B1. The zero-root sentinel collides with the root-reuse MUST. [V]
Every closing voucher carries chain_root = 0, and the MUST (003 § One chain per lane, § Cross-lane preimage spend, and the rejection table) has no exemption for it. The second closing voucher a node ever sees — on any lane, or the same lane's second transfer — is rejected ChainRootReuse, whose retry rule is "derive a fresh seed, do not retry with the same root". But 0 is the only value that seals a voucher. This breaks the cooperative close universally, and the cooperative close is what the whole "signatures are O(1), the walk is fallback-only" argument rests on.

B2. The voucher resends the anchoring rule mandates are always rejected. [V]
The per-stream rule requires re-sending the current root voucher at stream open and on each rollover, and calls resends "idempotent". crates/incentive/src/lane.rs:311 is if signed.voucher.amount <= self.last_amount { return Err(AmountRegression) } — an equal-amount resend is rejected, always. This also kills the UnanchoredPreimage recovery instruction ("send the current root voucher on this stream, then resend the preimage"), which is the only retryable path the new chain rules define.

B3. Rollover terminates sibling streams on a multi-stream lane.
Streams A and B on one lane, verified = 254. The payer releases index 255 on B, then signs V2 with root R2 and sends it on both. QUIC orders within a stream, not across, so the node may accept V2 on A first — adopting R2 and resetting verified = 0. B's in-flight index-255 preimage then walks to R1, not R2, and fails BadPreimage, which the retry table marks terminal. This fires on every rollover with ≥2 active streams — the exact configuration § Concurrent Streams exists to support. UnanchoredPreimage cannot rescue it: a bare 33-byte reveal does not name its chain, so the node cannot distinguish a superseded-chain reveal from garbage.

B4. chunk_price is payer-signed and validated nowhere. [V]
No ChunkPriceMismatch reason exists in either ADR. A node quotes 10 base units/MB; the buyer signs chunk_price = 1 (the governance floor). Every preimage then meters at one tenth of the quote, and a preimage carries no price of its own, so there is no per-tick moment at which the node could notice. It redeems cleanly on-chain — the floor check passes at exactly the floor. Up to ~10,000× underpayment at the ceiling rate. Pre-PayWord the price appeared only in the amount delta, which the node already checked against its own quote; PayWord promotes it to a signed field and never says the node must validate it.

B5. The rollover fold is undefined for early rolls, and the sweep advice is unsafe.
The fold is specified only for exhaustion (amount_old + 255 × chunk_price). Four documented paths force an early roll (ChainIndexTooLarge, ChainRootReuse, RateFloorRaised, and B1). A payer rolling at verified index 200 with amount_old + 1 passes AmountRegression — that guard compares the amount axis only, and the watermark keeps last_amount and highest_index separate — so "a sweep redeems the latest signed voucher" collects 1 base unit instead of 200 chunks. The mirror case breaks the payer's stated zero-exposure invariant: folding a flat 255 when 200 were delivered signs for bytes not received.


Important (11)

# Finding
I1 The ChainIndexTooLarge row claims redemption reverts on index == 0 — but index 0 is the normal settlement path, stated three times elsewhere. As written, the contract reverts on every cooperative close.
I2 index > MAX_CHAIN_LENGTH is unreachable: the wire index is u8 and MAX_CHAIN_LENGTH = 255. The anti-griefing check credited in four places is dead code; only index == 0 is reachable. The bound is real but comes from the type — which is the stronger property and should be what the ADR says.
I3 [V] ADR 037 was not updated — five surviving "voucher interval" statements, including the normative credit_max parameter row and an implementation-status note describing per-interval voucher collection in the serve loop. ADR 003 explicitly couples the two documents, so they now disagree on the credit-window floor by 4×.
I4 [V] The WatermarkBundle gate recovers last_signature over (poolId, signer, provider, amount, bytes_delivered). The voucher is now seven fields, so the gate never verifies and the self-heal path is dead. Last surviving five-field tuple in the tree.
I5 owed / unredeemed / M exclude the chain frontier. M is the stated security parameter and now under-covers by up to 255 × chunk_price per lane, so "the tail is structurally zero" is false at the margin. t and the M ≥ N·t sizing inherit it.
I6 Persistence stores highest_index but not the tip bytes. Only the payer can produce a value at depth k, so after a restart the node cannot redeem its frontier — precisely in the abandonment case that is the chain's entire justification. Separately tip₀ = chain_root, verified₀ = 0 is never stated, and getting it wrong yields preimages that revert redeemMany and sink the whole batch.
I7 [V] CHUNK_BYTES collides with the existing CHUNK_BYTES = 1024 (BLAKE3 leaf) in crates/cache/src/fill_session.rs:74, crates/client-pull/src/driver.rs:115, crates/node/src/node_origin/pull_leg.rs:75. ADR 005's diagram now puts 1 MiB and 1024 bytes two lines apart. Resolution: payment keeps CHUNK_BYTES; the 1024-byte constant is renamed in those three crates.
I8 "On exactly those three reasons" is now four, because this PR adds a BadPreimage bundle bullet — and the retry table marks BadPreimage "do not retry", which makes attaching a bundle pointless.
I9 Credit window: ADR 003 says per-stream with that stream's own paid; ADR 005 says applied collectively across the lane. The PR's own lane-wide chain and aggregate byte counter make per-stream attribution impossible. Under the 003 reading the withholding bound multiplies by stream count.
I10 cumulative − paid survives twice in § Voucher ordering after the PR redefined payment as claimed − paid everywhere else — a half-applied edit in an authoritative section.
I11 claimed / claimedBytes are no longer "bounded by construction" — they are computed from attacker-chosen calldata. Resolution width is never stated, and an arithmetic revert is not on the skip list, so one crafted voucher could sink a batch. The rate-floor overflow argument is stale for the same reason.

Minor / accuracy (9)

# Finding
M1 "160 to 288" collides with contracts/src/PaymentPool.sol:78-83, which already uses "160 calldata bytes instead of 288" for the opposite comparison (static vs dynamic signature). Post-merge the two numbers mean opposite things and the contract comment becomes wrong.
M2 The withholding bound is overstated — "the chunk is the withholding bound … a node cannot pause below one chunk". The bound is the ramped window (credit_max = 64 MiB); § Chunk Cadence says correctly, in the same diff, that the chunk is "not the node's exposure limit".
M3 "chunk_price is signed so redemption never depends on a governance rate that moved after the signature" is false — redeem reads the live deliveryFloor with no per-lane snapshot. Signing fixes the claim arithmetic, not redeemability.
M4 "On the common closing path those bytes are zeros" — chunkPrice carries the real rate on every voucher. Three of four are zero; the ADR states it correctly twice elsewhere.
M5 adr/024-account-abstraction.md:126 still argues from "the fixed voucher-granularity signing frequency" — the premise this PR removed 116 lines above, in the same file.
M6 adr/011-content-takedown.md:460 keys the in-flight takedown check on "after the voucher … is collected". Under PayWord the boundary artifact is a preimage, and ADR 011 is the cited home of that check.
M7 "33 bytes flat, with no length prefix and no varint" contradicts ADR 013's mandatory varint framing plus discriminant. 33 is the postcard struct body, not the frame — and the claim is load-bearing for MAX_CHAIN_LENGTH = 255.
M8 [V] ADR 013 shows a five-variant ClientMessage; the real enum has six (StreamError), with VARIANT_COUNT = 6 pinned by client_message_variant_count_matches_discriminants. The renumbering as written hands an implementer a failing test with no hint.
M9 The payability table never defines "GB" as 10⁹ or 2³⁰. Under the binary reading the chosen 1 MiB row prices to 0.977 → 0 base units at the floor — unpayable, the exact failure the 100 KB row is rejected for. The "Rounding per tick" column is also target-rate-only; at the floor a 1 MiB chunk quantizes 100%, not 10%.

Rigor / style (5)

  • S1. The Consequences bullet credits node-side root-reuse rejection as part of the cross-lane defence, but the attack is reuse across two providers, where no single node sees both lanes — the backstop contributes zero. The check also needs node-global, never-expiring state that the specified per-lane watermark cannot hold, with no retention bound.
  • S2. Rule 1 reads as if a lane starts with a verified preimage; tip₀ / verified₀ are never initialized.
  • S3. "A real root … is never 0" is a 2⁻²⁵⁶ statement asserted as certainty, inside an argument that otherwise reasons correctly about preimage resistance.
  • S4. Is the chunk size governable? § Chunk Cadence says "governance does not move it"; § Chunk sizing says "an operator and governance decision".
  • S5. ASD-STE100 violations added by the diff: "footgun", "the walk is noise", "no place for an off-by-one to live", "255 buys", "three things at once", "gives away". Plus mixed ≤ and <= inside inline code, inconsistent MUST bolding, and one 52-word sentence.

What actually needs redesigning

B1, B2 and B3 are one defect wearing three hats: per-stream epoch anchoring does not work. Making anchoring lane-scoped dissolves all three:

  • The node's chain state is already lane-wide (chain_root, verified, tip) and a lane has exactly one live root, so the node can always name the chain a bare preimage belongs to. UnanchoredPreimage then means only "this lane holds no root yet" — which is decidable, unlike the per-stream condition.
  • No per-stream resends → B2 disappears, and the extra signed message per stream per epoch disappears with it.
  • Retain the retired root for a drain window after a rollover and try an incoming preimage against it before rejecting → B3 disappears.
  • Exempt chain_root == 0 from the reuse and retirement rules → B1 disappears.

B4 needs a normative rule (node MUST reject a voucher whose chunk_price ≠ its quoted rate_per_mb) plus a reject reason. B5 needs the fold defined as verified_index × chunk_price on both axes, and the sweep restated as "redeem the strongest claim held" rather than "the latest signed voucher".

Also worth deciding: the 4 MiB → 1 MiB quantum retarget is not required by PayWord — the chain works at any quantum — and it is what produces most of this PR's blast radius, including I3.

🤖 Generated with Claude Code

@alpergundogdu

Copy link
Copy Markdown
Contributor

Response — resolutions for all 30 findings

Thanks for the review. The problems are almost all real; several of the proposed solutions are heavier than they need to be, and two rest on a misread. This comment supersedes the review and records the disposition of every finding. This PR is ADR-only — findings that cite code ([V]) are ADR-vs-code mismatches; the fix lands in the ADR, and any code change is a tracked follow-up.

Headline

B1, B2, and B3 are not "one defect — per-stream anchoring doesn't work." Anchoring stays per-stream; each of the three has an independent, minimal fix. Going lane-scoped is not required and we are not taking it.

Blocking

  • B1 — zero-root vs root-reuse MUST. We do not hold a rejection table (storing every preimage is unacceptable), and ChainRootReuse is deleted as a node-side reason outright. Root reuse harms the client: a shared root lets a preimage revealed on lane A be replayed to redeem on lane B, so a node profits by accepting a reused root — anyone can fork the node to accept it, and node-side rejection protects no one who would run it. Reuse-avoidance is a pure client-side invariant: unique, well-seeded random roots per lane. Deleting the reason removes the zero-root collision at its source.

  • B2 — "resends are always rejected." This is a misread of the layer. The primitive advance_presigned returns AmountRegression on amount <= last_amount, but the node handler (added by the concurrency work, feat(payments): self-describing vouchers to enable concurrent same-lane settlement #1699/perf(node): per-lane lock is held across ecrecover, serializing concurrent same-lane vouchers #1735) catches that and treats an at-or-below-watermark voucher as already-satisfied — a benign no-op, no advance, no reject. The only rejection left is the divergent same-amount-more-bytes case (feat(payments): self-describing vouchers to enable concurrent same-lane settlement #1699 rule 4). Idempotent resends already work. We are not relaxing the primitive to <: that would let a same-amount-more-bytes voucher through and sign for unpaid bytes, reopening the rule-4 hole. Fix is ADR wording only.

  • B3 — rollover terminates sibling streams. Fixed by per-stream self-anchoring, not a drain window: each stream stores its own last-seen voucher/root and the lane advances the payment frontier from per-stream state. The payer sends the new-root voucher on every active stream at rollover (not one stream with cross-propagation). QUIC in-stream ordering then guarantees stream B's index-255 preimage is validated against B's own current root (R1) before B's own V2 arrives; stream A adopts R2 independently. No cross-stream stomp.

  • B4 — signed chunk_price validated nowhere. Accepted. rate_per_mb is fixed for a node's lifecycle (not hot-reloaded), so the node MUST reject a voucher whose chunk_price ≠ its own quoted rate — a plain equality check at accept time — with a new reject reason. Carve-out from M4: the equality check applies to metering vouchers only; a sealed voucher (chain_root == 0) requires chunk_price == 0.

  • B5 — fold undefined for early rolls; sweep advice unsafe. Accepted. The fold is amount_old + verified_index × chunk_price on both axes, and the sweep is restated as "redeem the strongest claim held," not "the latest signed voucher." The early-roll trigger list shrinks: ChainRootReuse is gone (B1), leaving ChainIndexTooLarge and RateFloorRaised.

Important

  • I1 — Accepted. The index == 0 revert is written backwards; index 0 is the normal settlement path. Fix the row.
  • I2 — Accepted. index > MAX_CHAIN_LENGTH is unreachable; the wire index is u8. Drop the dead runtime check and state the 255 bound as a type property. (With I1, ChainIndexTooLarge nearly evaporates as a reason.)
  • I3 — Accepted. ADR 037 is reconciled in this PR. We keep the 4 MiB → 1 MiB retarget: the floor is node config/policy (1×, 4×, 100× are all fine), not a hard protocol constant, so this is doc sync, not blast radius.
  • I4 — Accepted. The WatermarkBundle recovery tuple moves to the full seven-field voucher, and the bundle carries everything the self-heal needs, including preimages. Pre-launch — we break the wire, no shim.
  • I5 — Accepted (ADR-text fix). M, owed, and unredeemed are defined in ADR 003; fold the chain frontier (verified_index × chunk_price) into the sizing so M ≥ N·t covers the tail.
  • I6 — Accepted. The persisted lane state includes the tip preimage, not just highest_index, so the frontier survives a restart (the abandonment case). We also state tip₀ = chain_root, verified₀ = 0 explicitly.
  • I7 — Accepted as proposed: payment keeps CHUNK_BYTES; the BLAKE3-leaf constant is renamed. That rename is a follow-up code change, not this ADR PR.
  • I8 — Accepted. Drop the BadPreimage bundle bullet; the bundle stays on exactly the three self-heal reasons. BadPreimage is a hash-chain mismatch, which a payment-watermark bundle cannot fix — correctly terminal — and under the B3 fix the spurious BadPreimage no longer arises. (For the record: the bundle is reactive on a gated reject, not sent at stream open, and the strict-advance monotonicity guard makes multi-stream self-heal converge rather than loop.)
  • I9 — Accepted. The credit window is lane-collective. We consolidate the stance to lane-wide and reconcile ADR 003 to ADR 005. (Note: B3's per-stream root anchoring is orthogonal to lane-collective credit accounting — different axes.)
  • I10 — Accepted. Finish the edit: cumulative − paid → claimed − paid in § Voucher ordering.
  • I11 — Accepted, split. The ADR asserts the resolution/width invariant for claimed/claimedBytes now. The contract hardening — a per-voucher arithmetic fault must skip, not sink the batch — is a separate follow-up (tracked). Mitigating context: nodes already validate these fields before recording, so a well-behaved node never submits a crafted voucher; the contract fix is defense-in-depth at the boundary.

Minor / accuracy

  • M1 — Accepted. State the voucher width in words, not the 160/288 pair the contract comment owns for the static-vs-dynamic-signature comparison. LaneVoucher is a static struct — every field is one 32-byte word (5 words / 160 B today); each added field costs one word; a clean target is 8 words / 256 B. Keep it static — only a variable-length field breaks alignment.
  • M2 — Accepted. The withholding bound is the ramped window (credit_max = 64 MiB), not one chunk. Correct the overstated line to match § Chunk Cadence.
  • M3 — Accepted (wording). Signing chunk_price fixes the claim arithmetic, not redeemability — redeem reads the live deliveryFloor. Separately, we are pursuing a soft-floor design (below-floor delivery is a byte-inflation attack, not a payment concern): a sub-floor voucher still pays cumulative but the credited/byte-weight is clamped to the floor-justified ceiling instead of the current hard revert. That is a tracked follow-up, not part of this PR.
  • M4 — Accepted, fixed by design rather than doc: the closing voucher is a clean all-zeros chain section (chain_root == 0 ⟺ index == 0 ∧ tip == 0 ∧ chunk_price == 0), because a sealed voucher meters no chunk. The "those bytes are zeros" statement then holds.
  • M5 — Accepted. Update adr/024:126 to the PayWord signing model, consistent with the edit already made higher in the same file.
  • M6 — Accepted and applied in this PR. adr/011:460 now terminates in-flight takedowns "at the next chunk boundary, after the preimage for the chunk already delivered is revealed."
  • M7 — Accepted, decoupled. 33 bytes is the postcard struct body; the wire frame adds ADR 013's varint length prefix and discriminant. MAX_CHAIN_LENGTH = 255 comes from the u8 index type (I2), not the 33-byte size — decouple the two claims.
  • M8 — Accepted. ADR 013's ClientMessage is updated to all six variants (0–5, including StreamError) to match VARIANT_COUNT = 6.
  • M9 — Accepted. Drop "GB"; align the payability table to the contract's canonical binary unit (BYTES_PER_MB = 1_048_576, floor 1 base unit/MiB). Under that unit the chosen 1 MiB row is payable at the floor — the "0.977 → 0" was a unit-mismatch artifact. Add an honest floor-rate rounding note (a 1 MiB tick quantizes fully at the floor).

Rigor / style

All five accepted.

  • S1 — Remove the Consequences bullet crediting node-side root-reuse rejection; it contributes nothing to the cross-provider case and needs unbounded node-global state (matches B1).
  • S2 — State the tip₀ = chain_root, verified₀ = 0 initialization (same as I6).
  • S3 — Soften "a real root is never 0" to a negligible-probability statement, not certainty.
  • S4 — Reconcile the chunk-size governability contradiction to one stance: governance-bounded, operator-set within bounds (mirrors the rate-floor pattern).
  • S5 — Rewrite the ASD-STE100 violations to plain STE, normalize ≤/<=, make MUST bolding consistent, and split the 52-word sentence.

On the retarget

We keep the 4 MiB → 1 MiB quantum retarget. It is not required by PayWord, but the quantum is node policy, so it carries no protocol-level blast radius — only the doc sync in I3, which lands here.

Follow-ups (separate from this ADR PR)

  1. Rename the BLAKE3-leaf CHUNK_BYTES constant so payment keeps the name (I7).
  2. Harden redeemMany so a crafted voucher skips rather than reverting the batch (I11).
  3. Soft-floor: clamp byte-credit instead of reverting sub-floor vouchers (M3).

Applies the maintainer's rulings on all 30 review findings.

Design changes:
- Delete ChainRootReuse as a node-side reason. Root reuse pays the node and
  costs the payer, so a node-side rejection protects nobody who would run it,
  and enforcing it needs unbounded node-global state. Reuse-avoidance is a
  payer-side invariant. This also removes the zero-root sentinel collision at
  its source, since nothing retires a root any more.
- Per-stream self-anchoring: each stream carries its own
  (anchor voucher, chain_root, verified, tip), and the payer sends the new-root
  voucher on every active stream at rollover. QUIC in-stream ordering then keeps
  a sibling stream'\''s old-chain preimages valid, so a rollover cannot strand it.
  The lane claim is a maximum over per-stream extensions, never a sum.
- The node MUST reject a voucher whose chunk_price is not its quoted rate_per_mb
  (new ChunkPriceMismatch reason); a sealed voucher carries chunk_price = 0.
- The rollover fold is amount_old + verified_index * chunk_price on both axes,
  covering early rolls, and a sweep redeems the strongest claim held rather than
  the latest signed voucher.

Corrections: an at-or-below-watermark voucher is already-satisfied, not a
rejection (handler behaviour since #1699); the persisted lane record keeps the
tip preimage so the frontier survives a restart; owed and M include the chain
frontier; the credit window is lane-collective; claimed/claimedBytes are bounded
by check rather than by construction; ADR 037 and ADR 011 reconciled to the
chunk meter; ClientMessage lists all six variants; voucher width stated in words.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@yigitdot

Copy link
Copy Markdown
Contributor Author

All 30 dispositions applied in 99b86c55. Diff is now 14 files — adr/037-regional-proxy-warming.md and adr/011-content-takedown.md joined it (see the note at the bottom).

Design changes

B1 — ChainRootReuse deleted. Removed as a wire reason, and with it the node-side MUST, the rejection-table row, the "backstop" paragraph, and the Consequences bullet (which was S1's fix too). § One chain per lane now carries two payer-side rules and an explicit statement of why there is no node-side rule: reuse pays the node and costs the payer, so a rejection protects nobody who would run it, and it would need an unbounded never-expiring root set. With nothing retiring a root, the zero-root sentinel collides with nothing — no exemption clause needed.

B3 — per-stream self-anchoring. Each stream now holds its own (anchor voucher, chain_root, verified, tip), seeded verified = 0, tip = chain_root (which also closes S2/I6b). At rollover the payer sends the new-root voucher on every active stream. QUIC in-stream ordering then reads each stream's old-chain preimages against its own old root before its own roll voucher lands, so a fast stream adopting R₂ cannot strand a sibling finishing R₁.

Two things I had to pin down for the rule to be complete, flagging them since they are mine rather than yours:

  • The lane claim is a maximum, not a sum — over the highest signed amount and each stream's anchor amount + verified × chunk_price. Summing would double-count, because the roll voucher already folds the retired chain into its own amount.
  • Per-stream anchors are in-memory only. A restart drops the streams, so the durable record keeps the strongest claim's chain state.

B4 — ChunkPriceMismatch. Node MUST require chunk_price == its quoted rate_per_mb on metering vouchers, with your M4 carve-out (sealed voucher ⇒ chunk_price == 0).

B5 — fold and sweep. Fold is amount_old + verified_index × chunk_price on both axes, stated for early rolls too, with both directions called out: folding less discards proved value, folding more signs for bytes not received. Sweep is "the strongest claim held".

B2 — you were right and I was wrong. I read the primitive at crates/incentive/src/lane.rs:311 and never traced the handler. crates/node/src/handlers/client/voucher.rs:303-317 catches PoolError::AmountRegression and returns Ok with the watermark unchanged; the tolerance landed in #1699 (ea12f8c2). Fixed as wording only. I also reconciled ADR 005's AmountRegression enum comment and retry row, which still described it as a live rejection — otherwise 003 and 005 would have contradicted each other.

Everything else

I1–I6, I8–I11 and M1–M9 applied as ruled. S1–S5 done, including the STE rewrites ("footgun", "the walk is noise", "255 buys", "three things at once", "gives away", the off-by-one idiom) and the 52-word sentence split.

make check-refs and make check-book-list both green; grep -rn "ChainRootReuse" adr/ and the five-field-tuple grep both return nothing; "voucher interval" survives only as the deliberate historical back-reference in ADR 003.

Two things for you

1. M1 — the 8-word target does not reconcile. LaneVoucher is 5 words today and PayWord adds four one-word fields (chainRoot, chunkPrice, chainIndex, preimage) — that is 9 words / 288 B, not 8. Reaching 8 needs two fields packed into a single word (chunkPrice as uint64 alongside the uint8 chainIndex is the obvious candidate), which is an ABI design change I did not want to make on your behalf. I have written the passage in words as asked, stated 9, and left contracts/src/PaymentPool.sol:420-421 owning the 160-vs-288 static-vs-dynamic comparison. Say the word if you want the packing and I will do it.

2. M6 and I3 were described as already applied, and were not. The response says ADR 011 is "applied in this PR" and ADR 037 "is reconciled in this PR", but neither file was in the diff and no commits had landed on the branch. Both are in now — ADR 011:460 terminates at the next chunk boundary after the preimage is revealed, and ADR 037's five statements are reconciled including the normative credit_max parameter row and the serve-loop note (which now says the per-iteration proof becomes a ChunkPreimage).

Deferred code work — noted, not filed

Per your split, these stay out of this ADR PR. Recording them here rather than opening issues; they belong against the existing PayWord implementation issue #1752:

  1. I7 — rename the BLAKE3-leaf CHUNK_BYTES so payment keeps the name: crates/cache/src/fill_session.rs:74, crates/client-pull/src/driver.rs:115, crates/node/src/node_origin/pull_leg.rs:75.
  2. I11 — harden redeemMany so a per-voucher arithmetic fault skips rather than reverting the batch. The ADR now asserts the resolution/width invariant; the contract does not yet enforce it.
  3. M3 — soft-floor: clamp byte-credit instead of reverting sub-floor vouchers.

🤖 Generated with Claude Code

…er (#1670)

Closes the M1 gap raised in review: LaneVoucher was heading for 9 words / 288 B,
against a target of 8 / 256 B.

chunkPrice needs 64 bits and chainIndex needs 8, so both ride one packed
`chainMeter` word: reserved 23 bytes (MUST be zero) | chunkPrice (u64) |
chainIndex (u8), big-endian. Redemption splits it with a shift and a mask, and
rejects a non-zero reserved span rather than masking it, so the word stays
extendable. The struct stays static — uint256 is fixed-width — so an array of
LaneVoucher still carries no offsets, length words or padding.

Adds a per-word struct table and a byte-layout diagram, and states that the
EIP-712 typehash keeps `uint256 chunkPrice`: the contract decodes the packed
word and widens it back before rebuilding the struct hash, so no signer sees the
packing and no digest changes. chainIndex is a redemption parameter, not a
signed field, so packing it alongside is signature-neutral.

Consequence worth noting: extracting chainIndex as a uint8 caps it at 255
on-chain the same way the wire byte does, so the chainIndex <= MAX_CHAIN_LENGTH
require is now unreachable at both layers and is replaced by the reserved-span
check. Flags the 255-vs-256 boundary explicitly in both ADRs — u8 reaches 255,
index 0 is settlement, so releasable indices are 1..=255 and 256 would need an
index-1 offset encoding.

Docs only.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@yigitdot

Copy link
Copy Markdown
Contributor Author

M1 closed in 0a69aaec — the voucher is now 8 words / 256 B, not 9.

chunkPrice needs 64 bits and chainIndex needs 8, so both ride one packed chainMeter word:

chainMeter (32 bytes, big-endian)

 byte  0                     22 23            30 31
      +------------------------+----------------+--+
      |  reserved — MUST be 0  |   chunkPrice   |ci|
      +------------------------+----------------+--+
         23 bytes                 8 bytes (u64)  1 byte (u8)

chunkPrice = uint64(chainMeter >> 8)
chainIndex = uint8(chainMeter & 0xff)

The struct stays static — uint256 is fixed-width, so an array of LaneVoucher still carries no per-element offsets, no length word and no padding. ADR 003 § Voucher signatures are compact now has a per-word struct table and that byte diagram.

No signature changes. chainIndex is a redemption parameter, not a signed field, so packing it alongside chunkPrice is signature-neutral. The EIP-712 typehash keeps uint256 chunkPrice; the contract decodes the packed word and widens it back before rebuilding the struct hash. Signers never see the packed representation and no digest changes, so no client signing code moves.

The reserved 23 bytes MUST be zero and redemption MUST reject a non-zero span rather than masking it — one comparison, and it keeps the word extendable without any voucher signed today becoming reinterpretable.

One consequence worth flagging

Extracting chainIndex as a uint8 caps it at 255 on-chain the same way the wire byte does. So the chainIndex <= MAX_CHAIN_LENGTH require is now unreachable at both layers — I have replaced it with the reserved-span check rather than leave a second dead check in the spec (I2 removed the first one). The bound is now purely a type property, end to end.

That also makes the index one representation from wire to calldata: the u8 on the wire is the low byte of chainMeter, with no offset on send and no conversion on receipt.

255 vs 256, stated explicitly

Flagged in both ADRs as you asked. A u8 reaches 255 and index 0 is reserved for redeem-time settlement, so the releasable range is 1..=255 and one chain meters at most 255 chunks / 255 MiB. A 256-chunk chain is not representable without an index - 1 offset encoding — one extra chunk per chain in exchange for reintroducing exactly the off-by-one the byte-is-the-index rule removes. The ADR takes the shorter chain.

Docs only; make check-refs and make check-book-list green.

🤖 Generated with Claude Code

@alpergundogdu

Copy link
Copy Markdown
Contributor

On the packing — agreed, it's sound: chainIndex is a redemption parameter, not signed, so riding it in the low byte of chainMeter alongside uint64 chunkPrice is signature-neutral and the struct stays static. No objection.

On 255 vs 256 — we don't actually disagree on the mechanism, only on how the passage frames it, and the framing overstates a tradeoff that isn't there.

The mechanism, to be explicit:

  • chain_root = keccak²⁵⁵(s) is index 0.
  • Indices 1..=255 are the releasable preimages: index k reveals keccak²⁵⁵⁻ᵏ(s), and redemption checks keccak^k(preimage) == chain_root.
  • So the index space is 0..=255 — 256 values, exactly one u8 — where index 0 is the root (zero chunks, settlement) and 1..=255 each meter a chunk.

So "256" counts index slots and "255" counts payable chunks. Both are right; they count different things. The u8 domain 0..=255 is not a bound anyone chose — it is the index space. The root sits at index 0 by construction, and the contract walks keccak chainIndex times from a uint8, so there is no other way to write it.

The part worth cutting is the closing tradeoff at 003:154 — "a 256-chunk chain would need an index − 1 offset encoding. One extra chunk per chain is not worth reintroducing that hazard." There was never a 256-payable-chunk design to give up; index 0 is the root, full stop. Framing 255 as a concession implies a cost that doesn't exist. Suggest rewording it to state the fact plainly: the index space is 0..=255, index 0 is the root, so a chain meters up to 255 chunks — inherent, not a tradeoff. Same for the "255 vs 256" section in the packing comment above.

Everything else in both comments looks right to me — including the two corollaries you flagged as yours (lane claim as a max not a sum, in-memory-only anchors); both are correct and necessary under the per-stream fix.

@alpergundogdu

Copy link
Copy Markdown
Contributor

One correction to my own wording above: I wrote "meters up to 255 chunks," which quietly implies index 0 pays nothing. It doesn't.

Index 0 is payable. It resolves to cumulative — the voucher's base amount — which the contract already states: "a real-root voucher at index 0 … resolves to exactly cumulative" (003:254). So the voucher settles on its own, independent of the chain, and that base can itself fold in a whole retired chain's worth of chunks via the rollover fold.

So the precise framing is:

  • 255 = the chain's incremental range (indices 1..=255, each adding chunk_price over the anchor).
  • The base voucher is payable regardless — index 0 pays amount.

"255 payable chunks" conflates the two. It's 255 incremental chain steps over an already-payable base voucher. Worth saying it that way in the passage so index 0 doesn't read as a dead slot.

yigitdot and others added 2 commits August 19, 2026 16:23
…radeoff (#1670)

256 and 255 count different things and both are right: the u8 index space is
0..=255 — 256 slots, exactly one byte — and index 0 is chain_root itself, which
meters no chunk and never travels the wire. That leaves 1..=255 as the
releasable preimages, so a chain meters 255 payable chunks.

The previous wording presented 255 as a concession, claiming a 256-chunk chain
would need an index-1 offset encoding not worth the hazard. There was never a
256-payable-chunk design to give up: the root occupies index 0 by construction.
Framing it as a tradeoff implied a cost that does not exist.

No mechanism changes. MAX_CHAIN_LENGTH stays 255 (the highest index), the wire
index stays a direct u8, the packed chainMeter word keeps its 23 reserved bytes
and uint8 low byte, and LaneVoucher stays 8 words / 256 B.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…hunk count (#1670)

Follow-up to 01abd9e, which still implied index 0 was a dead slot.

Index 0 names chain_root and resolves to the voucher's own cumulative amount,
so the base voucher is payable with no chain at all — and that base may already
fold in a whole retired chain through the rollover fold. What index 0 does not
do is add an increment, which is why it never travels the wire: a reveal there
would prove nothing the voucher does not already carry.

So the 256 slots are one payable base plus 255 incremental steps over it, not
256 minus a wasted one. "255 payable chunks" conflated the two.

No mechanism changes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@yigitdot

Copy link
Copy Markdown
Contributor Author

Both corrections applied — 01abd9e3 then 0284e744. You were right twice, and the second one caught wording I had just committed.

On the framing. Agreed there was never a tradeoff to describe. The passage now states the mechanism plainly: the u8 domain 0..=255 is the index space — 256 slots — and the root sits at index 0 by construction, not by anything chosen here. The "a 256-chunk chain would need an index − 1 offset encoding … not worth reintroducing that hazard" sentence is gone from ADR 003, and the matching "the bound is 255, NOT 256" text is gone from the MAX_CHAIN_LENGTH doc comment and the one-byte-end-to-end paragraph in ADR 005.

On index 0 being payable. This is the one I would have shipped wrong. My first pass replaced "255 vs 256" with "256 index slots yield 255 payable chunks — the root occupies one slot" — which is exactly the dead-slot reading you flagged. Corrected to:

Index 0 is not a dead slot. It is the settlement case, and it pays: it resolves to cumulative, the amount the voucher already carries. What it does not do is add an increment, which is why it never travels the wire — a reveal at index 0 would prove nothing the voucher does not already say. So the 256 slots are one payable base plus 255 incremental steps over it, not 256 minus a wasted one.

§ Chain length and rollover now opens on the same distinction — index 0 resolves to the voucher's own amount, and that base may already fold in a whole retired chain through the rollover fold, while 1..=255 are the chain's incremental range at one chunk_price each. MAX_CHAIN_LENGTH is described as the highest index, and a chain "adds up to 255 MiB over its anchor" rather than "meters 255 MiB". ADR 005's constant doc carries the same wording: 256 slots = one payable base + 255 increments.

Nothing mechanical moved in either commit: MAX_CHAIN_LENGTH is still 255, the wire index is still a direct u8, chainMeter keeps its 23 reserved bytes and uint8 low byte, and LaneVoucher is still 8 words / 256 B.

Noted that the packing is agreed and that the two corollaries stand — lane claim as a max rather than a sum, and per-stream anchors being in-memory only with the durable record keeping the strongest claim's chain state.

make check-refs and make check-book-list green.

🤖 Generated with Claude Code

alpergundogdu added a commit that referenced this pull request Aug 19, 2026
…ad of reverting (#1753)

* feat(payments): soft delivery-rate floor — clamp credited bytes instead of reverting

The deliveryFloor's purpose is to stop cheap bytes from inflating the served-bytes
metric (the ADR 036 governance vote weight), not to police payment. Replace the hard
`RateFloorViolation` revert in `PaymentPool` redemption with a clamp: a sub-floor
voucher settles its full `cumulative` USDC and credits only
`min(bytesDelivered, cumulative * BYTES_PER_MB / deliveryFloor)` bytes toward the
served-bytes counter that feeds `DecdnGovernor` vote weight.

This removes the batch-poisoning failure mode where one sub-floor voucher reverted a
whole `redeemMany` (every pool and lane). The realistic trigger is a governance
floor-raise landing on a voucher a node already served and accepted in good faith.
Credit stays bounded by real, floor-priced routed USDC, so cheap bytes still cannot
buy vote weight; `cumulative` needs no extra bound because credit is paid-proportional.

Contract:
- PaymentPool: clamp in `_applyVoucher`; delete `RateFloorViolation`; the redeemMany
  skip-vs-revert taxonomy now reverts only on a structural error (bad signature /
  closed pool). Tests rewritten to soft-floor semantics (+ batch-no-poison,
  after-floor-raise, fuzz). Gas snapshot regenerated.

Off-chain (the seller no longer hard-rejects either):
- Remove the acceptance-time floor check in the client voucher handler; the
  advertised-rate check still protects per-delta revenue. `rate_bounds` now only
  clamps the node's own quote up to the floor before signing.
- Remove the now-unproducible `RateFloorRaised` wire reason end to end: the enum
  variant, its buyer-side cache-miss retry classifier (collapses to `PoolExhausted`),
  the metric, the public-API snapshot, and its ADR 005 definition.

ADRs: 003 (§Rate-floor enforcement rewrite + call sites), 036 (threat-model
dependency), 005 (VoucherRejectReason). ADR 016 unchanged — the contract surface
(routeSettlement pipe, constructor args) is unchanged and it never enumerated the error.

Contract-side follow-up to the ADR-only PR #1751.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(node): drop dead handler setup from two verify_voucher unit tests

`verify_voucher` is now an associated fn, so `stale_voucher_is_benign_*` and
`divergent_voucher_at_equal_amount_*` no longer need the `handler_over_store`
fixture (they sign with a local EIP-712 domain and `verify_voucher` skips the
signature). Remove the unused handler/store/metrics setup and downgrade both to
sync `#[test]` — no `.await` remains.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
…h-chain-meter

# Conflicts:
#	adr/003-payments.md
#	adr/005-protocol.md
@alpergundogdu
alpergundogdu merged commit 67a3bfd into main Aug 19, 2026
25 checks passed
@alpergundogdu
alpergundogdu deleted the docs/1670-payword-hash-chain-meter branch August 19, 2026 14:56
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.

docs(adr): land just PayWord (hash-chained per-MB meter) into ADR 003

2 participants