Repository navigation
feat(client-pull,cli): client-initiated cooperative close - #973
Conversation
The buyer/initiator half of cooperative close, on top of the provider waiver (#957) and the wire+EIP-712 foundation (#949). One settle, no 48h dispute window (ADR 003 §Cooperative close). Shared core — `decdn_client_pull::cooperative_close`: - `request_cooperative_close_auth` does the `cdn/client/v1` exchange: send `CooperativeCloseRequest { channel_id }`, await `CooperativeCloseAuth`. A clean stream-end with no frame (the provider's decline for an unknown / zero-voucher channel, handlers/client.rs) maps to `Ok(None)`. - `prepare_close` is the network-free, security-critical step: the provider dictates the final tuple, so the client (a) refuses if it exceeds the authorized watermark — a provider can't hold a higher client voucher, so a larger tuple is a payout-inflation attempt up to the deposit — and (b) verifies the waiver recovers to the provider before spending gas, then signs its own voucher over the agreed tuple. - `cooperative_close` ties request -> prepare -> on-chain `cooperativeClose` submit. The contract enforces the deposit ceiling and monotonic claimed* floor, so a revert is non-fatal (Reverted) — caller falls back to closeChannel. Generic over `Provider`, so the node->node buyer reconcile (#972) drives the same core. Thin CLI — `decdn channel coop-close`: - Chain coords resolve flag > [blockchain] config > default (pure `resolve_chain`, unit-tested). The channel + authorized watermark come from the buyer store (`get_by_provider`), so no manual amount/nonce/bytes tuple is passed — the store IS the record of what this client paid. On Settled the channel is forgotten; Declined/Reverted tell the user to fall back. Tests: prepare_close accept-at-watermark / accept-below / refuse-over-claim / refuse-wrong-signer; CLI resolve precedence. 622 crate tests pass (one pre-existing non-hermetic setup test, which reads the dev's real ~/.decdn config, excluded); workspace clippy + fmt clean. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Coverage reportTotal: 83.59% (was 83.82%, ▼ 0.22%) — 39817/47631 lines
History
|
There was a problem hiding this comment.
Pull request overview
Adds the buyer-side (“client-initiator”) cooperative-close flow to the shared paid-pull requester crate and exposes it via a new decdn channel coop-close CLI command, enabling a one-transaction channel settlement path when the provider supplies a signed cooperative-close waiver.
Changes:
- Introduces
decdn_client_pull::cooperative_closewith request → validate/sign → submitcooperativeCloseorchestration. - Adds a new CLI command group
decdn channelwithcoop-close, wired to buyer-channel store state (no manual tuple flags). - Extends common CLI parsing/export surface to include the new
channelsubcommand.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/common/src/cli/mod.rs | Registers and re-exports the new channel CLI module/types. |
| crates/common/src/cli/channel.rs | Defines clap args for decdn channel coop-close. |
| crates/client-pull/src/lib.rs | Exposes the new cooperative_close module from decdn-client-pull. |
| crates/client-pull/src/cooperative_close.rs | Implements the cooperative-close core (request auth, verify waiver, sign voucher, submit tx) plus unit tests. |
| crates/cli/src/main.rs | Routes the new Command::Channel to the CLI command dispatcher. |
| crates/cli/src/commands/mod.rs | Adds the channel command implementation module. |
| crates/cli/src/commands/channel.rs | Implements decdn channel coop-close wiring (config/flags resolution, store lookup, endpoint setup, on-chain submission). |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| // A clean stream end with no frame is the provider's decline: the handler | ||
| // calls `send.finish()` without a reply for an unknown channel or a | ||
| // zero-voucher channel. That surfaces here as an `UnexpectedEof` while | ||
| // reading the length prefix — map it to `None`; surface anything else. | ||
| let frame = match read_frame(&mut recv).await { | ||
| Ok(f) => f, | ||
| Err(FrameError::Io(e)) if e.kind() == std::io::ErrorKind::UnexpectedEof => { | ||
| return Ok(None); | ||
| } | ||
| Err(e) => return Err(anyhow::anyhow!("read auth: {e}")), | ||
| }; |
There was a problem hiding this comment.
Keeping the current mapping, by design. A truncated/malformed length prefix surfaces as the same UnexpectedEof, so it does fold into Declined — but the consequence is a fallback to the closeChannel → dispute-window → settleChannel path, which is always valid and risks no funds. Distinguishing clean-EOF from mid-frame-EOF needs a separate first-byte peek (read_frame can't tell us how many bytes it consumed) and changes nothing about the safe outcome for what would be a provider crashing mid-write. The clean stream end is the documented decline contract on the handler side, so I'd rather not add protocol-read complexity here. Open to it if you'd prefer the truncated case to hard-error instead.
| let amount = U256::from_be_bytes(auth.amount); | ||
| let nonce = U256::from_be_bytes(auth.nonce); | ||
| let bytes_delivered = U256::from_be_bytes(auth.bytes_delivered); |
There was a problem hiding this comment.
Added an explicit check in c7e7fe2, plus a covering test (refuses_waiver_for_wrong_channel):
if B256::from(auth.channel_id) != channel_id {
anyhow::bail!("provider returned a waiver for the wrong channel: ...");
}Verification would still fail closed on a mismatch (the digest is rebuilt from the local channel_id), so this is purely for an actionable error over an opaque "verification failed".
There was a problem hiding this comment.
Code Review
This pull request introduces the client-side cooperative payment-channel close feature (decdn channel coop-close). It adds the CLI command wiring, the core request-verify-submit logic in crates/client-pull/src/cooperative_close.rs, and corresponding unit tests. Feedback on the implementation points out a critical issue in the cooperative_close function: calling .send().await on the contract call triggers gas estimation, which will fail and return a hard error if the transaction would revert. This bypasses the intended graceful fallback to CooperativeCloseOutcome::Reverted. The reviewer suggested catching the revert error during the send call and mapping it to the reverted outcome.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| let pending = contract | ||
| .cooperativeClose( | ||
| channel_id, | ||
| prepared.amount, | ||
| prepared.nonce, | ||
| prepared.bytes_delivered, | ||
| prepared.client_sig, | ||
| prepared.provider_sig, | ||
| ) | ||
| .send() | ||
| .await | ||
| .map_err(|e| anyhow::anyhow!("cooperativeClose send failed: {e}"))?; |
There was a problem hiding this comment.
In Alloy, calling .send().await on a contract call builder automatically performs gas estimation (which simulates the transaction on the RPC node). If the transaction would revert on-chain (e.g., due to a race condition or a regressed watermark), gas estimation will fail, and .send().await will return an Err.
Because this error is immediately propagated via ? on line 283, the function will return a hard Err instead of the expected CooperativeCloseOutcome::Reverted. This prevents the CLI from gracefully falling back and printing the actionable guidance defined in coop_close (line 189).
To fix this, we should catch the revert error during .send().await and map it to Ok(CooperativeCloseOutcome::Reverted) if the error message indicates a revert. This allows the caller to distinguish between different failure modes efficiently using the descriptive outcome enum.
let pending = match contract
.cooperativeClose(
channel_id,
prepared.amount,
prepared.nonce,
prepared.bytes_delivered,
prepared.client_sig,
prepared.provider_sig,
)
.send()
.await
{
Ok(p) => p,
Err(e) => {
if e.to_string().contains("revert") {
return Ok(CooperativeCloseOutcome::Reverted);
}
return Err(anyhow::anyhow!("cooperativeClose send failed: {e}"));
}
};References
- Refactor functions to return descriptive outcome enums instead of booleans to avoid redundant async lookups and allow callers to distinguish between different failure modes (e.g., data missing vs. resource exhaustion) efficiently.
There was a problem hiding this comment.
Fixed in c7e7fe2 — the underlying concern is right: a deterministic revert is caught at gas estimation, so .send() returns Err and never reaches the receipt.status() path, defeating the Reverted fallback.
I went with the typed accessor rather than a to_string().contains("revert") match, which is brittle across RPC providers and (more importantly) would misclassify transient RPC/nonce failures as reverts:
Ok(pending) => pending,
Err(e) if e.as_revert_data().is_some() => return Ok(CooperativeCloseOutcome::Reverted),
Err(e) => return Err(anyhow::anyhow!("cooperativeClose send failed: {e}")),as_revert_data() (alloy-contract 2.0.5) is Some only when the node returned revert data, so a genuine transport error still surfaces as an error the caller can retry — matching the node-side try_settle posture where a send failure is transient, not a settlement signal. The existing get_receipt().status() branch still covers the rarer estimation-passed-then-mined-revert case.
Code reviewNo issues found. Checked for bugs and CLAUDE.md compliance. 🤖 Generated with Claude Code - If this code review was useful, please react with 👍. Otherwise, react with 👎. |
- Map a deterministic estimation-time revert (caught by gas estimation in `.send()`) to `CooperativeCloseOutcome::Reverted` via typed `as_revert_data()`, so the CLI prints the closeChannel fallback guidance instead of a hard error. A send error without revert data stays a transport/RPC error the caller should retry. - Submit the re-serialized parsed `provider_sig.as_bytes()` rather than the raw wire bytes, so a non-canonical `v` (0/1) that parses and verifies still lands on-chain in the 27/28 form `ECDSA.recover` requires — both sigs now go through the same normalizer. - Reject a waiver whose echoed `channel_id` does not match the requested channel with an actionable error (signature verification already failed closed; this just makes the diagnostic clear). Add a covering test. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…y vector (#1009) (#1010) * test(incentive,contracts): pin cooperative-close EIP-712 waiver parity vector (#1009) The cooperative-close waiver (PRs #948/#949/#957/#973) is signed off-chain in Rust and verified on-chain by PaymentChannel, with the EIP-712 type and domain hand-duplicated on each side. Nothing pinned the full typed-data digest across both, so a drift in the domain (name/version) or struct encoding would produce unsettleable waivers with no test failure — the existing coverage only pinned the typehash string (Rust) and round-tripped sign/recover within each language. Commit one canonical parity vector and assert it from both sides: - Rust: EXPECTED_COOP_CLOSE_DIGEST + cooperative_close_digest_matches_committed_vector asserting sample_close().signing_hash(sample_domain()) equals it. - Solidity: test_cooperativeClose_digestMatchesVector recomputes the digest with the contract's public COOPERATIVE_CLOSE_TYPEHASH and the fixed domain, and test_cooperativeClose_domainMatchesVector ties the deployed contract's ERC-5267 eip712Domain() name/version to the vector. Verified the vector catches the drift class: bumping the domain version on either side fails the corresponding test. Test-only; no production code changed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * test(contracts): refresh .gas-snapshot for cooperative-close vector tests The #1010 vector tests add two functions plus fixtures to PaymentChannel.t.sol, enlarging that suite's test-contract bytecode and shifting per-test deployment gas across PaymentChannelTest, plus the two new entries (test_cooperativeClose_digestMatchesVector, test_cooperativeClose_domainMatchesVector). Regenerated via `FOUNDRY_PROFILE=ci forge snapshot --snap .gas-snapshot`; non-reproducible fuzz `runs:` lines left at committed values (the CI gate strips them). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Closes #971. The buyer/initiator half of cooperative close — the part that actually calls
cooperativeCloseon-chain. Builds on the merged contract (#948), wire+EIP-712 (#949), and provider waiver (#957). One settle, no 48h dispute window (ADR 003 §Cooperative close). Base =main(all deps merged).Shared core —
decdn_client_pull::cooperative_closerequest_cooperative_close_auth— thecdn/client/v1exchange: sendCooperativeCloseRequest { channel_id }, awaitCooperativeCloseAuth. The provider's decline (unknown / zero-voucher channel) is a cleansend.finish()with no frame on the node side (feat(node): cooperative-close provider side — sign waiver + stop serving #957), which surfaces here as anUnexpectedEofand maps toOk(None).prepare_close— network-free, security-critical. The wire design has the provider dictate the final tuple (CooperativeCloseRequestcarries onlychannel_id; the auth returnsamount/nonce/bytes). So the client must:<=what the client issued, so a returned tuple above the authorized watermark is a payout-inflation attempt (toward the full deposit). Refuse.clientVoucherSigthe contract checks againstchannel.client).cooperative_close— request → prepare → submitcooperativeClose. The contract enforces the deposit ceiling and monotonicclaimed*floor, so a mined revert is non-fatal (Reverted) and the caller falls back tocloseChannel. Generic overProviderso the node→node buyer reconcile (Cooperative close: node-as-buyer periodic reconcile of node→node channels #972) drives the same core.Thin CLI —
decdn channel coop-closeNew top-level
channelcommand group. Chain coords resolve flag >[blockchain]config > default (pureresolve_chain, unit-tested). The channel id and authorized watermark come from the buyer store (get_by_provider) — the store is already the record of what this client paid viadecdn fetch, so there's no error-prone manual--amount/--nonce/--bytes. OnSettledthe channel is forgotten (deposit refunded);Declined/Revertedprint actionable fallback guidance.Tests
prepare_close: accept-at-watermark, accept-below-watermark, refuse over-claim, refuse wrong-signer.resolve_chainprecedence (flag>config>default, missing-required).cargo nextest run -p decdn-client-pull -p decdn-cli -p decdn-common→ 622 passing. One pre-existing failure excluded:setup_dry_run_does_not_leak_rpc_url_on_unreachable_endpointis non-hermetic — it omits--config, so on a dev box with a real~/.decdn/node.tomlit picks up that keystore path and aborts before the RPC path under test (green in CI's clean HOME; unrelated to this diff).cargo clippy --workspace --all-targets+cargo fmt --checkclean.Not in scope
closeChannelon decline — the command reports and exits non-zero.🤖 Generated with Claude Code