Skip to content

feat: enforce the seller-side deposit floor before serving, drop the on-chain minDeposit - #1518

Merged
alpergundogdu merged 5 commits into
mainfrom
claude/deposit-floors-1516-1515
Jul 30, 2026
Merged

alpergundogdu merged 5 commits into
mainfrom
claude/deposit-floors-1516-1515

Conversation

@thiras

@thiras thiras commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Batches two issues about deposit floors. They belong together because the first is the second's safety predicate: #1515's argument is "the seller-side per-voucher ceiling already bounds service to what's funded", and #1516 is what makes that true before the first byte rather than after the first interval.

Closes #1516
Closes #1515

#1516 — the seller-side floor was off by one credit window

serve_stream's direct-serve path signed a success StreamResponse and started streaming without ever consulting the channel's remaining deposit. The only deposit authority was ChannelState::stage_voucher (AmountExceedsDeposit), which cannot fire until the first voucher boundary — by which point a full credit window had shipped. A channel that could not cover even that window was served it anyway, on every request, and a client's resume loop could farm a fresh one per retry attempt.

The serve path now reserves min(credit_window(interval_bytes), request span) against remaining headroom and refuses before signing, reusing the existing ServeRejectReason::InsufficientDeposit and its counter. It is the direct-serve twin of the pull-through guard window.rs has carried since #856, against a narrower ceiling; both are cross-referenced so they stay in step.

