Skip to content

feat(node): cooperative-close provider side — sign waiver + stop serving - #957

Merged
alpergundogdu merged 3 commits into
mainfrom
claude/coop-close-node
Jun 19, 2026
Merged

alpergundogdu merged 3 commits into
mainfrom
claude/coop-close-node

Conversation

@alpergundogdu

Copy link
Copy Markdown
Contributor

Provider/node half of cooperative close (ADR 003): the node signs a cooperative-close waiver at the channel's current voucher watermark, persists a "signed" flag, and stops serving/accepting vouchers on that channel thereafter.

Supersedes #952, which GitHub auto-closed (and refused to reopen) when its stacked base branch claude/coop-close-protocol was deleted on the merge of #949. This is the same branch, rebased cleanly onto main, with the decdn-protocol public-API snapshot regenerated for the new VoucherRejectReason::CooperativeCloseSigned variant.

Review comments from #952 (schema-version-guarded v1 flag decode, off-thread fsync via spawn_blocking, idempotent retry) were addressed in commit f625e51.

🤖 Generated with Claude Code

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request implements cooperative-close functionality (ADR 003) by adding a cooperative_close_signed flag to ChannelState and updating the persistent channel store to serialize/deserialize this flag in a backward-compatible manner. It introduces handling for CooperativeCloseRequest in the client handler, which signs a waiver over the channel's current watermark and returns a CooperativeCloseAuth, while subsequently refusing further delivery on that channel. Feedback suggests optimizing the serialization of the boolean flag in channel_store.rs by directly pushing the byte representation instead of using postcard::to_allocvec to avoid heap allocation.

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.

Comment on lines +666 to +670
let coop_encoded =
postcard::to_allocvec(&state.cooperative_close_signed()).map_err(|err| {
StoreError::Codec(format!("postcard encode of coop-close flag: {err}"))
})?;
encoded.extend_from_slice(&coop_encoded);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Since a bool in Postcard is always serialized as a single byte (0x00 for false and 0x01 for true), we can avoid the heap allocation and overhead of postcard::to_allocvec by directly pushing the byte representation onto encoded.

Suggested change
let coop_encoded =
postcard::to_allocvec(&state.cooperative_close_signed()).map_err(|err| {
StoreError::Codec(format!("postcard encode of coop-close flag: {err}"))
})?;
encoded.extend_from_slice(&coop_encoded);
encoded.push(u8::from(state.cooperative_close_signed()));

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

Implements the provider/node side of ADR-003 cooperative close: the node can sign a cooperative-close waiver at the current voucher watermark, persist a “signed” flag on the channel, and refuse further serving / voucher acceptance for that channel.

Changes:

  • Adds VoucherRejectReason::CooperativeCloseSigned to the protocol surface and pins it in the public API snapshot.
  • Persists a new cooperative_close_signed flag in channel state (redb record trailing segment) and enforces it in the client handler (serve gate + in-flight voucher gate).
  • Adds end-to-end and persistence tests plus a new metric for cooperative-close-based delivery refusals.

Reviewed changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
crates/protocol/tests/snapshots/public_api__public_api.snap Public API snapshot updated for new reject reason variant.
crates/protocol/src/client.rs Adds CooperativeCloseSigned to VoucherRejectReason and updates discriminant test list.
crates/node/tests/client_loopback.rs Adds loopback E2E test for waiver signing, persistence, and refusing delivery.
crates/node/src/metrics.rs Adds counter + helper method for cooperative-close stream rejection.
crates/node/src/handlers/client.rs Adds cooperative-close request handling, refusal gates, and emits new reject reason.
crates/node/src/channel_store.rs Extends encode/decode to append/read coop-close flag as trailing postcard segment + tests.
crates/node/src/admin.rs Updates channel test fixture hydration for new ChannelState::hydrate parameter.
crates/incentive/src/store.rs Updates store tests/fixtures for new ChannelState::hydrate parameter.
crates/incentive/src/channel.rs Adds cooperative_close_signed field + accessor + durable mark method.
crates/cli/tests/admin_peers.rs Updates channel test fixture hydration for new ChannelState::hydrate parameter.

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

