Repository navigation
fix: close two money-path guards that had no correct branch (#1532, #1495) - #1538
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Free Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (24)
WalkthroughThe changes add signed cooperative-close watermark reconciliation across the protocol, client, node, CLI, metrics, and integration tests. They also enforce buyback slippage and zero-band constraints, update deployment documentation and gas snapshots, and increase the E2E timeout budget. ChangesCooperative close reconciliation
Buyback guard validation
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant Node
participant BuyerStore
Client->>Node: request cooperative-close authorization
Node-->>Client: return signed watermark and echo
Client->>Client: verify exact settlement tuple
Client->>BuyerStore: persist reconciled watermark
Client->>Node: submit cooperative close
Note 🎁 Summarized by CodeRabbit FreeYour 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 |
Gas snapshotNo gas changes vs base. |
Contracts coverageLine coverage: 89.89% (2614/2908 lines) |
Coverage reportTotal: 80.30% (was 80.25%, ▲ +0.05%) — 54931/68403 lines
History
|
There was a problem hiding this comment.
🟡 Not ready to approve
The CHANGELOG incorrectly states the healed watermark is carried by CooperativeCloseOutcome variants rather than being surfaced via the new out-param API, and should be corrected to match the implementation.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
This review doesn't count toward merge requirements. Sign up for the private preview to control whether Copilot approvals count.
Pull request overview
This PR closes two “money-path guard” gaps across the Solidity buyback burner and the Rust payments cooperative-close flow: (1) prevents governance/deploy config from silently disabling buyback MEV protections or wedging buybacks, and (2) enables cooperative-close to reconcile when a client’s persisted watermark lags the node’s state by verifying an echoed client voucher signature via a non-wire-breaking trailing extension.
Changes:
- Enforce
slippageBpsceiling and reject a zeromaxBuybackAmountband inGuardedBuybackBurner, with updated tests/docs and retained deploy-time fail-fast checks. - Add
CooperativeCloseAuthExt { last_signature }as trailing bytes (two-phase framing) and update node/client logic to use it to safely reconcile over-claim scenarios. - Add metrics + persistence for reconciled watermarks, an anvil-backed e2e journey, and adjust CI timeout/docs/ADRs accordingly.
File summaries
| File | Description |
|---|---|
| crates/protocol/tests/snapshots/public_api__public_api.snap | Updates protocol public API snapshot for the new cooperative-close extension helpers/types. |
| crates/protocol/src/lib.rs | Re-exports CooperativeCloseAuthExt and new encode/parse helpers from the protocol crate root. |
| crates/protocol/src/client.rs | Introduces CooperativeCloseAuthExt, plus encode/parse helpers for two-phase cooperative-close auth payloads and associated tests. |
| crates/node/tests/client_loopback.rs | Extends loopback tests to assert the node emits the trailing cooperative-close auth extension when available. |
| crates/node/src/metrics.rs | Adds counters for “no echo” cooperative-close auth and watermark-heal reconciliations, plus recorder wiring/tests. |
| crates/node/src/handlers/client/wire.rs | Adds write_payload to frame already-encoded payloads (base message + trailing extension bytes). |
| crates/node/src/handlers/client/voucher.rs | Attaches CooperativeCloseAuthExt echo when possible and uses encode_cooperative_close_auth to write the two-phase payload. |
| crates/node/src/handlers/client/mod.rs | Plumbs the new protocol items into the handler module scope for submodules. |
| crates/node/src/buyer_channel.rs | Persists reconciled watermarks (best-effort) and meters when reconciliation occurred. |
| crates/e2e/tests/coop_close_watermark_reconcile.rs | Adds an anvil-backed e2e verifying a lagging client watermark can still cooperative-close and settle at node state. |
| crates/e2e/src/client.rs | Exposes fixture signer/endpoint accessors needed by the new cooperative-close e2e journey. |
| crates/client-pull/src/lib.rs | Extracts shared signature verification helper voucher_signed_by and reuses it in watermark resume logic. |
| crates/client-pull/src/cooperative_close.rs | Adds reconciliation branch using echoed last_signature, parses trailing extension bytes, and reports healed watermark via out-param. |
| crates/cli/src/commands/channel.rs | Persists a reconciled watermark on every path (including errors) before inspecting cooperative-close outcome. |
| contracts/test/GenesisBuybackActivation.t.sol | Updates guard-band dead-case commentary to reflect new contract-level guard while pinning script fail-fast behavior. |
| contracts/test/BuybackVenueLib.t.sol | Updates documentation/comments for the dead guard-band case and continued pre-broadcast guard. |
| contracts/test/BuybackBurnerBalancerV3.t.sol | Adds coverage for slippage ceiling and zero-max buyback band at both constructor and setter entry points. |
| contracts/src/GuardedBuybackBurner.sol | Enforces SLIPPAGE_CEILING and rejects maxBuybackAmount == 0 in constructor and setter (BuybackBandDead). |
| contracts/script/lib/BuybackVenueLib.sol | Retains deploy-time GuardBandDead fail-fast with updated rationale now that the contract also enforces it. |
| contracts/script/DeployProtocol.s.sol | Documents new bounds for buyback env vars (MAX_BUYBACK_AMOUNT non-zero, SLIPPAGE_BPS ceiling). |
| contracts/script/ActivateBuyback.s.sol | Same env-var bound documentation updates for the activation script. |
| contracts/.gas-snapshot | Updates gas snapshot to reflect new tests and minor runtime changes. |
| CHANGELOG.md | Adds release notes for both fixes (payments reconciliation + buyback guard bounds). |
| adr/018-liquidity-strategy.md | Updates ADR parameter table + narrative to specify non-zero max buyback and slippage ceiling bounds. |
| adr/005-protocol.md | Documents the two-phase cooperative-close auth extension as non-wire-breaking schema evolution. |
| adr/003-payments.md | Documents the cooperative-close reconciliation mechanism and its security properties. |
| .github/workflows/ci.yml | Raises anvil-e2e job timeout to account for the additional e2e journey inventory. |
Review details
- Files reviewed: 27/27 changed files
- Comments generated: 1
- Review effort level: Lite
We're testing this review assessment. Please use 👍 or 👎 to tell us if it's correct.
…1495) Both are gaps in shipped surfaces where a guard on a money path is missing the branch it needs — one fails open, the other fails closed with no way out. #1532 — GuardedBuybackBurner accepted a slippage tolerance that disables the MEV defense, and a buyback band that can never execute. `slippageBps` was rejected only at `>= 100%`, so 9999 scaled the TWAP floor to 0.01% of fair value: the whole ADR 018 MEV stack off, with no revert, no event, and a green deploy. It is now bounded at SLIPPAGE_CEILING = 1000 (10%, against a 200 bps default) at the constructor and setSlippageTolerance, mirroring the [1%, 30%] bound epochLiquidityCapFraction already carried at both sites. Separately, `maxBuybackAmount == 0` constructed cleanly then reverted AboveMaxBuyback on every call forever — a burner accruing the FeeRouter's buyback bucket with no way to spend it — and governance could walk the band to 0/0 in two calls, since a zero ceiling is not an *inverted* band once the floor is also zero. Both entry points now revert BuybackBandDead. The deploy-time BuybackVenueLib.GuardBandDead is retained as a pre-broadcast fail-fast. Both bounds are stated in the ADR 018 parameter table, which is the source of truth for them. Shipped defaults satisfy both, so no deployment path changes. #1495 — a cooperative close now reconciles when the client's watermark lags the node's, instead of stranding the channel. The over-claim refusal in prepare_close is load-bearing: without it a provider could ask the client to sign away up to the full deposit. But it had no reconciliation branch, so a client that signed vouchers it did not durably persist before an unclean exit could never settle, and its deposit stayed locked until expiry. The node now echoes the client's OWN last-accepted voucher signature alongside the waiver, and the client settles at the node's state only when that signature recovers to its own voucher-signing key over exactly the tuple being settled. Anything else keeps the refusal. This strengthens rather than relaxes the check: only the client could have produced that signature, so a tuple that verifies is one it already committed to — strictly stronger evidence than the local record it replaces. Same primitive the fetch path uses to self-heal a watermark (WatermarkBundle.last_signature, #1481); the recovery core is extracted as `voucher_signed_by` and shared rather than reimplemented. Not wire-breaking. The echo rides as a CooperativeCloseAuthExt trailing extension (the two-phase pattern StreamRequest/StreamRequestExt uses), so CooperativeCloseAuth is unchanged on the wire and mixed-version peers interoperate both ways: an old client ignores the trailing bytes, a new client against an old node reads no echo, and both keep the pre-existing refusal. No ALPN bump; operators can hot-upgrade across it. CooperativeCloseOutcome::Settled/Reverted now carry the healed watermark so the buyer store is advanced before the channel row is dropped, and so a closeChannel fallback submits the voucher actually signed. Verification: forge build --deny warnings / test / fresh gas snapshot, slither, aderyn, solhint; cargo fmt, clippy --all-targets -D warnings, 2691 workspace tests, doctests, rustdoc -D warnings; 28/28 anvil e2e including a new coop_close_watermark_reconcile journey that desyncs a real buyer against a live node and asserts the close settles at the node's state. Closes #1532 Closes #1495 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Five review agents; two disagreed on the most severe finding, so it was adjudicated against source. Corrections to my own work, in severity order. Accuracy — "deposit stranded until expiry" was wrong, and it was in an ADR. Repeated across six sites including adr/003-payments.md, which the repo treats as source of truth for money-path claims. The closeChannel -> dispute window -> settleChannel fallback exists and cooperative_close.rs documents it in the same file. Nothing was ever stranded: the client under-claims and recovers its deposit; it is the *provider* that must dispute to be made whole. Reworded to what actually happens — the one-transaction settle becomes unreachable and the fallback submits a voucher below what the client signed. Framing inherited from the issue text and propagated without checking. Two test files still asserted the burner does not check a zero band (BuybackVenueLib.t.sol, GenesisBuybackActivation.t.sol) — I rewrote that exact sentence in BuybackVenueLib.sol and missed both mirrors. CHANGELOG:679 stated the same in present tense, 200 lines from the new entry saying otherwise. Adjudicated: a dropped `reconciled` does NOT strand the proof. One agent claimed the node refuses to re-waive after `cooperative_close_signed`, making it one-shot; it does not — that flag gates delivery (dispatch.rs:697) and voucher acceptance (voucher.rs:150), not `handle_cooperative_close`, and `mark_cooperative_close_signed` early-returns Ok when already set. A repeat request re-derives the proof. Money was correct on every path. Fixed anyway, because dropping a proven value on two error legs is cheap to stop and the receipt-error leg is genuinely awkward: `get_receipt` failing does not mean the tx failed, so the chain can settle at the healed watermark while the store keeps the stale one. `reconciled` moves from duplicated enum fields to a `&mut Option<AuthorizedWatermark>` out-param written BEFORE the send, so every return path reports it — the same shape `stream_fetch_tracked` already uses for `progress`, and for the same reason. `CooperativeCloseOutcome` returns to three fieldless variants. `voucher_signed_by` now takes `&Voucher` (4 args, not 8) and the `#[allow(clippy::too_many_arguments)]` is gone. Its justification comment was factually wrong: it claimed a struct would be "a name that has no other use", but `decdn_incentive::Voucher` has exactly those five fields and was being constructed *inside* the function. `prepare_close` now builds one `settlement` voucher, proves that value, and signs that same value — so "what was verified" and "what is committed" are one value rather than two locals that agree. Adds `#[must_use]`. The over-claim refusal now distinguishes an absent echo from a hostile one; the operator's next action differs (upgrade/wait vs stop using this provider) and both previously read "carries no signature of ours". Metered two silent paths. The node's no-echo arm is not hypothetical: it is deterministic for schema-v1 store records, which never wrote the signature segment (channel_store.rs:259), and that is the oldest node population — the one most likely serving the clients #1495 exists for. Now warns and increments `decdn_cooperative_close_auth_no_echo_total`. A reconcile firing means our own durable store lost committed vouchers, so it is warn-level plus `decdn_buyer_reconcile_watermark_healed_total` rather than a debug line. Tests: `persist_reconciled` had none, and `advance_progress` takes three adjacent U256s in an order matching neither the struct nor the tuple used elsewhere — a transposition compiles and silently persists a wrong watermark. Three tests with distinct per-field values, plus the ChannelMismatch arm. Also a malformed-remainder test mirroring `parse_stream_request_ext`'s, and assertions pinning the two refusal messages apart. The e2e's journey 2 tested nothing it claimed: it closed an unknown channel id, short-circuiting before `prepare_close`, so the no-echo refusal was never exercised — while paying for a second buyer and a full anvil fetch the assertion never used. Cut; the header's fixture-sharing and coverage claims corrected. Runtime drops 26s -> 5.4s. ci.yml's anvil-e2e inventory said in terms that the bound needed raising before the next journey landed, and #1495 landed one. Inventory updated to 20 tests / 17 files / 269m and timeout-minutes 130 -> 160. Not taken: a SLIPPAGE_FLOOR. `slippageBps == 0` is degenerate but pre-existing (0 passed the old check too) and does not wedge "forever" as reported — it starves buybacks until spot beats the TWAP. ADR 018 now says it is not an operating point rather than silently blessing it via the stated range. Also not taken: the newtype refactors (VoucherSig, OwnVoucher, proof-carrying ProvenWatermark) — real improvements, but they rework shipped surfaces well beyond this fix. Verification: forge fmt/build --deny warnings/test/fresh snapshot/solhint; cargo fmt, clippy --all-targets -D warnings, 2695 workspace tests, rustdoc -D warnings, cargo deny, pre-commit. Anvil e2e green. anvil-e2e targets linted explicitly since CI omits that feature — zero findings in the touched files. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… is surfaced The bullet described the pre-review-pass API: `CooperativeCloseOutcome::Settled` and `Reverted` briefly carried a `reconciled` field, but the review pass moved it to a `&mut Option<AuthorizedWatermark>` out-param on `cooperative_close` so the error legs report it too, leaving the enum with three fieldless variants. The CHANGELOG was not updated with it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…loseAuth field, not an extension Pre-launch, so break the wire instead of negotiating. The client's last-accepted voucher signature (#1495 reconcile echo) moves from a separate CooperativeCloseAuthExt trailing extension into a last_signature field on CooperativeCloseAuth itself. Drops the two-phase machinery: the CooperativeCloseAuthExt struct, encode_cooperative_close_auth / parse_cooperative_close_auth_ext, and the remainder-parsing on both sides. The node now sends the auth via the ordinary write_message and the client reads it with a single decode_message. Semantics are unchanged — an empty last_signature means no echo and the client keeps its refusal; validate() checks both signature lengths. Co-Authored-By: Claude Opus 4.8 <[email protected]>
e79101a to
e2c70f2
Compare
Two gaps in shipped surfaces where a guard on a money path is missing the branch it needs — one fails open, the other fails closed with no way out. They are batched because that is the shared shape, not because they touch the same code.
#1532 —
GuardedBuybackBurneraccepted settings that disable the guardslippageBpswas rejected only at>= 100%, so9999scaled the TWAP floor to 0.01% of fair value: the whole ADR 018 MEV stack off, with no revert, no event, and a green deploy. Now bounded atSLIPPAGE_CEILING = 1000(10%, against a 200 bps default) at the constructor andsetSlippageTolerance, mirroring the[1%, 30%]boundepochLiquidityCapFractionalready carried at both sites.Separately,
maxBuybackAmount == 0constructed cleanly then revertedAboveMaxBuybackon every non-zero call — a burner accruing the FeeRouter's buyback bucket with no way to spend it — and governance could walk the band to0/0in two calls, since a zero ceiling is not an inverted band once the floor is also zero. Both entry points now revertBuybackBandDead.BuybackVenueLib.GuardBandDeadis retained as a pre-broadcast fail-fast so a mis-set env var still surfaces before the deploy transaction.Both bounds are stated in the ADR 018 parameter table, which is the source of truth for them. Shipped defaults (200 bps,
10_000e6) satisfy both, so no deployment path changes.#1495 — a cooperative close could not reconcile a lagging client watermark
The over-claim refusal in
prepare_closeis load-bearing: without it a provider could ask the client to sign away up to the full deposit. But it had no reconciliation branch, so a client that signed vouchers it did not durably persist before an unclean exit could not cooperatively close at all.Nothing was lost — the
closeChannel→ dispute window →settleChannelfallback remains — but the one-transaction settle was unreachable, and the fallback submits a voucher below what the client actually signed, underpaying the provider unless it watches the window and disputes.The node now echoes the client's own last-accepted voucher signature, and the client settles at the node's state only when that signature recovers to its own voucher-signing key over exactly the tuple being settled. Anything else keeps the refusal.
This strengthens rather than relaxes the check: only the client could have produced that signature, so a tuple that verifies is one it already committed to — strictly stronger evidence than the local record it replaces. Same primitive the fetch path uses to self-heal (
WatermarkBundle.last_signature, #1481); the recovery core is extracted asvoucher_signed_byand shared rather than reimplemented.Worth stating for review: the branch grants a hostile node nothing it did not already have. A verifying echo is a redeemable client voucher over that tuple — the node could already submit it via
closeChannel.Wire-breaking (pre-launch)
The echo is a new
last_signaturefield onCooperativeCloseAuthitself, not a trailing extension. The network is pre-launch, so there is no mixed-version population to preserve and the field is added directly rather than negotiated through a two-phase extension. This drops the whole two-phase apparatus that an earlier revision of this PR carried — theCooperativeCloseAuthExtstruct,encode_cooperative_close_auth/parse_cooperative_close_auth_ext, and the remainder-parsing on both sides — so the node sends the auth via the ordinarywrite_messageand the client reads it with a singledecode_message.last_signatureis empty when the node holds no stored signature for the channel, in which case the client keeps the pre-existing refusal;CooperativeCloseAuth::validatenow checks both signature lengths.Review pass
The second commit addresses a five-agent review of the first. Highlights, since they are corrections to my own work:
adr/003-payments.md. Untrue — the fallback exists andcooperative_close.rsdocuments it in the same file. Reworded to what actually happens.reconciledis recoverable. Adjudicated against source:cooperative_close_signedgates delivery and voucher acceptance, nothandle_cooperative_close, so a repeat request re-derives the proof. Money was correct on every path. Fixed anyway —reconciledis now a&mut Option<…>out-param written before the send, matchingstream_fetch_tracked'sprogress.voucher_signed_bynow takes&Voucher(4 args, not 8). Its#[allow(clippy::too_many_arguments)]justification was factually wrong —Voucherhas exactly those five fields and was constructed inside the function.persist_reconciledtests added (itsadvance_progresscall takes three adjacentU256s in an order matching neither the struct nor the tuple used elsewhere);ci.yml's anvil-e2e bound raised, which its own comment said was needed before the next journey landed.Deliberately not taken, with reasoning in the commit: a
SLIPPAGE_FLOOR(0is pre-existing and starves rather than wedges; ADR 018 now says it is not an operating point instead of silently blessing it), and the newtype refactors — real improvements, but they rework shipped surfaces well beyond this fix.Verification
forge fmt --check,FOUNDRY_PROFILE=ci forge build --sizes --deny warnings,forge test, fresh.gas-snapshot, slither, aderyn, solhint — checked by exit code.cargo fmt,clippy --all-targets -D warnings, 2695 workspace tests, doctests,rustdoc -D warnings,cargo deny,pre-commit.Anvil e2e green, including a new
coop_close_watermark_reconcilejourney that desyncs a real buyer against a live node and asserts the close settles at the node's state with the reported watermark matching the on-chainclaimedAmount. Theanvil-e2etargets were linted explicitly since CI omits that feature — zero findings in the touched files.Closes #1532
Closes #1495
🤖 Generated with Claude Code
Summary by CodeRabbit
Bug Fixes
Documentation