Skip to content

docs(adr): hash-chain the per-MB meter, decouple voucher persistence - #1652

Closed
thiras wants to merge 7 commits into
mainfrom
claude/payword-hash-chain-meter
Closed

thiras wants to merge 7 commits into
mainfrom
claude/payword-hash-chain-meter

Conversation

@thiras

@thiras thiras commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Rebased onto main now that #1650 has merged. ADR-only — no Rust or Solidity. Implementation follows as separate issues.

Why

Per-MB metering is the product, so the goal was not to coarsen the meter but to make the per-interval claim free. The cost sits in one requirement in ADR 003 § Off-chain voucher state persistence: the node must durably commit the lane watermark before sending VoucherAck. That is ~3.18 ms/voucher and caps a lane at ~313 MiB/s at the 1 MB wire cadence (measured in #1490). Everything above it exists to hide it:

fsync-before-ack  ->  ack costs 3.18 ms
                  ->  credit window (#1477) to get the ack off the critical path
                  ->  sizing  credit_window >= throughput * (RTT + commit_interval)
                  ->  group commit (#1490): BufferedVoucherReader, sync parse_frame,
                      staged-candidate/swap, whole-batch RetryLater, collected_any gating
                  ->  window width then forces interval negotiation and lane arbitration

Two independent, stackable decisions dismantle it from the base.

Decision 1 — persistence is best-effort, the chain is the floor

Accept on verification and persist asynchronously, flushing on a value bound so the post-crash replay surface is at most one credit window — exactly the credit a node already extends, knowingly, every time it serves. An unknown lane seeds its floor from watermark[poolId][signer][provider] with one eth_call; the lane floor is max(local, chain). A persist failure becomes a metric, not a wire rejection.

Seeding is lazy and per-lane, which is what makes ADR 016's "a pool names no provider, so it is not node-enumerable" a non-issue rather than a blocker.

The win is decoupling, not fsync count: group commit already amortised the writes. What cost was that the commit sat on the acknowledgement path.

Decision 2 — the voucher becomes a chain-epoch anchor

PayWord (Rivest–Shamir, 1996) on each (poolId, signer, provider) lane. One signed Voucher opens an epoch (default 1024 × 64 KiB) carrying chainRoot / chainLength / chunkBytes / chunkPrice. Each chunk is paid by a bare 32-byte Preimage.

Before After
Per-interval payer cost secp256k1 sign 0 (precomputed)
Per-interval node cost ecrecover + fsync one keccak
Round trips per interval 1 (VoucherAck) 0 — preimages are unidirectional
Signatures per GiB 256 16
Meter ticks per GiB 256 16,384

The meter gets 64× finer, not coarser, while signatures drop 16×.

chunkBytes is a lane property advertised by the node, not a per-stream negotiation. That is what lets ADR 003 § Concurrent Streams rules 1 and 3 be deleted: they were specified but never implemented (no lane-wide minimum is computed anywhere, and the credit-window pause is per-stream).

Measured cost, not estimated

Both halves were measured against this repo rather than guessed.

CPU per GiB, one lane (release build, real decdn-incentive signing path):

Old (4 MiB voucher) New (64 KiB preimage)
Client 21.9 ms 7.1 ms
Node, accept path 145.9 ms 9.3 ms
— of which fsync 89.0 ms 0 (moved off-path)

Client 3.1× cheaper, node accept path 15.7× cheaper. The client's win is modest because the chain adds 16,384 hashes/GiB it never had — it trades signatures for hashing and comes out ahead, not for free.

Gas (Foundry, solc 0.8.28, optimizer 200 runs, measured on the existing PaymentChannel harness):

Gas
Redemption today, cold lane 277,517
Redemption today, warm lane 113,618
Walk of 1024, scratch-space assembly (~97/step) 99,390
Walk of 1024, naive abi.encodePacked (~189/step) 193,306
Walk of 256, assembly 24,886

A full-depth walk adds ~99k gas to a ~114k warm redemption — an 87% increase in the worst case, not noise. So this design moves cost from off-chain to on-chain: the per-chunk path loses a signature, an ack and an fsync; redemption gets up to 87% more expensive. That holds because redemption is rare and one call settles every prior epoch. MAX_CHAIN_LENGTH prices it, and the ADR carries a MUST to hash from scratch space in assembly — the naive form costs ~1.95× more for the same result.

The naive row was re-measured after the rebase and corrected from 239,580 (~224/step) to 193,306 (~189/step); abi.encode and bytes.concat measure identically, so the saving comes from staying in scratch space rather than from the spelling. The assembly rows reproduce within 1%, so the 87% figure is unchanged.

Two correctness rules added during review

Chains MUST be independent per lane. A preimage carries no payee — it is a bearer token for its chain. A signer that opens two lanes on one chainRoot lets either node spend the other's preimages, at the signer's expense, bounded only by its cap. No node can detect it, since each sees only its own lane. The ADR originally called this reuse "harmless"; it voids the zero-exposure property. Rivest and Shamir specify a chain per vendor in the 1996 paper — this was a regression against the source scheme, not a novel edge case.

A client that lost its state can resume. The claim that justified deleting the watermark self-heal — "a signer derives its own chain index from the preimages it has released" — assumed the signer still has its state. A crashed client knows neither its epoch nor its index. ADR 003 § Client Restart and Lane Resume specifies deriving the chain seed as KDF(signer_secret, pool_id, provider, epoch_base, chunk_bytes, chunk_price, chain_length) — no per-lane secret is persisted at all — plus a self-authenticating position exchange.

Reconciled with #1650 during the rebase

#1650 landed three changes after this branch forked, so the chain design is layered on top of them rather than reverting them:

  • The voucher carries no nonce and no token. Both are gone from the field list, the EIP-712 typehash and digest, the wire format and the glossary. § Voucher ordering is rewritten: epochs are ordered by their cumulative base, and within an epoch by the self-proving chain index. WrongToken is dropped from VoucherRejectReason (nine mirrored variants, not ten).
  • LanePosition no longer names the epoch by a counter. With no nonce, the node echoes back the signer's own signed voucher: LanePosition { voucher, chain_index, preimage }. Everything the seed derivation needs is inside it, and the "no signature gate" property is unaffected — a preimage still proves its own index. Keying the KDF on the epoch's signed terms also closes a hole a bare cumulative base would open: two epochs sharing a base but repriced would otherwise derive the same chain.
  • The refundable floor M is kept over this branch's older "redemption credit window", including in the chunk-risk table, the partial-redemption paragraph, the Negative consequences and the glossary.

Wire changes (pre-launch cut, no shim)

  • ClientMessage::VoucherAck removed; Preimage([u8; 32]) takes its slot (discriminant 4, renumbering the tail)
  • voucher_interval_mb removed from StreamRequest/StreamResponse; node-advertised chunk_bytes replaces it
  • WatermarkBundle replaced by LanePosition { voucher, chain_index, preimage }, carried on StaleEpoch. It needs no signature gates — the old bundle needed two, because a bare cumulative number carries no proof of itself, whereas claiming index k requires exhibiting preimage k, which a node can only hold if the signer released it
  • VoucherRejectReason: drops AmountRegression, BytesRegression, RetryLater; adds BadChainParams, StaleEpoch, BadPreimage, ChainExhausted

Downstream claims corrected

ADR 024 and ADR 012 both motivated session keys with "at the default 1 MB voucher cadence, a 100 MB download needs 100 EIP-712 signatures." Under the chain that is about two, so the premise no longer holds. Rewritten to rest on unattended operation instead: nodes still sign a slash_sig per response, and payer signatures scale with lanes rather than bytes with nobody present to confirm them. The session-key case survives; the arithmetic behind it did not.

Files

003 (payment model, chunk cadence, credit window, client restart, redemption, persistence, attack vectors, EIP-712 type) · 005 (wire) · 013 (ClientMessage enum, frozen fields) · 016 (redeem signature, watermark read row) · 012 014 024 036 037 038 039 appendix-observability appendix-operator-key-rotation architecture glossary README CHANGELOG.

New observability rows (decdn_preimages_received_total, decdn_preimages_rejected_total, decdn_lane_seed_from_chain_total, decdn_lane_flush_lag_bytes) are all Status planned, since nothing emits them yet.

README deliberately does not describe preimages: VoucherAck is still the shipped wire and no preimage code exists, so its payment prose is phrased to be true of both the current implementation and the ADR.

Verification

  • pre-commit on every commit: markdownlint, adr reference hygiene (links, anchors, section spacing) and adr book list in sync all pass
  • Gas figures re-measured after the rebase with a throwaway Foundry probe on the real setup; probe deleted, tree clean
  • Cross-checked by hand: the VoucherRejectReason set in 005 matches the rejection table in 003 and the mirror obligation; no nonce, token, WrongToken, WatermarkBundle, RetryLater or epoch_nonce references survive outside adr/_history/
  • CI now runs — the branch is based on main, so ci.yml triggers

Known gap (pre-existing, worth a follow-up)

ADR 003's detailed redeem behavior block still spells the old signature redeem(poolId, signer, provider, cumulative, bytesDelivered, voucherSig, capability), while the summary, the function table and ADR 016 use redeem(voucher, sig, chainIndex, preimage, cap). That block was never updated when the chain landed.

Follow-up issues to file

  1. D1 node — relax the store durability contract; delete collect_voucher_batch, BufferedVoucherReader, parse_frame, staged-candidate/swap, voucher_commit_interval_ms, RetryLater; add lazy chain-seeded lane hydration
  2. D2 contract — PaymentPool chain fields + walk verification (assembly, scratch space) + anchor typehash; regenerate .gas-snapshot (a gas change fails solidity build+test and is invisible to local forge test)
  3. D2 wire — crates/protocol message set, VARIANT_COUNT, public-api snapshot regen
  4. D2 client — chain construction, KDF seed derivation, epoch rollover, LanePosition resume; collapse ledger.rs's outstanding/resolve_ack/resolve_reject FIFO and the committed()-vs-settlement() hazard into one frontier
  5. D2 bindings — hand-written sol! in crates/incentive/src/payment_channel.rs and crates/e2e/src/bindings.rs; ABI drift here is caught only by the anvil e2e job

🤖 Generated with Claude Code

Copilot AI lite review requested due to automatic review settings August 10, 2026 21:21
@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: 4597b90d-930f-4706-9f40-f08b8782d940

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

Comment @coderabbitai help to get the list of available commands.

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

Updates the deCDN design documentation to switch per-MB metering to a PayWord-style hash-chain model (voucher opens an epoch; preimages pay per chunk) and to decouple off-chain lane persistence from the payment acceptance path (best-effort async persistence with lazy on-chain seeding as the floor). This is an ADR/documentation-only PR intended to specify a single pre-launch wire cut with no shims.

Changes:

  • Specify hash-chain per-chunk payments: remove VoucherAck, introduce Preimage([u8; 32]), replace voucher_interval_mb with node-advertised chunk_bytes, and revise rejection reasons and redeem signature.
  • Redefine off-chain lane state persistence as best-effort with a value-bounded flush policy and lazy per-lane seeding from on-chain watermark.
  • Sweep downstream docs (architecture, glossary, client/AA rationale, observability appendix, related ADRs) to match the new payment and wire model.

Reviewed changes

Copilot reviewed 17 out of 17 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
README.md Updates top-level project description and crate inventory to reference hash-chain payments.
CHANGELOG.md Records the planned (design-only) wire-breaking shift to preimage payments and best-effort persistence.
adr/003-payments.md Core payment model rewrite: epochs + preimages, bounded chain walk, best-effort persistence + chain floor seeding.
adr/005-protocol.md Wire protocol updates: Preimage replaces VoucherAck, chunk_bytes replaces voucher_interval_mb, updated reject reasons and semantics.
adr/012-client.md Updates client cadence and session-key justification to reflect epoch signatures vs per-interval signing.
adr/013-schema-evolution.md Documents the pre-launch exception for removing/replacing a mid-enum variant (VoucherAck → Preimage) and field removals.
adr/014-on-chain-verification.md Updates the StreamResponse field listing (chunk_bytes?).
adr/016-contract-interactions.md Updates PaymentPool.redeem signature and adds lane watermark read usage for lazy seeding.
adr/024-account-abstraction.md Reframes AA/session-key motivation around unattended signing and lane fan-out rather than per-MB signature volume.
adr/036-served-bytes-voting-weight.md Updates rate-floor discussion to account for resolved-claim arithmetic under epochs + chain index.
adr/037-regional-proxy-warming.md Updates payment pacing language from vouchers/acks to preimages/epochs and chunk cadence.
adr/038-bao-verified-range-streaming.md Updates envelope/payment message names and framing language to chunk_bytes + Preimage.
adr/039-multi-source-parallel-fetch.md Updates “self-enforcing delivery” description to preimage-based pacing.
adr/architecture.md Updates architecture narrative to reflect preimage payments and epoch vouchers; updates reading-order payment chapter summary.
adr/glossary.md Adds/updates payment glossary terms: voucher epoch, preimage, credit window (new semantics).
adr/appendix-observability.md Adds planned metrics for preimages and lane persistence/seeding; adjusts existing voucher metric semantics.
adr/appendix-operator-key-rotation.md Updates hot-signing rationale wording to match new payment signature cadence assumptions.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread README.md Resolved
Comment thread adr/glossary.md Resolved
Comment thread adr/appendix-observability.md Resolved
Comment thread README.md Resolved
thiras added a commit that referenced this pull request Aug 10, 2026
Addresses review on #1652.

The flush-bound units comment surfaced a real inconsistency in ADR 003, not
just in the metric description. `credit_window` is a byte quantity, but the
persistence rule bounded "un-flushed accepted **value**" by it — comparing USDC
against bytes — while the next sentence concluded the replay surface is "one
credit window of re-delivered bytes", which only holds on the bytes reading.
The bound is now stated in bytes, and `decdn_lane_flush_lag_bytes` matches its
own `_bytes` suffix.

Preimage verification cost is now stated precisely in both ADR 005 and the
glossary: it costs as many hashes as the index advances (one in steady state),
rather than an unconditional "one hash" that the first-of-epoch case
contradicted. Glossary also calls the preimage a per-chunk instrument settling
per-MB-priced delivery, rather than a "per-MB" one.

README no longer claims shipped behaviour that does not exist: `VoucherAck` is
still the wire (crates/protocol/src/client.rs:103) and no preimage-chain code
exists. The crate line drops "+ preimage chains", and the payment prose is
stated at a level true of both the current wire and the ADR, so it overstates
nothing while still not contradicting ADR 003.

Verified: make -C adr check-refs (1685 anchors resolve);
`cargo nextest run -p decdn-node -E 'test(/metric/)'` — 39 passed.

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

github-actions Bot commented Aug 10, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 80.88% (was 80.88%, ● 0.00%) — 60163/74382 lines

No Rust files changed in this PR.

History
Commit Total Δ vs base
2372cc2 80.89% ▲ +0.01%
eb32038 80.90% ▲ +0.02%
33baaa8 80.88% ● 0.00%
7656706 80.89% ▲ +0.01%
0375b00 (HEAD) 80.88% ● 0.00%

@alpergundogdu
alpergundogdu marked this pull request as draft August 11, 2026 10:43
Base automatically changed from claude/practical-lamport-45bbfb to main August 11, 2026 11:19
thiras and others added 6 commits August 11, 2026 19:06
Two stacked ADR decisions that keep per-MB metering while removing the
machinery built to make a signed per-interval voucher fast.

The fsync-before-VoucherAck rule in ADR 003 put a ~3.18 ms durable commit on
the acknowledgement path. That forced the credit window to cover
`RTT + commit_interval`, which forced group-commit batching, which forced
voucher-interval negotiation and the concurrent-stream lane-arbitration rules.
Both decisions dismantle that tower from the base.

1. Persistence is best-effort; the chain is the floor.
   Accept on verification and persist asynchronously, flushing on a value bound
   so the post-crash replay surface is at most one credit window — the credit a
   node already extends by serving. An unknown lane seeds its floor from
   `watermark[poolId][signer][provider]` with one eth_call; the lane floor is
   `max(local, chain)`. Seeding is lazy and per-lane, so a pool naming no
   provider never needs to be node-enumerable. A persist failure becomes a
   metric, not a wire rejection.

2. The voucher becomes a chain-epoch anchor; preimages meter the chunks.
   PayWord on each lane: one signed Voucher opens an epoch (default 1024 x
   64 KiB) carrying chainRoot/chainLength/chunkBytes/chunkPrice, and each chunk
   is paid by a bare 32-byte Preimage — one keccak, no signature, no ack, no
   round trip, nothing to persist. `redeem` walks at most MAX_CHAIN_LENGTH
   (1024) hashes and the contract stores no chain state, so the pool, per-signer
   cap, sharded register, min(delta, remaining) and FeeRouter routing are
   untouched. The meter gets 64x finer rather than coarser, and the withholding
   bound tightens with it.

Wire (pre-launch cut, no shim): VoucherAck removed and Preimage takes its slot;
voucher_interval_mb replaced by node-advertised chunk_bytes; WatermarkBundle and
the VoucherRejected bundle field removed, since a signer derives its own chain
index; VoucherRejectReason drops StaleNonce/AmountRegression/BytesRegression/
RetryLater and adds BadChainParams/StaleEpoch/BadPreimage/ChainExhausted.

ADR 003 Concurrent Streams rules 1 and 3 are deleted rather than deferred —
they were specified but never implemented, and a lane-wide chunk size makes
them unnecessary.

Corrects two downstream claims the chain invalidates: ADR 024 and ADR 012 both
motivated session keys with "a 100 MB download needs 100 signatures", which is
now about two. The session-key case is rewritten to rest on unattended
operation (nodes sign slash_sig per response; payer signatures scale with lanes
and have nobody to confirm them), which the chain does not weaken.

Stacked on #1650. Docs only — implementation follows as separate issues.

Verified: make -C adr check-refs (1685 anchors resolve), check-book-list,
adr-ref-hygiene + adr-book-list + trailing-whitespace + end-of-file-fixer
pre-commit hooks, and `cargo nextest run -p decdn-node -E 'test(/metric/)'`
(39 passed) for the appendix-observability registry check. markdownlint fails
only on .github/workflows/issue-triage.md, identical before this branch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Addresses review on #1652.

The flush-bound units comment surfaced a real inconsistency in ADR 003, not
just in the metric description. `credit_window` is a byte quantity, but the
persistence rule bounded "un-flushed accepted **value**" by it — comparing USDC
against bytes — while the next sentence concluded the replay surface is "one
credit window of re-delivered bytes", which only holds on the bytes reading.
The bound is now stated in bytes, and `decdn_lane_flush_lag_bytes` matches its
own `_bytes` suffix.

Preimage verification cost is now stated precisely in both ADR 005 and the
glossary: it costs as many hashes as the index advances (one in steady state),
rather than an unconditional "one hash" that the first-of-epoch case
contradicted. Glossary also calls the preimage a per-chunk instrument settling
per-MB-priced delivery, rather than a "per-MB" one.

README no longer claims shipped behaviour that does not exist: `VoucherAck` is
still the wire (crates/protocol/src/client.rs:103) and no preimage-chain code
exists. The crate line drops "+ preimage chains", and the payment prose is
stated at a level true of both the current wire and the ADR, so it overstates
nothing while still not contradicting ADR 003.

Verified: make -C adr check-refs (1685 anchors resolve);
`cargo nextest run -p decdn-node -E 'test(/metric/)'` — 39 passed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The data-withholding attack vector still described the retired ack model ("the
last acknowledged voucher") and did not answer the question the chain epoch
raises: the node now holds a signed voucher before it delivers anything.

It grants no new claim. The voucher's `cumulative` is the epoch base — value
the lane already earned — and everything above it needs a preimage, which the
signer releases only for a received, hash-verified chunk. A node that delivers
nothing redeems at `chainIndex = 0` and claims exactly that base: zero on a
fresh lane (reverts `NothingToRedeem`), and on an established lane only what
the previous epoch's preimages already covered.

Payer exposure stays at zero despite signing first; node exposure stays at one
chunk.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The chain-root reuse attack vector only reasoned about the client trying to
cheat nodes, concluded "not possible", and called reuse "equally useless to the
attacker". That is right for that direction and wrong about the one that
matters.

A preimage carries no payee — it is a bearer token for its chain. So a signer
that opens two lanes on the same `chainRoot` makes every preimage it releases
to one node a valid claim on the other's lane. Node A hands preimage k to node
B, and B redeems at index k having delivered a fraction of it. The signer pays
for chunks it never received, bounded only by `chainLength × chunkPrice` per
extra lane and ultimately by its own cap. No node can detect this: each sees
only its own lane and cannot know another voucher shares its root.

That is the zero-exposure property being given away, and the ADR described it
as harmless.

Adds the missing requirement — a signer MUST derive an independent chain per
`(provider, epoch)` from a fresh seed, and chains for two lanes MUST NOT be
derivable from each other — in both the Chunk Cadence section and the attack
vector. Qualifies the "payer's exposure stays at zero" claim in Credit Window,
which silently depended on it. Corrects the EIP-712 section, which credited the
signed `provider` field with confining preimages; it confines the voucher, and
only per-lane chain independence confines the preimages.

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

The ADR asserted the redemption chain walk costs "roughly 60k gas in the worst
case" and framed that as negligible against a whole-epoch settlement. Both
halves were wrong.

Measured on this repo's Foundry setup (solc 0.8.28, optimizer, 200 runs), by
instrumenting the existing PaymentChannel harness:

  redemption today, cold lane                     277,517
  redemption today, warm lane                     113,618
  walk of 1024, scratch-space assembly (~97/step)  99,390
  walk of 1024, naive abi.encodePacked (~224/step) 239,580
  walk of 256, assembly                            24,886

So a full-depth walk adds ~99k gas to a ~114k warm redemption — an 87% increase
in the worst case, not noise. The estimate was 1.7x low against an optimal
implementation and 4x low against a naive one.

Records the measured table, states the trade plainly (on-chain gas rises to buy
a one-hash off-chain payment path, and holds only because redemption is rare
and one call settles every prior epoch), and adds the implementation
requirement the numbers imply: hash from scratch space in assembly, because
round-tripping through abi.encodePacked costs 2.4x more for the same result.
Adds the matching Negative consequence, which previously named only the audit
surface and not the gas.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The claim that justified deleting the watermark self-heal — "a signer derives
its own chain index from the preimages it has released, so it always knows its
position" — silently assumed the signer still HAS its state. A client that
crashed and lost it knows nothing, and had no way to place itself on a lane or
choose a correct base for its next epoch. The rejection carried no data either,
so the node could not tell it.

Adds ADR 003 § Client Restart and Lane Resume:

- A signer SHOULD derive each epoch's chain seed as
  KDF(signer_secret, pool_id, provider, epoch_nonce) rather than persist it, so
  it keeps no per-lane secret and can regenerate any chain from its long-term
  key. `provider` is in the derivation because chains must stay independent per
  lane; `epoch_nonce` makes re-derivation reproduce the same chain and a new
  epoch never reuse one.
- The node supplies the position the signer cannot derive, as a `LanePosition
  { epoch_nonce, chain_index, preimage }` on `StaleEpoch`.
- It authenticates itself with one hash: claiming index k requires exhibiting
  preimage k, which the node can only hold if the signer released it and cannot
  compute from a lower one. Understating is possible and self-harming.

This is strictly stronger than the bundle it replaces, which needed two
signature gates because a bare cumulative number carries no proof of itself.
The payload shrinks and the gates disappear.

Also records what was already true and unstated: a client that never comes back
owes nothing, having paid only for chunks it received, and abandons at worst an
unspent chain holding no money.

Wire: `VoucherRejected` goes from one field to two (`reason`, `position`).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@thiras
thiras force-pushed the claude/payword-hash-chain-meter branch from 0375b00 to 8abcc2b Compare August 11, 2026 16:09
The naive-walk row said 239,580 gas (~224/step). Re-measured on the
stated setup (solc 0.8.28, optimizer on, 200 runs) it is 193,306
(~189/step), and `abi.encode` and `bytes.concat` measure the same, so
the saving comes from staying in scratch space rather than from the
spelling. The assembly rows reproduce within 1%, so the 87% worst-case
increase over a warm redemption is unchanged; only the penalty for the
naive form drops from 2.4x to ~1.95x.

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

alpergundogdu commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Discussion note (not a blocker) — two economic floors under the finer meter that the ADR does not currently state, and that interact:

1. USDC-precision payability floor. USDC is 6-decimal, so the smallest non-zero payment is $0.000001. Against the ADR 009 price band the default 64 KiB chunk is sub-precision:

  • target $0.01/GB → 64 KiB ≈ $0.00000066 → rounds to 0, unpayable (the rate floor rejects it).
  • finest payable chunk ≈ ~100 KB at the $0.01/GB target, ≈ ~1 MB at the $0.001/GB floor.

So chunk_bytes has a price×precision floor and the 64 KiB default sits below it. Raising chunk_bytes to the payable minimum gives back part of the meter-fineness win — the withholding bound grows with the chunk.

2. Settlement-gas floor — which this PR raises. Per the ADR’s own Consequences, a full-depth walk adds ~99k gas to a ~114k redemption (+87% worst case). That lifts the minimum cumulative delivery worth an on-chain redeem (rough, current spot):

  • Arbitrum: ~430–800 MB per lane-lifetime
  • Optimism: ~20–40 MB

Why they belong together. Both bound the same region — value that moves off-chain but is uneconomic to settle on-chain, i.e. the dust / free-ride surface a non-paying lane sits in. Floor (1) caps how fine the meter is actually allowed to go; the walk widens floor (2). Note the direction: making chunks payable pushes chunk_bytes up, which shortens the walk — so the two floors partly pull against each other, worth reconciling deliberately.

Discussion questions:

  • Should the 64 KiB default instead be derived from chunk_price ≥ 1 USDC unit at the live rate, rather than fixed?
  • Is MAX_CHAIN_LENGTH = 1024 sized against the raised settlement gas on the target chain? (Negligible on a cheap L2; a full epoch is ~$0.008 on Arbitrum.)
  • Does the finer meter still pay for itself once chunk_bytes is floored to payability?

@alpergundogdu

alpergundogdu commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up — voucher schema slimming. Calldata is the dominant L2 redeem cost, so invariant fields re-posted on every redemption are pure waste (same bytes, over and over).

Hoist invariant policy fields to constants — drop from the signed voucher:

  • chain_length → fix to MAX_CHAIN_LENGTH. Removes a field and makes the walk bound deterministic.
  • chunk_bytes → fix to one value in the payable band (~256 KB–1 MB, per the precision floor in the previous note). No economic repudiation — a structural constant everyone agrees on. Also settles the earlier "derive vs fix" question: fix it once, globally, at the payable floor.

Net of the two real cuts: ~2 signed fields removed ≈ ~20% less redeem calldata → proportionally smaller dust floor on calldata-dominated chains (Arbitrum). Negligible where calldata is already near-free (Optimism).

@alpergundogdu

Copy link
Copy Markdown
Contributor

Closing in favour of a narrower split — thanks for the deep work here, the reasoning is being carried forward, not dropped.

PayWord lands on its own in ADR 003 (Payment Model) — where the payment model lives, not a new ADR — tracked in #1670. Both review notes on this PR are folded into that issue:

  • chunk payability floor (64 KiB is sub-USDC-precision → unpayable; set chunk_bytes at the ~100 KB–1 MB payable floor),
  • voucher schema slimming (fix chain_length/chunk_bytes out of the signed voucher, keep chunk_price signed).

Decision 1 (best-effort / async voucher persistence, chain-as-floor) is not being silently dropped — it's flagged in #1670 as needing its own home (fold the max(local, chain) watermark seed into ADR 003, file separately, or drop deliberately). Your call on where it goes.

Two related follow-ups spun out of the same discussion:

Reopen if you'd rather iterate here instead.

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.

3 participants