Comment on lines 2237 to 2240
Ok((_, _)) => Err(StreamReadError {
err: anyhow::anyhow!("expected ClientMessage::StreamRequest"),
err: anyhow::anyhow!("expected StreamRequest or CooperativeCloseRequest"),
app_code: 0x01, // UNSUPPORTED_MESSAGE
}),
Comment on lines +2118 to +2133
// Persist the no-longer-serving flag before returning the waiver. On a
// store failure this propagates (no auth sent) and the channel stays
// serveable — safe. `mark_cooperative_close_signed` performs a
// synchronous fsynced redb write, which must not block a runtime
// worker — run it on the blocking pool against a clone and commit back
// only on `Ok`, mirroring `apply_voucher` / `update_channel_deposit`.
let mut candidate = guard.state.clone();
let store = Arc::clone(&self.channel_state_store);
let (mark_res, candidate) = tokio::task::spawn_blocking(move || {
let res = candidate.mark_cooperative_close_signed(&*store);
(res, candidate)
})
.await
.map_err(|e| anyhow::anyhow!("cooperative-close mark task failed: {e}"))?;
mark_res?;
guard.state = candidate;
Comment on lines +568 to +576
let (cooperative_close_signed, leftover): (bool, &[u8]) =
if stored.schema_version >= 2 && !after_trailer.is_empty() {
postcard::take_from_bytes::<bool>(after_trailer).map_err(|err| StoreError::Corrupt {
channel_id: Some(channel_id),
detail: format!("postcard decode of coop-close flag failed: {err}"),
})?
} else {
(false, after_trailer)
};
@github-actions

github-actions Bot commented Jun 19, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 84.31% (was 84.31%, ▲ +0.01%) — 38878/46111 lines

File Coverage Lines Δ
crates/incentive/src/channel.rs 96.15% 400/416 ▼ 0.07%
crates/incentive/src/store.rs 90.96% 161/177 ▲ +0.05%
crates/node/src/admin.rs 95.11% 1225/1288 ● 0.00%
crates/node/src/channel_store.rs 87.45% 1443/1650 ▼ 0.15%
crates/node/src/handlers/client.rs 78.74% 922/1171 ▲ +0.37%
crates/node/src/metrics.rs 83.40% 804/964 ▲ +0.12%
crates/protocol/src/client.rs 98.10% 618/630 ● 0.00%
History
Commit Total Δ vs base
3c230fe 84.31% ▲ +0.01%
4225688 (HEAD) 84.31% ▲ +0.01%

alpergundogdu and others added 3 commits June 19, 2026 17:13
…ing (#947)

Implements the node (provider) half of cooperative close (ADR 003 §Cooperative
close), on top of the wire + EIP-712 foundation (#949).

- Handler answers a CooperativeCloseRequest on cdn/client/v1 by signing a
  CooperativeClose waiver over the channel's current voucher watermark
  (last_amount/nonce/bytes) with the node's eth key and replying with a
  CooperativeCloseAuth. Best-effort: unknown channel or no-voucher-yet
  (nonce 0) finishes with no auth and the client falls back to closeChannel.

- Self-protection (the "refuse payment after signing" guard): a persisted
  cooperative_close_signed flag on ChannelState. Once set, the node refuses
  new StreamRequests (ServeRejectReason::CooperativeCloseSigned -> NotFound,
  wire-indistinguishable) and rejects in-flight vouchers
  (VoucherRejectReason::CooperativeCloseSigned). Checking the flag at both the
  request gate and the voucher gate bounds any signed-mid-delivery loss to one
  voucher interval, so no separate "don't sign while delivering" interlock is
  needed.

- Persistence: the flag rides as an additive trailing postcard segment after
  the v2 trailer in channels.redb — no schema bump, defaults false for records
  written before it existed (forward/backward compatible).

- mark_cooperative_close_signed uses the same clone-record-swap durability
  discipline as apply_voucher (#527): persist before the waiver is returned.

Tests: redb round-trip across reopen, no-segment-decodes-false, and an
end-to-end loopback (waiver recovers to the node key over the on-chain typed
data, flag persists, subsequent delivery refused). 951 crate tests pass;
workspace clippy + fmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…read fsync, idempotent retry

- channel_store: gate the coop-close bool decode on schema_version >= 2 so
  v1 records' trailing bytes are never mis-decoded as the flag
- client handler: run mark_cooperative_close_signed on spawn_blocking, matching
  apply_voucher / update_channel_deposit (no fsync on a runtime worker)
- incentive: early-return Ok(()) when already flagged, avoiding a redundant
  fsync on retried CooperativeCloseRequest

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

#952 adds VoucherRejectReason::CooperativeCloseSigned to the public surface;
the snapshot wasn't refreshed against main (it passed only vs the old stacked
base). Additive-only regeneration.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alpergundogdu
alpergundogdu force-pushed the claude/coop-close-node branch from 3c230fe to 4225688 Compare June 19, 2026 16:15
@alpergundogdu
alpergundogdu merged commit 1ce612a into main Jun 19, 2026
20 checks passed
@alpergundogdu
alpergundogdu deleted the claude/coop-close-node branch June 19, 2026 16:21
alpergundogdu added a commit that referenced this pull request Jun 23, 2026
* feat(client-pull,cli): client-initiated cooperative close (#971)

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]>

* fix(client-pull): address coop-close review feedback

- 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]>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
thiras added a commit that referenced this pull request Jun 27, 2026
…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]>
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.

2 participants