Three quantities are deliberate and documented at the call site:

  • Headroom, not gross deposit. Both stage_voucher and PaymentChannel._advanceClaimWatermark compare the cumulative voucher amount, so a long-lived channel with most of its deposit claimed has almost nothing left. Gating on the gross deposit would leave the bug intact for reused channels — the common case.
  • The credit window, not one interval. deliver streams while delivered - paid < credit_window(interval_bytes), so gating on one interval would let configuring credit_window_bytes (Paid delivery is stop-and-wait per voucher: throughput is RTT-bound, not link-bound #1477) silently reopen the hole.
  • Capped by the request span. A funded sub-interval blob or bounded range must not be refused for failing to cover a window it will never use.

The reservation is priced in content bytes while delivery bills bao wire bytes, so it runs loose by the proof overhead — the same deliberate looseness window.rs documents, and in the safe direction (it can only ever serve a request it should have refused, never refuse one that could pay). Absolute residual free egress drops from a full credit window (1 MiB default) to the proof bytes on one. The mid-stream ceiling remains the exact authority.

No wire, config, or ABI change.

#1515 — the on-chain floor was dead weight

PaymentChannel.minDeposit bounded neither of the things it appeared to: service is bounded by what the deposit funds, and channel spam by gas. It cost a storage slot, a governance setter, two ABI surfaces, an error selector, and a deposit clamp reimplemented at four Rust call sites.

Removed the state var, DEFAULT_MIN_DEPOSIT, setMinDeposit, MinDepositUpdated, DepositBelowMinimum, and both openChannel checks. The floor was the only zero-guard, so both checks are replaced by the existing ZeroAmount — pre-transfer on the requested amount, post-transfer on the received balance delta, mirroring topUp. The second is not redundant: a fee-on-transfer USDC proxy could shave a positive deposit to zero, and a zero-deposit channel is un-serviceable while still consuming a _providerChannels slot and a client nonce.

MIN_DEPOSIT_FLOOR was never a deposit floor — both uses bound the delivery rate floor, and _advanceClaimWatermark relies on it to keep deliveryFloor a non-zero divisor. Renamed MIN_RATE_FLOOR, re-homed beside MAX_RATE_PER_MB, and documented, since the old name was carrying the explanation.

openChannel drops ~2.2k gas per call.

BREAKING (contract ABI, not config)

minDeposit() and setMinDeposit(uint256) are gone; the MinDepositUpdated topic and the DepositBelowMinimum selector are retired. A governance parameter no longer exists, so any scripted setMinDeposit proposal is un-executable. Requires a fresh deployment — PaymentChannel has a constructor and no proxy.

Not config-breaking: blockchain.buyer_deposit_micro_usdc keeps its name, its 10 USDC default, and its > 0 validation. Buyer paths simply no longer read the contract to clamp up to a floor.

Three places the issues were wrong

Following them literally would have shipped bugs:

  1. fix(node): refuse before serving when deposit can't cover the next interval #1516 specified the gross deposit. Wrong quantity — see above.
  2. fix(node): refuse before serving when deposit can't cover the next interval #1516 said "one voucher interval." Understates the exposure — deliver fronts a whole credit window.
  3. refactor(contracts): remove minDeposit floor #1515 said to drop ChannelOpenFailureReason::InsufficientDeposit. Two of its three trigger selectors are ERC20InsufficientBalance/ERC20InsufficientAllowance, untouched by this change and the primary operator signals for that class. Kept the variant and its counter; swapped only DepositBelowMinimum for ZeroAmount, since a zero-deposit revert is exactly the "fund the wallet / raise the deposit" class and folding it into ContractRevert would tell the operator the cause was on-chain state.

Two things worth a reviewer's attention

  • test_setters_onlyGovernance was PaymentChannel's only AccessControlUnauthorizedAccount probe, and its probe target was setMinDeposit. Deleting the setter would have dropped all governance-authorization coverage with zero CI signal. Retargeted to all three surviving GOVERNANCE_ROLE setters, which also makes the plural name true.
  • tracked_watermark_survives_post_ack_error changed terminal error, as a direct consequence of the fix. The mid-stream rejection carries a WatermarkBundle, so the client reseeds and retries, and the retry is now refused pre-serve instead of handed another free window — pre-fix, each resume attempt farmed one. Its acked == 1 assertion still pins the mid-stream ceiling (only reachable if voucher 1 was acked and voucher 2 hit it), and a new assertion pins that the resume loop can no longer farm windows.

Review round (commit 5)

A multi-agent review found two real defects in the gate and a set of wrong claims, all fixed in fix(node): price the deposit gate on the aligned span…:

  • The gate priced the wrong quantity. export_bao_range_stream snaps a range out to 16 KiB chunk-group boundaries and deliver does not trim back, so the payer is billed the aligned superset — while the gate reserved the requested span. A two-byte range reserved 2 bytes against a 16 KiB group delivered. Added aligned_span() mirroring align_range, with 7 unit tests, and re-exported CHUNK_GROUP_BYTES through decdn-cache (which already owns the aligning export) rather than adding a node → bao-range edge.
  • clamped_rate() ran twice per refusal. respond_error calls it internally; the gate added a second call, and it bumps rate_bounds_clamped and logs. Added respond_error_at_rate.
  • "well under 1%" was wrong — that is ADR 038's whole-blob amortized rate; the boundary proof measures 6.25% for a single group of a 1 GiB blob. Restated as the absolute bound (~1.3 KiB/request).
  • Two docs claimed coverage that does not exist. The guard sits after the buffered/range/local fill tiers, which are gated on ownership but not deposit, so an underfunded channel can still cause origin egress and upstream USDC. metrics.rs and ADR 037 now say so; the ordering hole is serve: hoist a pre-spend deposit check above the buffered/range/local fill tiers #1519.
  • Corrected wrong claims in the CHANGELOG (MIN_DEPOSIT_FLOOR had three call sites, one being setMinDeposit's own bound), ADR 003 (the griefing model attributed the defender's gas to the attacker), PaymentChannel.sol, config/mod.rs, channel_open_error.rs, and a stale type(uint64).max in the e2e journey.

Two test gaps closed, both confirmed to fail under an injected mutant:

  • client_headroom_equal_to_the_ceiling_is_served — < → <= survived all four original tests while refusing every exactly-funded channel.
  • client_resumed_range_is_priced_on_the_tail_not_the_whole_blob — the byte_offset > 0 arm. A NotFound on a resume makes the CLI rewind to zero and re-pay for the whole blob, so a mispriced resume would silently double the bill on every interrupted large fetch.

Follow-ups filed rather than widened into this PR: #1519 (hoist a pre-spend deposit check above the fill tiers — the one that still costs the operator money), #1520 (the refusal has no log, alert, or dashboard), #1521 (no fee-on-transfer mock, so received-delta accounting is untested).

Verification (all run locally)

Gate Result
cargo nextest run --workspace 2660 passed
forge test (CI profile) 799 passed
forge build --sizes --deny warnings clean
forge fmt --check / solhint clean / 0 errors
slither (fail_on: medium) exit 0
aderyn (fail-on: high) 0 highs
cargo clippy --workspace --all-targets -D warnings clean
cargo doc / cargo deny clean
anvil e2e (settlement) 5 passed
anvil e2e (journeys) 30 passed

Gas snapshot regenerated. The anvil journeys matter most here — they are the only gate that catches sol! binding drift, and they deploy the modified PaymentChannel for real via the production DeployProtocol script.

Also verified by hand: the ~2.2k gas figure against the snapshot, the ADR 009 §Rate floor citation in the new NatSpec, that no saturation in the new gate can fail open (all fail closed), and that headroom == ceiling passes since the check is <.

ADR upkeep

adr/ is the source of truth per CLAUDE.md, so the removed parameter is gone from canon: the ADR 003 quick-reference bullet, setter table, constructor description and safety-bounds table; the ADR 009 governable-parameter table and rationale bullet; the ADR 016 GOVERNANCE_ROLE setter list. The adjacent "Rate floor" rows stay — that is what MIN_RATE_FLOOR names.

Two paragraphs were rewritten rather than deleted, because their reasoning was load-bearing on the floor: Deposit Economics now states why a network minimum is unnecessary, and Channel griefing is re-anchored on gas rather than on a 10 USDC recommendation nothing on-chain ever enforced.

Rebased onto #1512

Ten files overlapped. Two needed manual resolution; the rest auto-merged and were checked by hand for semantic damage.

Worth noting for reviewers: #1512 deleted the #1130 origin-held CacheMiss suppression from respond_error. That removes the concern that a new pre-serve ok: false on a held blob could manufacture phantom-announcement evidence — the offense no longer exists, so the question is moot rather than merely out of scope.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Breaking Changes
    • Payment channels now accept any non-zero deposit; zero deposits are rejected, and the “minimum deposit” on-chain floor and governance controls/events are removed (fresh deployment required).
  • Bug Fixes
    • Underfunded serving is now refused before streaming begins, using channel remaining headroom and a reserved ceiling based on credit window vs requested span.
  • Documentation
    • Updated ADRs, CLI/help text, and configuration guidance to reflect the new deposit behavior and recommended-minimum wording.
  • Tests / Chores
    • Adjusted e2e/unit coverage, ABI bindings, and gas snapshots to match the new rules.

Copilot AI review requested due to automatic review settings July 29, 2026 19:59
@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Free

Run ID: 1a31220b-5360-4fad-b9be-534eb2e31580

📥 Commits

Reviewing files that changed from the base of the PR and between b5875f1 and 6a4c0cb.

📒 Files selected for processing (32)
  • CHANGELOG.md
  • adr/003-payments.md
  • adr/009-governance.md
  • adr/016-contract-interactions.md
  • adr/037-regional-proxy-warming.md
  • contracts/.gas-snapshot
  • contracts/src/PaymentChannel.sol
  • contracts/test/PaymentChannel.t.sol
  • crates/cache/src/lib.rs
  • crates/cli/src/commands/channel.rs
  • crates/cli/src/commands/fetch.rs
  • crates/client-pull/src/buyer_channel.rs
  • crates/common/src/cli/fetch.rs
  • crates/common/src/config/mod.rs
  • crates/common/src/config/resolved.rs
  • crates/common/src/config/types.rs
  • crates/e2e/src/bindings.rs
  • crates/e2e/src/client.rs
  • crates/e2e/tests/cli_bundle_pull_channel_id.rs
  • crates/e2e/tests/cli_fetch_resume.rs
  • crates/e2e/tests/cli_fetch_topup.rs
  • crates/e2e/tests/g_gov_02_rate_bounds.rs
  • crates/incentive/src/channel_open_error.rs
  • crates/incentive/src/payment_channel.rs
  • crates/node/src/buyer_channel.rs
  • crates/node/src/handlers/client/dispatch.rs
  • crates/node/src/handlers/client/mod.rs
  • crates/node/src/handlers/client/window.rs
  • crates/node/src/handlers/client/wire.rs
  • crates/node/src/metrics.rs
  • crates/node/tests/anvil_settlement_e2e.rs
  • crates/node/tests/client_loopback.rs
💤 Files with no reviewable changes (2)
  • crates/common/src/cli/fetch.rs
  • adr/009-governance.md
🚧 Files skipped from review as they are similar to previous changes (26)
  • crates/common/src/config/resolved.rs
  • crates/e2e/src/bindings.rs
  • adr/016-contract-interactions.md
  • crates/node/tests/anvil_settlement_e2e.rs
  • crates/e2e/tests/g_gov_02_rate_bounds.rs
  • crates/common/src/config/mod.rs
  • crates/e2e/src/client.rs
  • crates/e2e/tests/cli_bundle_pull_channel_id.rs
  • crates/e2e/tests/cli_fetch_resume.rs
  • crates/incentive/src/payment_channel.rs
  • crates/client-pull/src/buyer_channel.rs
  • crates/e2e/tests/cli_fetch_topup.rs
  • adr/037-regional-proxy-warming.md
  • crates/incentive/src/channel_open_error.rs
  • crates/common/src/config/types.rs
  • contracts/.gas-snapshot
  • crates/node/src/handlers/client/window.rs
  • crates/node/src/handlers/client/dispatch.rs
  • crates/cli/src/commands/channel.rs
  • crates/node/src/metrics.rs
  • CHANGELOG.md
  • crates/cli/src/commands/fetch.rs
  • contracts/test/PaymentChannel.t.sol
  • adr/003-payments.md
  • crates/node/src/buyer_channel.rs
  • contracts/src/PaymentChannel.sol

Walkthrough

The contract removes the governable minimum-deposit API and accepts any non-zero deposit. Client integrations stop clamping deposits on-chain, while node serving adds pre-signing checks against remaining payment headroom and validates the behavior with loopback tests.

Changes

Payment channel and serve-path changes

Layer / File(s) Summary
Remove the on-chain minimum deposit API
contracts/src/PaymentChannel.sol, contracts/test/PaymentChannel.t.sol, crates/incentive/..., adr/..., contracts/.gas-snapshot
PaymentChannel removes minDeposit, setMinDeposit, related ABI elements, and DepositBelowMinimum; zero deposits now revert while any non-zero deposit is accepted. Rate-bound naming, documentation, bindings, tests, and gas snapshots are updated.
Update client deposit selection
crates/cli/..., crates/client-pull/..., crates/common/..., crates/e2e/..., crates/node/src/buyer_channel.rs
Client and buyer-channel flows use configured deposits directly, retaining the 10 USDC recommendation without querying or clamping to an on-chain minimum.
Add pre-serve deposit budgeting
crates/cache/src/lib.rs, crates/node/src/handlers/client/..., crates/node/src/metrics.rs, CHANGELOG.md, adr/037-regional-proxy-warming.md
serve_stream reserves capacity based on aligned request span, credit window, and remaining channel headroom before signing a response.
Validate deposit-gated serving
crates/node/tests/client_loopback.rs
Tests cover underfunded, sub-interval, configured-window, resume, boundary, and spent-down channels, including refusal type, unchanged state, and rejection metrics.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant serve_stream
  participant PaymentChannelState
  participant Metrics
  Client->>serve_stream: Send StreamRequest
  serve_stream->>PaymentChannelState: Read deposit and last_amount
  serve_stream->>serve_stream: Calculate aligned request credit ceiling
  serve_stream->>Metrics: Increment rejection metric when headroom is insufficient
  serve_stream-->>Client: Return pre-serve refusal or signed response
Loading

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.

@github-actions

Copy link
Copy Markdown

Gas snapshot

No gas changes vs base.

@github-actions

github-actions Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Contracts coverage

Line coverage: 90.05% (2508/2785 lines)
▲ +0.15pp vs base (89.90% → 90.05%)
Run: 30499440716

@github-actions

github-actions Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 80.19% (was 80.17%, ▲ +0.02%) — 54223/67622 lines

File Coverage Lines Δ
crates/cache/src/lib.rs 100.00% 28/28 ● 0.00%
crates/cli/src/commands/channel.rs 54.96% 471/857 ▲ +0.38%
crates/cli/src/commands/fetch.rs 41.34% 530/1282 ▲ +0.22%
crates/client-pull/src/buyer_channel.rs 45.53% 107/235 ● 0.00%
crates/common/src/cli/fetch.rs 100.00% 150/150 ● 0.00%
crates/common/src/config/mod.rs 97.05% 6853/7061 ● 0.00%
crates/common/src/config/resolved.rs 100.00% 33/33 ● 0.00%
crates/e2e/src/client.rs 0.00% 0/414 ● 0.00%
crates/incentive/src/channel_open_error.rs 95.77% 68/71 ▼ 0.28%
crates/node/src/buyer_channel.rs 59.21% 1266/2138 ▲ +0.01%
crates/node/src/handlers/client/dispatch.rs 88.47% 284/321 ▲ +2.28%
crates/node/src/handlers/client/mod.rs 89.71% 680/758 ● 0.00%
crates/node/src/handlers/client/window.rs 85.07% 245/288 ● 0.00%
crates/node/src/handlers/client/wire.rs 95.56% 129/135 ▲ +0.36%
crates/node/src/metrics.rs 95.39% 972/1019 ● 0.00%
History
Commit Total Δ vs base
b5875f1 80.23% ▲ +0.02%
925c72a 80.17% ● 0.00%
1971929 80.19% ▲ +0.02%
6a4c0cb (HEAD) 80.19% ▲ +0.02%

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 tightens payment-channel safety on the node serve path by enforcing a seller-side remaining-deposit floor before signing/streaming, and simplifies the on-chain PaymentChannel by removing the minDeposit governable parameter (ABI-breaking, redeploy required). It updates Rust client/buyer paths to stop reading/clamping against minDeposit, refreshes tests, metrics/docs, and ADR canon accordingly.

Changes:

  • Add a direct-serve pre-flight deposit guard in serve_stream (reserve min(credit_window, request_span) against remaining headroom before signing).
  • Remove PaymentChannel.minDeposit/setMinDeposit/related event+error; replace open checks with ZeroAmount and rename MIN_DEPOSIT_FLOOR → MIN_RATE_FLOOR.
  • Update Rust bindings, buyer-channel open logic, tests (Rust + Solidity + e2e), metrics/docs, and ADR references to match the new contract surface.

Reviewed changes

Copilot reviewed 29 out of 29 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
crates/node/src/handlers/client/dispatch.rs Adds pre-sign direct-serve deposit gate based on remaining headroom and credit window/span.
crates/node/src/handlers/client/window.rs Cross-references the existing pull-through pre-flight deposit guard with the new direct-serve twin.
crates/node/src/metrics.rs Updates channel-open and serve-stream rejection metric documentation to reflect removed minDeposit.
crates/node/src/buyer_channel.rs Removes minDeposit clamping from buyer-channel refill/open logic and adjusts unit tests.
crates/node/tests/client_loopback.rs Adjusts loopback tests for new refusal behavior and adds focused #1516 regression tests.
crates/node/tests/anvil_settlement_e2e.rs Updates settlement e2e fixtures/comments for removed on-chain deposit floor and updated revert string sample.
crates/incentive/src/payment_channel.rs Removes minDeposit() from the Rust sol! interface.
crates/incentive/src/channel_open_error.rs Reclassifies insufficient-deposit failures using ZeroAmount selector; updates docs/tests.
crates/client-pull/src/buyer_channel.rs Updates buyer-channel open docs/error commentary to remove minDeposit references.
crates/cli/src/commands/fetch.rs Removes minDeposit read/clamp from CLI fetch open path; updates docs.
crates/cli/src/commands/channel.rs Removes minDeposit read/clamp from decdn channel open path and updates docs.
crates/common/src/config/mod.rs Removes “clamp to on-chain floor” wording; keeps > 0 validation and updates error text.
crates/common/src/config/resolved.rs Updates resolved-config docs to reflect “escrowed as configured” semantics.
crates/common/src/config/types.rs Updates config-schema docs for buyer deposit (removes on-chain clamping).
crates/common/src/cli/fetch.rs Updates CLI arg help text to remove minDeposit clamping claim.
crates/e2e/src/bindings.rs Removes minDeposit() from e2e contract bindings.
crates/e2e/src/client.rs Updates default deposit documentation to remove minDeposit reference.
crates/e2e/tests/cli_fetch_topup.rs Removes minDeposit clamp logic and updates deposit comment.
crates/e2e/tests/cli_fetch_resume.rs Updates deposit comment to ADR recommendation (no on-chain floor).
crates/e2e/tests/cli_bundle_pull_channel_id.rs Removes minDeposit clamp logic and updates deposit comment.
crates/e2e/tests/g_gov_02_rate_bounds.rs Renames MIN_DEPOSIT_FLOOR → MIN_RATE_FLOOR in docs and ABI comments.
contracts/src/PaymentChannel.sol Removes minDeposit storage+setter+event+error; enforces non-zero deposit via ZeroAmount; renames rate-floor constant.
contracts/test/PaymentChannel.t.sol Updates tests for zero-deposit revert, 1-base-unit open acceptance, removed getter/setter, and governance-only setter coverage.
contracts/.gas-snapshot Refreshes gas snapshot reflecting removed storage and checks.
CHANGELOG.md Documents ABI break and the new pre-serve deposit behavior.
adr/003-payments.md Updates canon: no on-chain deposit floor beyond non-zero; documents seller-side pre-flight deposit guard rationale.
adr/009-governance.md Removes minDeposit from governable-parameter tables and rationale.
adr/016-contract-interactions.md Removes setMinDeposit from GOVERNANCE_ROLE setter inventory.
adr/037-regional-proxy-warming.md Notes direct-serve path now has the same deposit guard (narrower ceiling) as pull-through.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread crates/common/src/config/types.rs Outdated
Comment on lines 202 to 206
/// Deposit (base units, `µUSDC`) the buyer path escrows when opening a
/// `PaymentChannel` against an upstream provider on a cache miss (#744).
/// Absent => default (10 USDC = `10_000_000` `µUSDC`, ADR 003 § Deposit
/// Economics recommended minimum). Clamped up to the on-chain `minDeposit`
/// Economics recommended minimum). Escrowed as configured
/// floor at open time.
Comment thread crates/node/src/metrics.rs Outdated
Comment on lines 802 to 806
/// `decdn_channel_open_failures_insufficient_deposit_total` (#966): a buyer
/// `openChannel` tx reverted because the node's USDC balance/allowance could
/// not cover the deposit, or the deposit was below the on-chain `minDeposit`
/// floor. A *misconfiguration* signal — the fix is operator-side (fund the
/// not cover the deposit, or the requested deposit was zero.
/// A *misconfiguration* signal — the fix is operator-side (fund the
/// wallet, raise the configured deposit), not infrastructure. A plain counter
…redit window

The direct-serve path signed a success `StreamResponse` and streamed a full
credit window before the per-voucher deposit ceiling could fire at the first
voucher boundary, so a channel that could not cover even that window was served
it anyway — one free interval per request at the default cadence, and a fresh
one per attempt of the client's resume loop.

Add the direct-serve twin of the pull-through pre-flight guard `window.rs` has
carried since #856. It reserves `min(credit window, requested span)` against the
channel's remaining headroom and refuses before anything is signed.

Three quantities are deliberate, and documented at the call site:

- **Headroom, not gross deposit.** Both `ChannelState::stage_voucher` and
  `PaymentChannel._advanceClaimWatermark` compare the *cumulative* voucher
  amount, so a long-lived channel with most of its deposit claimed has almost
  nothing left; gating on the gross deposit would reproduce the bug for the
  reuse case.
- **The credit window, not one interval.** `deliver` streams while
  `delivered - paid < credit_window(interval_bytes)`, so configuring
  `credit_window_bytes` (#1477) would otherwise silently re-open the hole.
- **Capped by the request span.** A funded sub-interval blob or bounded range
  must not be refused for failing to cover a window it will never use.

The reservation is priced in content bytes while delivery bills bao wire bytes,
so it runs loose by the proof fraction — the same deliberate looseness
`window.rs` documents, and in the safe direction. Residual free egress drops
from a whole credit window to well under 1% of one.

Reuses the existing `ServeRejectReason::InsufficientDeposit` and its counter; no
new metric, and no wire, config, or ABI change.

`tracked_watermark_survives_post_ack_error` changes terminal error as a direct
consequence: the mid-stream rejection carries a `WatermarkBundle`, so the client
reseeds and retries, and the retry is now refused pre-serve instead of being
handed another free window. Its `acked == 1` assertion still pins the mid-stream
ceiling, and it now also pins that the resume loop cannot farm windows.

Closes #1516

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@thiras
thiras force-pushed the claude/deposit-floors-1516-1515 branch 2 times, most recently from 925c72a to 1971929 Compare July 29, 2026 22:51
thiras and others added 4 commits July 30, 2026 02:22
Preparation for removing the `minDeposit` floor from `PaymentChannel` (#1515).
Every buyer-side open path read the floor off the contract and clamped its
configured deposit up to it; with the parameter gone there is nothing to clamp
to, and the read is a wasted RPC round trip at bring-up.

Drops the `minDeposit()` declaration from both `sol!` bindings and every call
site: the `BuyerChannelService` bootstrap self-check and its
`max(hint, default, min_deposit)` targets, the two CLI open paths, and the two
e2e fixtures that re-derived the clamp. Deposits are now escrowed exactly as
configured.

`blockchain.buyer_deposit_micro_usdc` keeps its name, its 10 USDC default, and
its `> 0` validation — the contract still rejects a zero deposit, so a
configured 0 remains an operator mistake worth catching at load time. Only the
message stops naming a parameter that is going away.

The contract itself is untouched here, so this commit builds and tests green
against the current `PaymentChannel`. Splitting it out also keeps the binding
deletions in the same commit as their callers: `cli_fetch_topup` and
`cli_bundle_pull_channel_id` call `minDeposit()` and only compile under
`--features anvil-e2e`, which the default CI test job never builds.

Refs #1515

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

The network minimum-deposit parameter bounded nothing that is not already
bounded. Service is bounded by what the deposit funds — the seller-side
per-voucher ceiling, tightened to fire before the first byte in the preceding
commit — and channel spam is bounded by gas. What it cost was a storage slot, a
governance setter, two ABI surfaces, an error selector, and a deposit clamp
reimplemented at four Rust call sites.

Removes `minDeposit`, `DEFAULT_MIN_DEPOSIT`, `setMinDeposit`,
`MinDepositUpdated`, `DepositBelowMinimum`, and both `openChannel` checks. The
floor was the only zero-guard on a deposit, so both checks are replaced by the
existing `ZeroAmount` — pre-transfer on the requested amount, and post-transfer
on the received balance delta, mirroring `topUp`. The second is not redundant: a
fee-on-transfer USDC proxy upgrade could shave a positive deposit to zero, and a
zero-deposit channel is un-serviceable (every voucher hits
`AmountExceedsDeposit`) while still consuming a `_providerChannels` slot and a
client nonce.

`MIN_DEPOSIT_FLOOR` was never a deposit floor — both its uses bound the
delivery *rate* floor, and `_advanceClaimWatermark` relies on it to keep
`deliveryFloor` a non-zero divisor. Renamed to `MIN_RATE_FLOOR`, re-homed beside
`MAX_RATE_PER_MB`, and documented, since the old name was carrying the
explanation.

`ChannelOpenFailureReason::InsufficientDeposit` is KEPT, contrary to the issue's
plan: two of its three trigger selectors are `ERC20InsufficientBalance` and
`ERC20InsufficientAllowance`, which this change does not touch and which are the
primary operator signals for that class. Only `DepositBelowMinimum` leaves the
classifier, replaced 1:1 by `ZeroAmount` — a zero-deposit revert is exactly the
"fund the wallet / raise the deposit" class, and folding it into
`ContractRevert` would tell the operator the cause was on-chain state.

`test_setters_onlyGovernance` was the contract's ONLY
`AccessControlUnauthorizedAccount` probe and its probe target was
`setMinDeposit`, so deleting the setter would have dropped PaymentChannel's
authorization coverage entirely with no CI signal. Retargeted to cover all three
surviving `GOVERNANCE_ROLE` setters, which also makes the plural name true and
removes the recurrence.

BREAKING (contract ABI): `minDeposit()` and `setMinDeposit(uint256)` are gone,
as are the `MinDepositUpdated` topic and the `DepositBelowMinimum` selector. A
governance parameter no longer exists, so any scripted `setMinDeposit` proposal
is un-executable. Requires a fresh deployment — PaymentChannel has a constructor
and no proxy. Not config-breaking: `blockchain.buyer_deposit_micro_usdc` keeps
its name, its 10 USDC default, and its `> 0` validation.

Gas snapshot regenerated: `openChannel` drops ~2.2k gas per call.

Refs #1515

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`adr/` is the source of truth for protocol claims, so the removed parameter must
not survive in canon. Drops it from the ADR 003 quick-reference bullet, the
setter table, the constructor description, and the safety-bounds table; from the
ADR 009 governable-parameter table and its rationale bullet; and from the
ADR 016 `GOVERNANCE_ROLE` setter list. The adjacent "Rate floor" rows stay —
that is the bound `MIN_RATE_FLOOR` names.

Two paragraphs needed rewriting rather than deletion, because their reasoning
was load-bearing on the floor:

- **Deposit Economics** justified the 1 USDC minimum as a dust-channel safety
  floor. It now states why a network minimum is unnecessary — service is bounded
  by what the deposit funds, spam by gas — and points at the two sections that
  carry those bounds. The 10 USDC client-side recommendation is unchanged
  throughout; only its status as "recommendation, not floor" is made explicit.
- **Channel griefing** costed the attack at "$1,000 opens 100 channels" on the
  strength of that recommendation, which nothing on-chain ever enforced. Re-
  anchored on gas, which is the real bound (and always was — an attacker was
  never obliged to follow a client-side default). The ~$18/100-channel gas
  figure and both proposed mitigations are unchanged and now more relevant.

Adds the BREAKING CHANGELOG entry: the ABI removals, the vanished
`MinDepositUpdated` topic, the un-executable governance proposal, the fresh-
deployment requirement, and the explicit note that this is not config-breaking.

Closes #1515

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

Two defects in the #1516 gate, both found by review.

**The gate priced the wrong quantity.** `export_bao_range_stream` snaps a range
out to the enclosing 16 KiB chunk-group boundaries — a bao proof anchors whole
groups — and `deliver` deliberately does NOT trim back, because trimming would
break verification; the receiver discards the leading bytes itself. So the payer
is billed for the aligned superset, while the gate reserved against the
*requested* span. A two-byte range request reserved 2 bytes against a full
16 KiB group delivered: four orders of magnitude, and up to two groups (~32 KiB)
in general. That is not the by-design looseness documented below it — it is the
wrong quantity for the same thing.

Adds `aligned_span`, mirroring `decdn_bao_range::align_range`, and re-exports
`CHUNK_GROUP_BYTES` through `decdn-cache` rather than adding a dependency edge
from `node` to `bao-range` — cache already owns the aligning export, so the
alignment granularity is legitimately part of its surface, and the re-export
doc says why it is billing-visible.

**`clamped_rate()` ran twice per refusal.** `respond_error` calls it internally,
and the gate added a second call. It is side-effecting: it bumps
`rate_bounds_clamped` and logs a warning when the configured rate sits below the
on-chain delivery floor. So on such a node every gate refusal double-counted the
metric and double-logged for one request that signed one response. Adds
`respond_error_at_rate` for a caller that already holds the rate;
`respond_error` delegates to it, so refusal paths that never needed the rate are
unchanged. The commit that introduced the gate claimed this was once-per-request;
it was not.

**Corrected claims.** The residual under-reservation was documented as "well
under 1%", citing ADR 038's ~0.4%. That figure is the whole-blob amortized rate;
the boundary proof is `64 * log2(blob_groups / range_groups)`, which measures at
6.25% for a single group of a 1 GiB blob and 7.81% at 16 GiB. Restated as the
absolute bound (~1.3 KiB per request), which is what actually carries the safety
argument, since the fraction is only small for window-sized or whole-blob spans.
Also corrected: the metric doc and ADR 037 both claimed the direct-serve guard is
pre-flight, but it sits after the buffered/range/local fill tiers, which are
gated on channel ownership and not on deposit — so an underfunded channel can
still cause origin egress and upstream USDC that this refusal then declines to
bill for. Both now say so; closing that ordering hole is tracked separately.

**Tests.** `aligned_span` gets 7 unit tests covering whole blob, empty blob
(#1054), sub-group range, boundary-straddling range, already-aligned range,
whole tail, and past-the-end clamping. Two loopback tests close gaps the original
four left open, and both were confirmed to fail under an injected mutant:

- `client_headroom_equal_to_the_ceiling_is_served` — `headroom == ceiling` must
  pass, since the check is `<`. Flipping it to `<=` survived all four original
  tests while refusing every exactly-funded channel with a lossy `NotFound`.
- `client_resumed_range_is_priced_on_the_tail_not_the_whole_blob` — the
  `byte_offset > 0` arm, which `decdn fetch --output` sends on every resume.
  This one has teeth: a `NotFound` on a resume makes the CLI treat the partial
  as possibly stale, rewind to zero, and re-download *and re-pay for* the whole
  blob. A mispriced resume would silently double the bill on every interrupted
  large fetch.

Also fixes the pre-existing arithmetic in `tracked_watermark_survives_post_ack_error`'s
doc: voucher 2's cumulative amount is 16, not 15, because billing is bao wire
bytes (1.5 MiB payload = 1_578_944 wire bytes). The rewrite in the gate commit
leaned on that number, so it is corrected here rather than left to rot.

Refs #1516

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@thiras
thiras force-pushed the claude/deposit-floors-1516-1515 branch from 1971929 to 6a4c0cb Compare July 29, 2026 23:24
@alpergundogdu
alpergundogdu merged commit 3d3bb7e into main Jul 30, 2026
25 checks passed
@alpergundogdu
alpergundogdu deleted the claude/deposit-floors-1516-1515 branch July 30, 2026 13:14
thiras added a commit that referenced this pull request Jul 30, 2026
The #1516 deposit gate runs on the serve path, which a cache miss reaches only
*after* the fill ladder. `try_range_pull_through` and `try_local_populate` front
the operator's own origin egress, and `try_pull_through`'s `cache.populate` walks
the paid `Peer` origin and fronts real upstream USDC — all three gated on channel
ownership via `pull_authorized`, none on solvency. So a dust-deposit channel could
name N absent hashes, make the operator pay for each, and be refused afterwards.
The client gained nothing (#1516 closed the free-egress half) but the bill was
real, and the rising `insufficient_deposit` counter read as "the guard is working"
while meaning the opposite.

Adds a pre-spend floor above every tier. The channel is already resolved above the
ladder for the ADR-011 funder gate (`dispatch.rs`, whose own comment argues
"resolving the channel early is a `HashMap` lookup, so the cost is nil") — the
`Arc` was simply being dropped, so this holds it rather than taking the map lock
again.

**Placed in the miss arm, not at the funder gate.** The serve path's ceiling is
`min(credit_window, aligned_span(..., total_bytes))`, and `total_bytes` is
unknowable before a fill. A gate above the availability check would therefore have
to drop the span cap, making it strictly stricter than the serve gate — which
refuses funded requests. Two existing tests pin exactly that: a 256 KiB blob on a
5-unit channel, and a resumed tail on a 5-unit channel. The second matters most:
`decdn fetch` treats a refused resume as a possibly-stale partial, rewinds to zero
and re-pays for the whole blob, so mispricing a resume doubles a user's bill.

**The floor is deliberately weak** — one credit window, "can this channel pay for
anything at all" — so it catches insolvency without pre-judging a small request.
`window.rs` keeps its stricter ceiling. The honest relationship, stated at the call
site: `DEFAULT_PULL_AHEAD_BYTES` is exactly one interval, so at default settings
the two compute the same number and the window guard is redundant; it earns its
place only once `max_blob_size_bytes` is finite. Residual, documented in the ADR
and CHANGELOG rather than papered over: a channel funded to exactly one window can
still trigger a whole-blob buffered pull costing more than it can repay, because
that tier is bounded by the cache engine's separate `max_blob_mb`, not by anything
the handler prices.

**`respond_error` now takes the request's price as a required argument.** The floor
needs the rate and then falls through into the ladder, whose miss arms refuse — and
`respond_error` used to compute the rate itself, so that fall-through would
double-count `rate_bounds_clamped` and double-log: the #1518 bug one layer up.
Rather than fix it by discipline across 21 call sites, the rate-recomputing wrapper
is deleted and the explicit one promoted, so `serve_stream` holds the crate's only
production `clamped_rate()` call and refusing without having priced the request
exactly once is unrepresentable. `serve_via_window_pull_through` takes the rate as
a parameter for the same reason — it was recomputing it, so that path
double-counted on every refusal today.

The pricing block sits *below* the binding block deliberately: the exits above it
(stream-cap shed, cooperative close, malformed binding) never sign anything, and
pricing them would meter a clamp for a request that never quoted a rate.

Tests, both confirmed to fail under an injected mutant:
- `underfunded_channel_never_reaches_the_paid_pull` — `hits == 0` is the acceptance
  criterion; the `cache_miss_total 0` assertion is what proves the refusal came
  from the floor rather than from the fill missing.
- `funded_channel_still_reaches_the_paid_pull` — the boundary control. Without it,
  tightening the floor or flipping `<` to `<=` would break nothing.

`window_pull_through_insufficient_deposit_refuses_before_pulling` had its deposit
raised 1 -> 100. At 1 the new floor fires first and the test keeps passing while
silently no longer covering `window.rs`'s guard; at 100 it clears the floor (10)
but not the 64 MiB blob ceiling (640). Verified by disabling that guard and
watching the test fail.

Closes #1519

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
thiras added a commit that referenced this pull request Jul 30, 2026
Four reviewers, and they converged on one theme: the mechanisms were sound, the
justifications around them were not. Eight factual claims were wrong and three doc
comments were attached to the wrong item. Two were genuine bugs.

**Bugs**

The floor priced a bounded range at a whole credit window even though `byte_len` is
right there. At stock config that window is 8 MiB (`DEFAULT_CREDIT_WINDOW_BYTES`
over a 4 MiB `DEFAULT_VOUCHER_INTERVAL_MB`), so a client funded for a 16 KiB range
was served warm and refused cold — and `decdn fetch` reads a refused resume as a
possibly-stale partial, rewinds to zero and re-pays for the whole blob. The floor
now caps by `aligned_span` when the request bounds itself, which is exactly the
argument used against hoisting it above the availability check in the first place.

`decdn channel top-up` does not exist. `ChannelCommand` is
`List | CoopClose | Close | Settle | Clean | Open`, so the new hint sent users to
clap's "unrecognized subcommand" — worse than the opaque `NotFound` it replaced.
And the CLI's estimate used the *protocol's* 1 MiB interval against the node's
8 MiB floor, so it under-detected by 8x and stayed silent across exactly the
headroom band a stock node refuses in. Both fixed; the message is now a lower bound
phrased as a possibility, and both causes attach instead of the first winning.

**Wrong claims, all corrected**

- "a merely small request is not pre-judged" and the CHANGELOG's "could not have
  completed the transfer either way" — false at stock config, where the floor is
  8 MiB. The residual is now stated rather than denied.
- "`DEFAULT_PULL_AHEAD_BYTES` is exactly one interval" — it is 1 MiB against a
  4 MiB default interval. The conclusion held, but via `window.rs`'s
  `.max(credit_window(..))` term, not the stated premise.
- "earns its place only once `max_blob_size_bytes` is finite" — `pull_ahead_bytes`
  is validated against `max_unrecouped_leech_bytes`, never the window, and a 1 MiB
  blob cap under an 8 MiB window makes that guard *weaker* than the floor.
- "every exit above this point returns without signing anything" — the cooperative
  close signs an EIP-712 waiver. It carries no rate, which is what actually matters.
- "`_advanceClaimWatermark` would revert at `withdraw`/`settleChannel`" —
  `settleChannel` never calls it, and the seller refuses off-chain via
  `stage_voucher` long before. The real harm is buyer-side: the inflated row
  suppresses auto-refill and compounds with every top-up.
- "nothing pinned that they export at zero … read `(no data)`" — those four
  counters always exported; what was missing was the assertion.
- "same technique as `MaliciousERC20`" — shared hook, not shared technique; that
  one is a reentrancy mock.
- "a property the compiler checks" — it stops implicit recomputation; a caller can
  still pass a wrong value. Now says what it actually buys.
- `blockchain.event_poll_interval_sec` → `_ms`; the panel described `cache_miss` as
  "not availability" while plotting it; `Overloaded` is peer backpressure, not the
  local problem the counter's doc implied.

**Three orphaned doc comments.** New items were inserted between an existing doc
block and the item it documented, so the block re-anchored and the original was left
bare. `credit_window` — cited by three other comments and called by the new floor —
ended up with no doc at all, its deadlock-freedom rationale heading a const. Nothing
catches this: both readings compile and rustdoc sees every item as documented.

**Four tests, each verified against an injected mutant**

- `spent_out_channel_never_reaches_the_paid_pull` — the `last_amount` term. A mutant
  reading `headroom = deposit` passed the *entire* suite before this. A spent-out
  channel is the production shape; a dust channel is the adversarial one, and only
  the latter was covered.
- `a_refused_request_clamps_the_rate_exactly_once` and
  `a_request_rejected_before_pricing_does_not_clamp_the_rate` — #1518's invariant,
  which nothing asserted. `rate_bounds_clamp_events` was referenced by no test, so
  the whole `respond_error` collapse rested on review attention. The second pins the
  *placement* of `clamped_rate()` below the binding block, previously prose only.
- `deposit_refusal_warn_reports_exactly_what_it_swallowed` — the throttle's atomics.
  The suppressed count is the feature and every part of producing it was unverified.

Also: `top_up`'s missing-event fallback now reads `getChannel` instead of guessing
the requested amount — the funds are escrowed by then, so an `eth_call` is cheap,
and the state that triggers it ("our ABI is wrong") is the worst one in which to
guess. Its `log_decode` filters on the emitting address, since `topUp` transfers
before it emits and this function's own premise is a token that misbehaves during
transfer. `FeeOnTransferUSDC::setFeeBps` is bounded; the vacuous post-revert assert
is replaced with one that can fail; the top-up leg gained the balance anchor the
open leg had. Extracting `resolve_top_up_credit` and `log_top_up_outcome` keeps
`top_up` under the complexity limit — the lint was right that the fallback deserved
its own function.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
thiras added a commit that referenced this pull request Jul 30, 2026
The #1516 deposit gate runs on the serve path, which a cache miss reaches only
*after* the fill ladder. `try_range_pull_through` and `try_local_populate` front
the operator's own origin egress, and `try_pull_through`'s `cache.populate` walks
the paid `Peer` origin and fronts real upstream USDC — all three gated on channel
ownership via `pull_authorized`, none on solvency. So a dust-deposit channel could
name N absent hashes, make the operator pay for each, and be refused afterwards.
The client gained nothing (#1516 closed the free-egress half) but the bill was
real, and the rising `insufficient_deposit` counter read as "the guard is working"
while meaning the opposite.

Adds a pre-spend floor above every tier. The channel is already resolved above the
ladder for the ADR-011 funder gate (`dispatch.rs`, whose own comment argues
"resolving the channel early is a `HashMap` lookup, so the cost is nil") — the
`Arc` was simply being dropped, so this holds it rather than taking the map lock
again.

**Placed in the miss arm, not at the funder gate.** The serve path's ceiling is
`min(credit_window, aligned_span(..., total_bytes))`, and `total_bytes` is
unknowable before a fill. A gate above the availability check would therefore have
to drop the span cap, making it strictly stricter than the serve gate — which
refuses funded requests. Two existing tests pin exactly that: a 256 KiB blob on a
5-unit channel, and a resumed tail on a 5-unit channel. The second matters most:
`decdn fetch` treats a refused resume as a possibly-stale partial, rewinds to zero
and re-pays for the whole blob, so mispricing a resume doubles a user's bill.

**The floor is deliberately weak** — one credit window, "can this channel pay for
anything at all" — so it catches insolvency without pre-judging a small request.
`window.rs` keeps its stricter ceiling. The honest relationship, stated at the call
site: `DEFAULT_PULL_AHEAD_BYTES` is exactly one interval, so at default settings
the two compute the same number and the window guard is redundant; it earns its
place only once `max_blob_size_bytes` is finite. Residual, documented in the ADR
and CHANGELOG rather than papered over: a channel funded to exactly one window can
still trigger a whole-blob buffered pull costing more than it can repay, because
that tier is bounded by the cache engine's separate `max_blob_mb`, not by anything
the handler prices.

**`respond_error` now takes the request's price as a required argument.** The floor
needs the rate and then falls through into the ladder, whose miss arms refuse — and
`respond_error` used to compute the rate itself, so that fall-through would
double-count `rate_bounds_clamped` and double-log: the #1518 bug one layer up.
Rather than fix it by discipline across 21 call sites, the rate-recomputing wrapper
is deleted and the explicit one promoted, so `serve_stream` holds the crate's only
production `clamped_rate()` call and refusing without having priced the request
exactly once is unrepresentable. `serve_via_window_pull_through` takes the rate as
a parameter for the same reason — it was recomputing it, so that path
double-counted on every refusal today.

The pricing block sits *below* the binding block deliberately: the exits above it
(stream-cap shed, cooperative close, malformed binding) never sign anything, and
pricing them would meter a clamp for a request that never quoted a rate.

Tests, both confirmed to fail under an injected mutant:
- `underfunded_channel_never_reaches_the_paid_pull` — `hits == 0` is the acceptance
  criterion; the `cache_miss_total 0` assertion is what proves the refusal came
  from the floor rather than from the fill missing.
- `funded_channel_still_reaches_the_paid_pull` — the boundary control. Without it,
  tightening the floor or flipping `<` to `<=` would break nothing.

`window_pull_through_insufficient_deposit_refuses_before_pulling` had its deposit
raised 1 -> 100. At 1 the new floor fires first and the test keeps passing while
silently no longer covering `window.rs`'s guard; at 100 it clears the floor (10)
but not the 64 MiB blob ceiling (640). Verified by disabling that guard and
watching the test fail.

Closes #1519

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
thiras added a commit that referenced this pull request Jul 30, 2026
Four reviewers, and they converged on one theme: the mechanisms were sound, the
justifications around them were not. Eight factual claims were wrong and three doc
comments were attached to the wrong item. Two were genuine bugs.

**Bugs**

The floor priced a bounded range at a whole credit window even though `byte_len` is
right there. At stock config that window is 8 MiB (`DEFAULT_CREDIT_WINDOW_BYTES`
over a 4 MiB `DEFAULT_VOUCHER_INTERVAL_MB`), so a client funded for a 16 KiB range
was served warm and refused cold — and `decdn fetch` reads a refused resume as a
possibly-stale partial, rewinds to zero and re-pays for the whole blob. The floor
now caps by `aligned_span` when the request bounds itself, which is exactly the
argument used against hoisting it above the availability check in the first place.

`decdn channel top-up` does not exist. `ChannelCommand` is
`List | CoopClose | Close | Settle | Clean | Open`, so the new hint sent users to
clap's "unrecognized subcommand" — worse than the opaque `NotFound` it replaced.
And the CLI's estimate used the *protocol's* 1 MiB interval against the node's
8 MiB floor, so it under-detected by 8x and stayed silent across exactly the
headroom band a stock node refuses in. Both fixed; the message is now a lower bound
phrased as a possibility, and both causes attach instead of the first winning.

**Wrong claims, all corrected**

- "a merely small request is not pre-judged" and the CHANGELOG's "could not have
  completed the transfer either way" — false at stock config, where the floor is
  8 MiB. The residual is now stated rather than denied.
- "`DEFAULT_PULL_AHEAD_BYTES` is exactly one interval" — it is 1 MiB against a
  4 MiB default interval. The conclusion held, but via `window.rs`'s
  `.max(credit_window(..))` term, not the stated premise.
- "earns its place only once `max_blob_size_bytes` is finite" — `pull_ahead_bytes`
  is validated against `max_unrecouped_leech_bytes`, never the window, and a 1 MiB
  blob cap under an 8 MiB window makes that guard *weaker* than the floor.
- "every exit above this point returns without signing anything" — the cooperative
  close signs an EIP-712 waiver. It carries no rate, which is what actually matters.
- "`_advanceClaimWatermark` would revert at `withdraw`/`settleChannel`" —
  `settleChannel` never calls it, and the seller refuses off-chain via
  `stage_voucher` long before. The real harm is buyer-side: the inflated row
  suppresses auto-refill and compounds with every top-up.
- "nothing pinned that they export at zero … read `(no data)`" — those four
  counters always exported; what was missing was the assertion.
- "same technique as `MaliciousERC20`" — shared hook, not shared technique; that
  one is a reentrancy mock.
- "a property the compiler checks" — it stops implicit recomputation; a caller can
  still pass a wrong value. Now says what it actually buys.
- `blockchain.event_poll_interval_sec` → `_ms`; the panel described `cache_miss` as
  "not availability" while plotting it; `Overloaded` is peer backpressure, not the
  local problem the counter's doc implied.

**Three orphaned doc comments.** New items were inserted between an existing doc
block and the item it documented, so the block re-anchored and the original was left
bare. `credit_window` — cited by three other comments and called by the new floor —
ended up with no doc at all, its deadlock-freedom rationale heading a const. Nothing
catches this: both readings compile and rustdoc sees every item as documented.

**Four tests, each verified against an injected mutant**

- `spent_out_channel_never_reaches_the_paid_pull` — the `last_amount` term. A mutant
  reading `headroom = deposit` passed the *entire* suite before this. A spent-out
  channel is the production shape; a dust channel is the adversarial one, and only
  the latter was covered.
- `a_refused_request_clamps_the_rate_exactly_once` and
  `a_request_rejected_before_pricing_does_not_clamp_the_rate` — #1518's invariant,
  which nothing asserted. `rate_bounds_clamp_events` was referenced by no test, so
  the whole `respond_error` collapse rested on review attention. The second pins the
  *placement* of `clamped_rate()` below the binding block, previously prose only.
- `deposit_refusal_warn_reports_exactly_what_it_swallowed` — the throttle's atomics.
  The suppressed count is the feature and every part of producing it was unverified.

Also: `top_up`'s missing-event fallback now reads `getChannel` instead of guessing
the requested amount — the funds are escrowed by then, so an `eth_call` is cheap,
and the state that triggers it ("our ABI is wrong") is the worst one in which to
guess. Its `log_decode` filters on the emitting address, since `topUp` transfers
before it emits and this function's own premise is a token that misbehaves during
transfer. `FeeOnTransferUSDC::setFeeBps` is bounded; the vacuous post-revert assert
is replaced with one that can fail; the top-up leg gained the balance anchor the
open leg had. Extracting `resolve_top_up_credit` and `log_top_up_outcome` keeps
`top_up` under the complexity limit — the lint was right that the fallback deserved
its own function.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
thiras added a commit that referenced this pull request Jul 30, 2026
…r, observability, received-delta coverage (#1526)

* fix(node): refuse an underfunded channel before any fill tier spends

The #1516 deposit gate runs on the serve path, which a cache miss reaches only
*after* the fill ladder. `try_range_pull_through` and `try_local_populate` front
the operator's own origin egress, and `try_pull_through`'s `cache.populate` walks
the paid `Peer` origin and fronts real upstream USDC — all three gated on channel
ownership via `pull_authorized`, none on solvency. So a dust-deposit channel could
name N absent hashes, make the operator pay for each, and be refused afterwards.
The client gained nothing (#1516 closed the free-egress half) but the bill was
real, and the rising `insufficient_deposit` counter read as "the guard is working"
while meaning the opposite.

Adds a pre-spend floor above every tier. The channel is already resolved above the
ladder for the ADR-011 funder gate (`dispatch.rs`, whose own comment argues
"resolving the channel early is a `HashMap` lookup, so the cost is nil") — the
`Arc` was simply being dropped, so this holds it rather than taking the map lock
again.

**Placed in the miss arm, not at the funder gate.** The serve path's ceiling is
`min(credit_window, aligned_span(..., total_bytes))`, and `total_bytes` is
unknowable before a fill. A gate above the availability check would therefore have
to drop the span cap, making it strictly stricter than the serve gate — which
refuses funded requests. Two existing tests pin exactly that: a 256 KiB blob on a
5-unit channel, and a resumed tail on a 5-unit channel. The second matters most:
`decdn fetch` treats a refused resume as a possibly-stale partial, rewinds to zero
and re-pays for the whole blob, so mispricing a resume doubles a user's bill.

**The floor is deliberately weak** — one credit window, "can this channel pay for
anything at all" — so it catches insolvency without pre-judging a small request.
`window.rs` keeps its stricter ceiling. The honest relationship, stated at the call
site: `DEFAULT_PULL_AHEAD_BYTES` is exactly one interval, so at default settings
the two compute the same number and the window guard is redundant; it earns its
place only once `max_blob_size_bytes` is finite. Residual, documented in the ADR
and CHANGELOG rather than papered over: a channel funded to exactly one window can
still trigger a whole-blob buffered pull costing more than it can repay, because
that tier is bounded by the cache engine's separate `max_blob_mb`, not by anything
the handler prices.

**`respond_error` now takes the request's price as a required argument.** The floor
needs the rate and then falls through into the ladder, whose miss arms refuse — and
`respond_error` used to compute the rate itself, so that fall-through would
double-count `rate_bounds_clamped` and double-log: the #1518 bug one layer up.
Rather than fix it by discipline across 21 call sites, the rate-recomputing wrapper
is deleted and the explicit one promoted, so `serve_stream` holds the crate's only
production `clamped_rate()` call and refusing without having priced the request
exactly once is unrepresentable. `serve_via_window_pull_through` takes the rate as
a parameter for the same reason — it was recomputing it, so that path
double-counted on every refusal today.

The pricing block sits *below* the binding block deliberately: the exits above it
(stream-cap shed, cooperative close, malformed binding) never sign anything, and
pricing them would meter a clamp for a request that never quoted a rate.

Tests, both confirmed to fail under an injected mutant:
- `underfunded_channel_never_reaches_the_paid_pull` — `hits == 0` is the acceptance
  criterion; the `cache_miss_total 0` assertion is what proves the refusal came
  from the floor rather than from the fill missing.
- `funded_channel_still_reaches_the_paid_pull` — the boundary control. Without it,
  tightening the floor or flipping `<` to `<=` would break nothing.

`window_pull_through_insufficient_deposit_refuses_before_pulling` had its deposit
raised 1 -> 100. At 1 the new floor fires first and the test keeps passing while
silently no longer covering `window.rs`'s guard; at 100 it clears the floor (10)
but not the 64 MiB blob ceiling (640). Verified by disabling that guard and
watching the test fail.

Closes #1519

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

* feat(node): make the insufficient-deposit refusal observable

The refusal emitted no log, and `grep monitoring/ docs/` for
`insufficient_deposit` returned nothing — no alert, no panel, no runbook entry.
"The metric is the signal" was the reasoning when the gate landed, and it does not
hold when nothing watches the metric: it meant "an operator who already suspects
this specific cause and knows the series name can query it by hand." Meanwhile the
wire code is deliberately lossy (`InsufficientDeposit` collapses to `NotFound`
with six other reasons so a prober cannot map channel balances), so a node could
refuse every paying client in silence.

**A throttled warn, not a per-refusal one and not a latch.** Warning per refusal is
farmable into log spam by exactly the abuse the gate guards against; a one-shot
latch — the only existing precedent (`log_per_source_poison`) — is wrong in the
other direction, because this fires legitimately and repeatedly, so a latched
warning is as invisible as none. So: one `warn!` per 5 minutes carrying the count
it suppressed, plus an unconditional `debug!` so a support ticket is answerable.
All three deposit guards emit it.

Unkeyed deliberately. A per-channel `governor` limiter was the obvious reach — it is
already a dependency and the vocabulary the request limiters speak — but keying it
means an unboundedly growing map, and the in-tree cost of owning one is
`retain_recent` sweeps, split single-flight prune guards, and two metrics per map.
That is a lot of machinery for a log line, and the aggregate is what answers the
triage question anyway. The window arithmetic is a pure function so it is tested
without sleeping, including the backwards-clock case (which suppresses rather than
spams — the safe direction for a log gate).

**The two causes are the point.** One unlabeled counter cannot separate a client
running dry (no action) from this node's chain watcher lagging an on-chain
`ChannelToppedUp` (funded clients being turned away, check RPC health). Opposite
remedies, identical signal. The log line, the alert description and the runbook all
say so, and the runbook gives the procedure that distinguishes them: compare
`decdn node channels` against `PaymentChannel.getChannel`.

**Buyer side.** `RefusalVerdict::Transient` bumped no counter at all, so a node
whose own deposit cannot buy anything saw every pull refused with nothing in its
telemetry — a seller refusing our channel signs `NotFound`, indistinguishable from
an honest miss. Adds `node_pull_refused_unattributable`; a rate approaching
`node_pull_refused` means "nobody will serve me", which is local.

**The CLI hint was pointing at the wrong fix.** `annotate_unbound_cache_miss`
hard-coded one cause for a `NotFound` ("set `blockchain.capacity_bond_address`"),
so an unbound fetch against an underfunded channel was told to set a config field
that would not help. It now checks the deposit case first, because that is the one
it can *prove* rather than guess: the signed refusal carries the node's quoted
rate, and the channel's own deposit and paid amount are in scope, so the shortfall
is arithmetic. It reasons only about our own channel from data the node already
sent, so the reject-reason collapse is untouched.

Two things found while doing this, worth flagging rather than burying:

- I nearly shipped a stale metric name. The first draft of the alert divided by
  `decdn_serve_stream_requests_total`, which the exporter does not emit — the exact
  bug #1513 is open about. There is no serve-attempt counter at all, so the alert
  is a raw rate and says why.
- The *existing* `DecdnHighStreamErrorRate` alert is built on
  `decdn_streams_failed_total` and `decdn_streams_completed_total`, neither of
  which this exporter emits. That rule cannot fire. Left alone as #1513's scope,
  but called out in a comment beside the new alert so nobody copies its denominator.

Also completes `serve_stream_rejected_counters_start_at_zero_and_increment_per_reason`,
which listed 10 of the 13 reject counters — the four missing ones had nothing
pinning that they export at zero, so a dashboard querying them read `(no data)`.

Closes #1520

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

* test(contracts): assert the received-delta accounting with a fee-on-transfer token

`openChannel` and `topUp` credit a measured balance delta rather than the requested
amount, and both carry a comment explaining that this is what stops a
fee-on-transfer proxy over-stating a channel against the shared USDC pool. Nothing
tested it: the suite had no fee-bearing token, so the delta arithmetic and both
post-transfer `ZeroAmount` guards were unexercised on every path. Three comments
asserting a protection with nothing behind them.

Adds an inline `FeeOnTransferUSDC` (overriding OZ v5's `_update`, the same technique
as `MaliciousERC20` in `TestnetFaucet.t.sol`) and a second test contract —
`PaymentChannelTest` hard-codes `new MockUSDC()` and types its `usdc` field
concretely, so there is no seam to inject a token through. Inline rather than
`test/mocks/`, matching the 16-of-30 majority; `mocks/` holds cross-file interface
stand-ins and the one token Rust needs as a standalone artifact.

Five assertions. The valuable ones are not the reverts but the deltas:
`ch.deposit == received` (**not** `== requested`) on open and top-up, and
`ChannelOpened.deposit` carrying the same value, since off-chain buyers build their
local row from that event. The 100%-burn cases reach the post-transfer `ZeroAmount`
guards, which no test could previously reach at all — the pre-transfer guard cannot
catch them because the requested amount is non-zero.

The fixture arms the fee only AFTER funding and approving the client. Funding at a
100% burn leaves the client with nothing, and the revert under test becomes
`ERC20InsufficientBalance` instead of the guard — which is exactly how the first
draft failed.

**Contract behaviour is unchanged.** A partial shave is credited as received, not
reverted. That is now an asserted decision rather than an unexercised path.
Reverting would hard-code "the settlement token must never be fee-bearing" into the
contract — a policy call larger than the test gap that prompted this, and one that
runs against the two commits that just deleted the on-chain minimum deposit.

Also fixes the Rust mirror of the same accounting, which was wrong in both legs:
`open_channel` recorded its `deposit` argument while already taking `channelId` and
`expiresAt` from `ChannelOpened`, and `top_up` never decoded `ChannelToppedUp` at
all. Under a fee-bearing token both would put the over-statement in the buyer's own
row — vouchers climbing past the on-chain deposit, `_advanceClaimWatermark`
reverting at settlement, the seller stranded with delivered bytes it cannot claim.
Both now read the credited value; `top_up` falls back to the requested amount with a
`warn!` if the event is missing, since the funds are already escrowed by then. The
comment asserting "USDC is not fee-on-transfer, so the local `+= additional`
matches" is gone, because the code no longer relies on it.

Not reachable today: the USDC address is immutable at deployment and mainnet USDC is
not fee-on-transfer. This is defensive depth.

Closes #1521

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

* fix: address the multi-agent review of #1519/#1520/#1521

Four reviewers, and they converged on one theme: the mechanisms were sound, the
justifications around them were not. Eight factual claims were wrong and three doc
comments were attached to the wrong item. Two were genuine bugs.

**Bugs**

The floor priced a bounded range at a whole credit window even though `byte_len` is
right there. At stock config that window is 8 MiB (`DEFAULT_CREDIT_WINDOW_BYTES`
over a 4 MiB `DEFAULT_VOUCHER_INTERVAL_MB`), so a client funded for a 16 KiB range
was served warm and refused cold — and `decdn fetch` reads a refused resume as a
possibly-stale partial, rewinds to zero and re-pays for the whole blob. The floor
now caps by `aligned_span` when the request bounds itself, which is exactly the
argument used against hoisting it above the availability check in the first place.

`decdn channel top-up` does not exist. `ChannelCommand` is
`List | CoopClose | Close | Settle | Clean | Open`, so the new hint sent users to
clap's "unrecognized subcommand" — worse than the opaque `NotFound` it replaced.
And the CLI's estimate used the *protocol's* 1 MiB interval against the node's
8 MiB floor, so it under-detected by 8x and stayed silent across exactly the
headroom band a stock node refuses in. Both fixed; the message is now a lower bound
phrased as a possibility, and both causes attach instead of the first winning.

**Wrong claims, all corrected**

- "a merely small request is not pre-judged" and the CHANGELOG's "could not have
  completed the transfer either way" — false at stock config, where the floor is
  8 MiB. The residual is now stated rather than denied.
- "`DEFAULT_PULL_AHEAD_BYTES` is exactly one interval" — it is 1 MiB against a
  4 MiB default interval. The conclusion held, but via `window.rs`'s
  `.max(credit_window(..))` term, not the stated premise.
- "earns its place only once `max_blob_size_bytes` is finite" — `pull_ahead_bytes`
  is validated against `max_unrecouped_leech_bytes`, never the window, and a 1 MiB
  blob cap under an 8 MiB window makes that guard *weaker* than the floor.
- "every exit above this point returns without signing anything" — the cooperative
  close signs an EIP-712 waiver. It carries no rate, which is what actually matters.
- "`_advanceClaimWatermark` would revert at `withdraw`/`settleChannel`" —
  `settleChannel` never calls it, and the seller refuses off-chain via
  `stage_voucher` long before. The real harm is buyer-side: the inflated row
  suppresses auto-refill and compounds with every top-up.
- "nothing pinned that they export at zero … read `(no data)`" — those four
  counters always exported; what was missing was the assertion.
- "same technique as `MaliciousERC20`" — shared hook, not shared technique; that
  one is a reentrancy mock.
- "a property the compiler checks" — it stops implicit recomputation; a caller can
  still pass a wrong value. Now says what it actually buys.
- `blockchain.event_poll_interval_sec` → `_ms`; the panel described `cache_miss` as
  "not availability" while plotting it; `Overloaded` is peer backpressure, not the
  local problem the counter's doc implied.

**Three orphaned doc comments.** New items were inserted between an existing doc
block and the item it documented, so the block re-anchored and the original was left
bare. `credit_window` — cited by three other comments and called by the new floor —
ended up with no doc at all, its deadlock-freedom rationale heading a const. Nothing
catches this: both readings compile and rustdoc sees every item as documented.

**Four tests, each verified against an injected mutant**

- `spent_out_channel_never_reaches_the_paid_pull` — the `last_amount` term. A mutant
  reading `headroom = deposit` passed the *entire* suite before this. A spent-out
  channel is the production shape; a dust channel is the adversarial one, and only
  the latter was covered.
- `a_refused_request_clamps_the_rate_exactly_once` and
  `a_request_rejected_before_pricing_does_not_clamp_the_rate` — #1518's invariant,
  which nothing asserted. `rate_bounds_clamp_events` was referenced by no test, so
  the whole `respond_error` collapse rested on review attention. The second pins the
  *placement* of `clamped_rate()` below the binding block, previously prose only.
- `deposit_refusal_warn_reports_exactly_what_it_swallowed` — the throttle's atomics.
  The suppressed count is the feature and every part of producing it was unverified.

Also: `top_up`'s missing-event fallback now reads `getChannel` instead of guessing
the requested amount — the funds are escrowed by then, so an `eth_call` is cheap,
and the state that triggers it ("our ABI is wrong") is the worst one in which to
guess. Its `log_decode` filters on the emitting address, since `topUp` transfers
before it emits and this function's own premise is a token that misbehaves during
transfer. `FeeOnTransferUSDC::setFeeBps` is bounded; the vacuous post-revert assert
is replaced with one that can fail; the top-up leg gained the balance anchor the
open leg had. Extracting `resolve_top_up_credit` and `log_top_up_outcome` keeps
`top_up` under the complexity limit — the lint was right that the fallback deserved
its own function.

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

* fix: correct the CLI hint's whitespace and five stale CHANGELOG claims

Three review comments, all correct. The first was worse than reported and the
other two exposed a pattern worth naming.

**The CLI hint printed literal whitespace runs.** The message was assembled with
single backslashes inside a generator heredoc, so the *generator* consumed them as
its own line continuations — stripping the newlines but leaving the indentation
inside the Rust string literal. The runtime output contained 18-space runs
("below the AT LEAST                  ~250000"). Rewritten with real Rust `\`
continuations and verified by reconstructing the collapsed literal: zero
double-space runs remain. The sibling message in the same function was already
correct because it used escaped backslashes, which is what made the bug invisible
to inspection.

Also dropped the "AT LEAST ~" construction the reviewer flagged as a grammatical
glitch; the lower-bound caveat now reads as a clause rather than shouted adjectives.

**Two CHANGELOG claims contradicted the code**, both flagged:

- "the one-clamp-per-request invariant something the compiler enforces" — it is
  not. Taking the price as a parameter stops `respond_error` recomputing it
  *implicitly*, which is the shape the bug took; a caller can still pass an inline
  `clamped_rate()` or the wrong value. What holds it is the single call site plus
  the two new tests. This is the same overstatement the review round corrected in
  `wire.rs`'s doc — I fixed the code comment and left this copy standing.
- `top_up`'s fallback chain — it reconciles against `getChannel` first and only
  credits the requested amount if that read *also* fails, at `error!` rather than
  `warn!`. The entry described the pre-review behaviour.

**Three more of the same class the reviewer did not reach.** Every one is a claim I
corrected in a code comment during the review round while leaving the CHANGELOG
copy stale, which is the actual defect here — not the individual sentences:

- `_advanceClaimWatermark` reverting at `withdraw`/`settleChannel`. `settleChannel`
  never calls it, and the seller refuses off-chain via `stage_voucher` long before.
  The real harm is buyer-side: the inflated row makes the auto-refill fire late or
  short, and the drift compounds with every top-up.
- "the USDC address is immutable at deployment and mainnet USDC is not
  fee-on-transfer" conflated address with behaviour. Real USDC is an upgradeable
  proxy — the immutable *address* is precisely why a behaviour change could not be
  escaped, which is the point rather than an aside.
- the cache engine's "separate `max_blob_mb`" — not separate; engine and handler
  both derive from `cache.max_blob_size_mb`, and what is true is only that the
  engine is the one bounding that tier.

Verification: `cargo nextest run --workspace` 2666 passed, clippy `-D warnings`
clean, `cargo fmt --check` clean, `decdn-cli` 385 passed. One full-suite run hit
`probe_rate_limit_returns_rate_limited_close_code`; it passes 6/6 in isolation and
neither `probe_loopback.rs` nor any probe rate-limit source file is in this
branch's diff, so it is a pre-existing timing flake under parallelism rather than
a regression here.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
alpergundogdu added a commit that referenced this pull request Jul 31, 2026
A reactive mid-fetch top-up lands on-chain, then the client immediately
reconnects to resume at the paid frontier. The node's settlement watcher may
not yet have applied the `ChannelToppedUp` event, so its pre-serve deposit
gate (ADR 003 / #1518, which checks headroom at open time) still sees the
pre-top-up deposit and refuses the resumed open. That refusal collapses to
`StreamError::NotFound`, which the CLI misread as a stale partial, rewound to
zero, hit the same stale gate, and failed with a misleading message.

Wait out the watcher: after a top-up, an open-time `NotFound` at the resumed
offset is treated as transient and the open is retried with short backoff
(bounded by MAX_TOPUP_SETTLE_WAITS) before the stale-partial rewind. Retrying
an open is money-safe — it sends no vouchers and does not move `byte_offset` —
so the no-double/under-pay guarantee is untouched.

Exposed by merging main's open-time pre-serve deposit floor (#1518): pre-#1518
the shortfall surfaced mid-stream after a delay that let the watcher catch up.
The multi-interval reactive-top-up e2e test is the regression guard.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
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.

fix(node): refuse before serving when deposit can't cover the next interval refactor(contracts): remove minDeposit floor

3 participants