Skip to content

feat(node): on-chain PaymentChannel seller settlement + CapacityBond rename (#327) - #743

Merged
thiras merged 4 commits into
mainfrom
feat/327-paymentchannel-onchain-client
Jun 1, 2026
Merged

thiras merged 4 commits into
mainfrom
feat/327-paymentchannel-onchain-client

Conversation

@thiras

@thiras thiras commented May 31, 2026

Copy link
Copy Markdown
Contributor

Closes #327 (seller-side scope).

Context

Issue #327 had drifted heavily. The poc-blocking part — the CapacityBond registry read-path — was already implemented as ChainStakerSet. The blocking dependency PaymentChannel.sol landed in #716, so the real remaining work is the on-chain PaymentChannel client (the Rust seller/provider settlement path), which was entirely absent. The voucher handler explicitly rejected every channel as unknown until this consumer existed.

Critical bug fixed

The Rust voucher EIP-712 domain name was "StablePaymentChannel", but the contract uses EIP712("PaymentChannel", "1"). Every closeChannel/withdraw would have reverted with InvalidVoucherSignature despite off-chain verification passing. Fixed and pinned with a regression test asserting the domain matches the contract literal.

What's in this PR

  • incentive: PaymentChannel sol! bindings (reads + writes + lifecycle events), validated field-for-field against the compiled ABI.
  • voucher: EIP-712 domain fix + regression test.
  • store: schema v2 persists the latest voucher signature (additive trailing postcard segment; v1 records hydrate with an empty signature and are unredeemable until re-recorded). Adds a get point-lookup to the ChannelStateStore trait.
  • node: PaymentChannelService — watches ChannelOpened (provider == self) → persist so the handler accepts vouchers (closes the documented Implement on-chain CapacityBond and PaymentChannel contract integration #327 gap), ChannelSettled → forget, ChannelCloseInitiated → observe-only (dispute monitor deferred, Implement cdn/watchtower/v1 channel dispute monitoring protocol #324). Redeems via threshold withdraw (hinted from the voucher-accept path) and best-effort closeChannel on graceful shutdown, with on-chain v-byte normalization (0/1 → 27/28).
  • runtime: wallet-filled provider from the eth signer, usdc() startup self-check, redeem_threshold_micro_usdc config (default 1 USDC), shutdown close hook.

⚠️ Breaking change

Renames StakingRegistry → CapacityBond (matching the on-chain contract):

  • config TOML key blockchain.staking_registry_address → blockchain.capacity_bond_address
  • CLI flag --staking-registry-address → --capacity-bond-address
  • env var DECDN_STAKING_REGISTRY_ADDRESS → DECDN_CAPACITY_BOND_ADDRESS

Acceptable at this stage (early implementation, no deployed configs), but operators with existing configs must rename the key/flag/env.

Verification

cargo build, clippy --workspace --all-targets -D warnings, fmt --check, 1264 tests pass, cargo deny, rustdoc -D warnings, and bindings cross-checked against the compiled PaymentChannel.json ABI (event indexed-layouts + function signatures).

Not run: the live anvil e2e — there's no existing on-chain integration harness (no alloy node-bindings dev-dep / anvil infra), so it'd be a separate scaffolding effort. The two runtime-only behaviors it would exercise beyond the static checks: on-chain acceptance of the normalized signature v-byte, and live event decode (the ABI cross-check substitutes for the latter).

Out of scope (deferred)

🤖 Generated with Claude Code

…rename (#327)

Implements the on-chain PaymentChannel client (seller/provider settlement
path) for issue #327. The CapacityBond registry read-path was already done
as ChainStakerSet; PaymentChannel.sol landed in #716, so this wires the
Rust side that drives close/withdraw/settle.

- incentive: PaymentChannel sol! bindings (reads + writes + lifecycle
  events), validated field-for-field against the compiled ABI.
- voucher: fix EIP-712 domain name "StablePaymentChannel" -> "PaymentChannel"
  to match the contract's EIP712("PaymentChannel","1") ctor — without this
  every closeChannel/withdraw reverts with InvalidVoucherSignature despite
  off-chain verification passing. Pinned with a regression test.
- store: schema v2 persists the latest voucher signature (additive trailing
  postcard segment; v1 records hydrate with an empty signature and are
  unredeemable until re-recorded). Adds a `get` point-lookup to the trait.
- node: PaymentChannelService watches ChannelOpened (provider==self) -> persist
  so the voucher handler accepts it, ChannelSettled -> forget,
  ChannelCloseInitiated -> observe-only (dispute monitor deferred, #324).
  Redeems via threshold `withdraw` (redeem hint from the voucher-accept path)
  and best-effort `closeChannel` on graceful shutdown, with on-chain v-byte
  normalization (0/1 -> 27/28).
- runtime: wallet-filled provider from the eth signer, usdc() startup
  self-check, redeem_threshold_micro_usdc config (default 1 USDC), shutdown
  close hook.

BREAKING CHANGE: renames StakingRegistry -> CapacityBond. The config TOML key
`blockchain.staking_registry_address` is now `blockchain.capacity_bond_address`,
the CLI flag `--staking-registry-address` is now `--capacity-bond-address`, and
the env var DECDN_STAKING_REGISTRY_ADDRESS is now DECDN_CAPACITY_BOND_ADDRESS.

Out of scope (deferred): buyer-side openChannel for node-to-node pulls, the
in-process dispute monitor (#324), and the live anvil e2e (no existing harness).

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

@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 renames StakingRegistry to CapacityBond and StablePaymentChannel to PaymentChannel across the codebase, introduces a configurable redemption threshold, and implements the on-chain seller-settlement service (PaymentChannelService) to handle automated withdrawals and channel closures on shutdown. Additionally, it updates the channel state persistence schema to version 2 to store voucher signatures. Feedback on the changes highlights a few key areas for improvement: preventing RPC spam by caching the last known withdrawnAmount to avoid redundant on-chain queries, parallelizing the retrieval of transaction receipts during shutdown to avoid exceeding the shutdown deadline, and cleaning up the unused submit_close helper function if the parallelized shutdown logic is adopted.

Comment thread crates/node/src/payment_settlement.rs Resolved
Comment thread crates/node/src/payment_settlement.rs Resolved
Comment thread crates/node/src/payment_settlement.rs Resolved
Comment thread crates/node/src/payment_settlement.rs Resolved
@github-actions

github-actions Bot commented May 31, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 87.79% (was 89.52%, ▼ 1.73%) — 24331/27715 lines

File Coverage Lines Δ
crates/cli/src/commands/config.rs 61.60% 77/125 ● 0.00%
crates/cli/src/commands/probe.rs 69.50% 139/200 ● 0.00%
crates/common/src/config/mod.rs 96.27% 4566/4743 ▲ +0.01%
crates/common/src/config/resolved.rs 100.00% 13/13 ● 0.00%
crates/incentive/src/channel.rs 95.07% 289/304 ▼ 0.91%
crates/incentive/src/probe_sig.rs 98.63% 216/219 ● 0.00%
crates/incentive/src/store.rs 92.17% 153/166 ▼ 0.05%
crates/incentive/src/voucher.rs 99.05% 208/210 ▲ +0.02%
crates/node/src/channel_store.rs 87.31% 619/709 ▼ 2.13%
crates/node/src/client_requester.rs 83.33% 200/240 ● 0.00%
crates/node/src/dht/chain_staker_set.rs 20.33% 50/246 ● 0.00%
crates/node/src/dht/origin.rs 100.00% 40/40 ● 0.00%
crates/node/src/dht/staker_set.rs 95.31% 61/64 ● 0.00%
crates/node/src/handlers/client.rs 74.67% 395/529 ▼ 4.28%
crates/node/src/payment_settlement.rs 15.32% 87/568 new
crates/node/src/runtime/mod.rs 47.76% 512/1072 ▼ 0.86%
crates/node/src/runtime/reload.rs 95.48% 1394/1460 ▲ +0.01%
crates/node/src/selection.rs 97.77% 525/537 ● 0.00%
History
Commit Total Δ vs base
5d658d8 88.43% ▼ 1.07%
076b919 87.97% ▼ 1.52%
34a91ae 88.14% ▼ 1.35%
270ed19 (HEAD) 87.79% ▼ 1.73%

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 adds seller-side on-chain PaymentChannel settlement integration for nodes and completes the StakingRegistry → CapacityBond naming/config transition. It also fixes the voucher EIP-712 domain so Rust-signed vouchers match the deployed PaymentChannel contract.

Changes:

  • Adds PaymentChannel ABI bindings, settlement watcher/redeemer service, runtime wiring, voucher-signature persistence, and redeem hints from the client handler.
  • Renames staking registry configuration/API references to CapacityBond.
  • Fixes the voucher EIP-712 domain literal and updates tests/config fixtures for the new schema and resolved config fields.

Reviewed changes

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

Show a summary per file
File Description
crates/node/tests/sighup_signal.rs Updates resolved config test fixture for capacity_bond_address and redeem threshold.
crates/node/tests/client_loopback.rs Adds ChannelStateStore::get to the failing-store test implementation.
crates/node/src/selection.rs Updates staking-registry wording to capacity-bond wording.
crates/node/src/runtime/reload.rs Updates reload test fixtures for renamed config and redeem threshold.
crates/node/src/runtime/mod.rs Wires PaymentChannelService, wallet provider, renamed CapacityBond address, and shutdown close hook.
crates/node/src/payment_settlement.rs Adds seller-side PaymentChannel watcher, redemption loop, signature normalization, and shutdown close logic.
crates/node/src/lib.rs Exposes the new payment_settlement module.
crates/node/src/handlers/client.rs Adds channel registration/forget hooks and best-effort redeem hints after voucher acceptance.
crates/node/src/dht/staker_set.rs Updates docs from StakingRegistry to CapacityBond.
crates/node/src/dht/origin.rs Updates docs from StakingRegistry to CapacityBond.
crates/node/src/dht/chain_staker_set.rs Switches chain staker binding from StakingRegistry to CapacityBond.
crates/node/src/client_requester.rs Updates voucher-domain documentation.
crates/node/src/channel_store.rs Bumps channel store schema, appends persisted voucher signatures, and adds point lookup.
crates/incentive/src/voucher.rs Renames voucher domain from StablePaymentChannel to PaymentChannel and adds regression coverage.
crates/incentive/src/store.rs Adds ChannelStateStore::get and memory-store implementation.
crates/incentive/src/probe_sig.rs Updates cross-contract replay documentation names.
crates/incentive/src/payment_channel.rs Adds PaymentChannel contract bindings for seller settlement.
crates/incentive/src/lib.rs Exports capacity_bond and payment_channel modules and updates crate docs.
crates/incentive/src/channel.rs Persists latest voucher signature in channel state.
crates/incentive/src/capacity_bond.rs Renames binding contract/export from StakingRegistry to CapacityBond.
crates/common/src/config/types.rs Renames config field and adds redeem-threshold TOML field.
crates/common/src/config/resolved.rs Updates resolved config shape for CapacityBond and redeem threshold.
crates/common/src/config/mod.rs Resolves renamed config/env/CLI fields and default redeem threshold.
crates/common/src/cli/run.rs Renames CLI/env field to capacity_bond_address.
crates/cli/tests/config_validate.rs Updates config-validation fixtures for renamed field and redeem threshold.
crates/cli/src/commands/probe.rs Updates documentation wording to CapacityBond.
crates/cli/src/commands/config.rs Updates config summary/default template for capacity_bond_address.

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

Comment thread crates/node/src/payment_settlement.rs Resolved
Comment thread crates/node/src/payment_settlement.rs Resolved
thiras and others added 2 commits June 1, 2026 01:37
…pUp + expiry handling (#327)

External review (gemini-code-assist, Copilot) on PR #743:

- redeemer: cache last-known on-chain `withdrawnAmount` per channel and skip
  the `getChannel` RPC when the accrued claim is provably below threshold —
  avoids per-voucher RPC spam under active streaming. The cache is always
  `<=` the true value (only our own `withdraw` advances it), so a redemption
  is never wrongly skipped.
- shutdown close: submit `closeChannel` sequentially (nonce order) but await
  receipts concurrently via `join_all` so more channels close within the
  bounded shutdown deadline. `submit_close` refactored into a free `send_close`
  returning a receipt future (`use<P>` precise capture).
- topUp (Copilot): subscribe to `ChannelToppedUp` and raise the tracked
  `ChannelState.deposit` so `apply_voucher` stops rejecting otherwise-valid
  vouchers a client signs after topping up.
- expiry (Copilot): persist the channel's on-chain `expiresAt` (schema-v2
  second trailing segment), add a periodic pre-expiry close sweep so the
  provider redeems before `reclaimExpired` can refund the client, and gate the
  voucher handler to refuse delivery once a channel is expired (defense in
  depth). Closing earns the claim; the sweep then retires (forgets) the
  channel so the node stops serving it.

Verification: clippy --workspace --all-targets -D warnings, fmt, 1264 tests,
rustdoc -D warnings — all green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ation, dead-field + doc fixes, tests (#327)

Multi-agent review of PR #743 (code/tests/errors/types/comments):

Critical:
- try_redeem / send_close now check `receipt.status()`. `get_receipt()`
  resolves Ok even for a reverted tx; previously a reverted `withdraw`
  poisoned the withdrawn-amount cache (channel silently never redeemed again
  until restart) and a reverted `closeChannel` made the expiry sweep forget an
  un-redeemed channel right before reclaimExpired. Both now leave state intact
  and retry.

Important:
- reject `blockchain.redeem_threshold_micro_usdc = 0` at config resolution (0
  withdraws on every voucher and reverts on zero-delta) — mirrors the
  rpc_watchdog floor pattern. Test added.
- correct the `as_bytes()` v-byte docs: alloy already emits 27/28, so
  `normalize_voucher_signature` is a defensive no-op today (not the active
  0/1->27/28 bridge the doc claimed).
- fix module docs: add `ChannelToppedUp` to the watcher's handled-events list;
  correct the "registered at startup" claim (startup is store hydration in
  ClientHandler::new, not register_open_channel); document the
  opened-during-downtime backfill gap.
- drop dead `redeem_threshold` / `self_address` fields from
  PaymentChannelService (read only in Debug; the live values are the copies
  moved into the tasks).

Tests (pure-logic gaps the review flagged):
- extract `is_expired` / `within_close_window` predicates (shared by the sweep
  and the handler expiry gate) + boundary table tests.
- register_open_channel idempotency preserves the voucher watermark (the #527
  replay-window guard) — was untested.
- update_channel_deposit raises / no-ops on non-increasing / no-ops on
  untracked.
- normalize empty signature.

Not changed (with rationale): kept the schema-v2 trailing-segment encoding —
the suggested "struct fields + version bump" breaks reading existing on-disk
v1 records (a v2 reader would read past end-of-input). Deferred to follow-ups:
observability metrics, an independent redeemer tick, shutdown-quiesce of the
redeemer, ChannelState type-strengthening, and the downtime log-backfill.

Verification: clippy --workspace --all-targets -D warnings, fmt, 1270 tests,
rustdoc -D warnings — all green.

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

Copy link
Copy Markdown
Contributor

Review — seller settlement (#743)

Reviewed the incremental diff against main. The settlement path is high quality; I verified the load-bearing parts and they hold up:

  • EIP-712 domain fix is correct — contract is EIP712("PaymentChannel","1") and the new DOMAIN_NAME/DOMAIN_VERSION + pinning test match.
  • sol! bindings match the contract (struct field order, withdraw/closeChannel/settleChannel/getChannel/usdc signatures, all four event signatures incl. indexed provider so the provider == self filter works).
  • Threshold/cache logic is sound: cumulative watermarks, cached withdrawnAmount is a <= lower bound (upper-bound unredeemed estimate), and the reverted-withdraw path correctly does not seed the cache.
  • Store v1→v2 migration is safe: v1 records hydrate with empty signature / 0 expiry and are skipped by every redeem/close guard; v3+ is rejected before the unknown trailer is used. Covered by tests.
  • CapacityBond rename is complete across config key, CLI flag, env var, DTOs, runtime, DHT staker set.

One thing worth a decision

settleChannel is bound but never called from Rust — crates/incentive/src/payment_channel.rs:123, no caller anywhere.

closeChannel (both the graceful-shutdown path and the expiry sweep) only initiates the dispute window — it does not pay the provider. The provider's un-withdrawn remainder (claimedAmount - withdrawnAmount) is paid out only when someone calls settleChannel after disputeDeadline (contract settleChannel → _route(provider, …), contracts/src/PaymentChannel.sol:434). The node never calls it, and the expiry-sweep path additionally forget_channels the row, so it can't follow up later either.

The doc comments (crates/node/src/payment_settlement.rs:29,209) say this is intentional — "a later settleChannel (by anyone) finalizes it." In practice the client is incentivized to call it to reclaim deposit - claimedAmount. But when clientRefund == 0 (client drew the full deposit), nobody has an incentive and the provider's remainder is stranded. The bulk is still collected by threshold withdraw, so this is only the sub-threshold tail.

[your call] — if this is deliberately deferred to the dispute monitor (#324), fine; consider either (a) not forget-ting the channel in the expiry path so a future settle can find it, or (b) a small persisted "pending settle" set swept after disputeDeadline. At minimum, calling it out as a known deferral in #324 would close the loop.

Automated multi-angle review (line-by-line + removed-behavior + cross-file), recall-biased.

…ow (#327)

closeChannel only opens the dispute window; the provider's un-withdrawn
remainder (claimedAmount - withdrawnAmount) is routed only when settleChannel
runs after disputeDeadline. The node never called settleChannel and the expiry
sweep forgot the channel, so when the client had no incentive to settle
(clientRefund == 0) the remainder stranded (PR #743 review by @alpergundogdu).

- Add durable PendingSettleStore (incentive trait + MemoryPendingSettleStore;
  redb-backed via a second `pending_settle_v1` table on the existing channel
  store, sharing one open file + fsync discipline).
- Record a pending-settle entry after every close (shutdown + pre-expiry sweep,
  both via send_close), keyed by channel with the on-chain disputeDeadline gate.
- Add a settle sweep (settle_pass/try_settle) that calls settleChannel once the
  window elapses, gated on the stored deadline to avoid guaranteed-revert gas;
  re-stamps the deadline if a dispute extended it, and drops the entry once a
  ChannelSettled event (from any party) confirms finalization.
- Failed-to-record paths log at error! with the manual settleChannel remedy.

No contract change (settleChannel already exists). Tests cover the store
round-trip/overwrite/forget/persistence, table independence, and the gate
boundary. clippy -D warnings, fmt, docs, and nextest all clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@thiras
thiras merged commit 2545538 into main Jun 1, 2026
18 checks passed
@thiras
thiras deleted the feat/327-paymentchannel-onchain-client branch June 1, 2026 13:48
thiras added a commit that referenced this pull request Jun 1, 2026
…745)

Stand up a live, gated end-to-end test (behind the `anvil-e2e` cargo feature,
off by default) that closes the two runtime-only verification gaps called out
in PR #743:
  1. on-chain acceptance of the normalized voucher signature v-byte, and
  2. live ChannelOpened/ChannelSettled event decode by PaymentChannelService.

The test spawns anvil, deploys a mintable mock USDC + the full protocol via
`forge script DeployProtocol.s.sol`, activates the node on-chain (stake +
registerNode — the iroh ed25519 key signs the Ed25519Verifier ownership proof,
the eth key signs the EIP-712 binding), brings up PaymentChannelService + a
persistent store + ClientHandler in-process, then runs a real iroh paid
delivery and asserts: the watcher persists the opened channel (closes the #327
WrongChannel gap), the threshold withdraw lands on-chain, FeeRouter.bytesPerEpoch
increments, graceful-shutdown closeChannel moves the channel to Closing, and
settleChannel after the dispute window is decoded and forgets the row.

Supporting changes:
- contracts: add test-only MintableUSDC (6-decimal, mintable) mock.
- node tests: extract the shared iroh helpers into tests/support/mod.rs
  (client_loopback.rs now consumes it; behavior-preserving).
- node: add the `anvil-e2e` feature (no new crate deps; anvil/forge run as
  subprocesses).
- ci: add a gated `anvil-e2e` job (Rust + Foundry) wired into ci-success.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
thiras added a commit that referenced this pull request Jun 1, 2026
…se/watcher comments

Rebased onto main (#743 squash-merged the #327 settlement work this branch
previously carried as duplicate commits); adapted the `bootstrap` call to
main's added `pending_store` param by deriving both trait handles from the one
`PersistentChannelStateStore`, mirroring the runtime wiring.

- free_port TOCTOU: spawn anvil through a retry helper that detects an early
  exit (port stolen between probe and bind) and retries on a fresh port, with a
  per-port 20s readiness timeout. The child is owned by AnvilGuard immediately
  so every early return reaps it.
- shutdown-close comment: corrected to state that `close_all_unredeemed`
  force-closes *every* still-Open channel with unredeemed work — channel 1 also
  closes when its single redeem lands the 1 MiB interval voucher (verified: the
  run logs `closed=2`), not just channel 2.
- watcher readiness comment: corrected to reflect the four sequential `.watch()`
  filter installs (not one) and that the ordering is bridged by the sleep plus
  the intervening mint/approve roundtrips; a fully deterministic fix needs a
  prod-side readiness signal / get_logs fallback, out of scope here.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
thiras added a commit that referenced this pull request Jun 1, 2026
…745) (#752)

* test(node): anvil e2e harness for on-chain PaymentChannel settlement (#745)

Stand up a live, gated end-to-end test (behind the `anvil-e2e` cargo feature,
off by default) that closes the two runtime-only verification gaps called out
in PR #743:
  1. on-chain acceptance of the normalized voucher signature v-byte, and
  2. live ChannelOpened/ChannelSettled event decode by PaymentChannelService.

The test spawns anvil, deploys a mintable mock USDC + the full protocol via
`forge script DeployProtocol.s.sol`, activates the node on-chain (stake +
registerNode — the iroh ed25519 key signs the Ed25519Verifier ownership proof,
the eth key signs the EIP-712 binding), brings up PaymentChannelService + a
persistent store + ClientHandler in-process, then runs a real iroh paid
delivery and asserts: the watcher persists the opened channel (closes the #327
WrongChannel gap), the threshold withdraw lands on-chain, FeeRouter.bytesPerEpoch
increments, graceful-shutdown closeChannel moves the channel to Closing, and
settleChannel after the dispute window is decoded and forgets the row.

Supporting changes:
- contracts: add test-only MintableUSDC (6-decimal, mintable) mock.
- node tests: extract the shared iroh helpers into tests/support/mod.rs
  (client_loopback.rs now consumes it; behavior-preserving).
- node: add the `anvil-e2e` feature (no new crate deps; anvil/forge run as
  subprocesses).
- ci: add a gated `anvil-e2e` job (Rust + Foundry) wired into ci-success.

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

* test(node): address PR #752 review — u64 evm_increaseTime + propagate artifact-read error

- evm_increaseTime: pass a plain u64 (JSON number) instead of U256 (hex-quantity
  string), which not every EVM client accepts for that RPC.
- deploy_mock_usdc: it returns Result, so propagate the artifact read/parse
  failures via map_err(...)?/ok_or_else instead of panicking with .expect.

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

* test(node): round-2 review — stderr log writer + assert ChannelOpened fields

- The redeemer/watcher warn!s (on-chain revert reasons) are emitted from tokio
  worker threads; `with_test_writer` routes through libtest's thread-local
  capture set only on the main thread, so those cross-thread logs would be
  dropped. Write to process stderr instead (nextest captures it and shows it on
  failure) — restores the intended diagnostic on a withdraw/close timeout.
- Assert the persisted channel 1's `client` and `deposit` match (free, non-flaky
  coverage that the watcher decoded ChannelOpened's non-indexed fields, not just
  the channelId topic).

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

* test(node): address Alper's review — anvil spawn retry + accurate close/watcher comments

Rebased onto main (#743 squash-merged the #327 settlement work this branch
previously carried as duplicate commits); adapted the `bootstrap` call to
main's added `pending_store` param by deriving both trait handles from the one
`PersistentChannelStateStore`, mirroring the runtime wiring.

- free_port TOCTOU: spawn anvil through a retry helper that detects an early
  exit (port stolen between probe and bind) and retries on a fresh port, with a
  per-port 20s readiness timeout. The child is owned by AnvilGuard immediately
  so every early return reaps it.
- shutdown-close comment: corrected to state that `close_all_unredeemed`
  force-closes *every* still-Open channel with unredeemed work — channel 1 also
  closes when its single redeem lands the 1 MiB interval voucher (verified: the
  run logs `closed=2`), not just channel 2.
- watcher readiness comment: corrected to reflect the four sequential `.watch()`
  filter installs (not one) and that the ordering is bridged by the sleep plus
  the intervening mint/approve roundtrips; a fully deterministic fix needs a
  prod-side readiness signal / get_logs fallback, out of scope here.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
thiras added a commit that referenced this pull request Jun 2, 2026
* feat(node): seller-settlement robustness follow-ups (#751)

Implements the seven deferred items from the PR #743 / #327 review across
correctness, robustness, observability, and type hygiene in the seller-side
payment-settlement path.

Correctness — opened-during-downtime backfill:
- Add `WatcherCheckpointStore` (persisted last-scanned `ChannelOpened` block).
  On bootstrap the watcher resumes the backfill from the checkpoint (minus a
  reorg margin, clamped to head) instead of only the bootstrap head, so a
  channel opened while the node was down is registered rather than rejected
  `WrongChannel` forever. The gap is walked in bounded `eth_getLogs` windows.
  The checkpoint is advanced past a live `ChannelOpened` only once it is
  persisted (a hold keeps the scalar checkpoint below an unpersisted open so
  the resume backfill re-covers it).

Robustness:
- Add a low-frequency redeemer self-tick that scans `load_all` for
  above-threshold channels, so a dropped advisory hint can't strand a claim.
- Quiesce (abort + await) the redeemer before the shutdown close so an
  in-flight `withdraw` can't race a `closeChannel` (benign revert + misleading
  warn); a `Drop` safety net aborts a non-gracefully-dropped redeemer.

Observability:
- New counters: `decdn_redeem_hints_dropped_total`,
  `decdn_redemption_failures_total`, `decdn_watcher_persist_failures_total`.
- Add `VoucherRejectReason::Expired` (frozen-order append) so the expiry
  serve-gate sends an actionable in-band reason instead of an opaque
  `anyhow::bail!` stream drop.

Type hygiene:
- Demote `ChannelState`'s replay-critical `last_*` fields behind a `hydrate`
  constructor + getters so the #527 "advance only via `apply_voucher`"
  invariant is compiler-enforced; `last_signature` is now `Option<[u8; 65]>`
  (empty-or-65-bytes unrepresentable-when-wrong), converted at the codec
  boundary so the on-disk format is unchanged.
- Bundle the schema-v2 trailing segments into a `TrailerV2` type (byte-identical
  on-disk layout; kept as a trailing segment for v1-record compatibility).

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

* refactor(node): address PR #781 review — sync redeemer mutex + backfill doc

- `PaymentChannelService.redeemer` uses `std::sync::Mutex` instead of
  `tokio::sync::Mutex` (gemini-code-assist): the guard is only held to `take()`
  the handle, never across an `.await`, so the async mutex was unnecessary
  overhead. Both lock sites recover a poisoned lock via
  `unwrap_or_else(PoisonError::into_inner)` rather than `unwrap`/`expect`
  (denied workspace-wide), and `Drop` now `lock()`s (uncontended under
  `&mut self`) instead of `try_lock()` so the abort still runs if poisoned.
- Fix the module-header description of the backfill floor `S` (Copilot): it is
  the *lower* of the bootstrap head and (checkpoint − reorg margin), not the
  maximum — matching `resolve_backfill_start`, so `[S, F]` covers both the
  #751 downtime gap and the #762 bring-up window.

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

* fix(node): harden #751 checkpoint against cross-arm/cross-cycle strand

Comprehensive review (silent-failure-hunter + code-reviewer) found the scan
checkpoint could advance past an unpersisted `ChannelOpened` and strand a
channel — the exact #751 failure class:

- The four watcher event streams are independent `.watch()` filters with no
  cross-stream block ordering, and the checkpoint was advanced from all four
  arms (the settled arm even on foreign-channel events). A later foreign event
  could persist the checkpoint past block N before our `ChannelOpened` at N was
  delivered and failed to persist, so the reactive `checkpoint_hold` was set too
  late; if the advance exceeded the reorg margin before a restart, N was skipped.

Fix: advance the scan checkpoint ONLY from the `opened` arm, on a successful
register (the only event that proves opens were scanned+registered through its
block). The `opened` stream is block-ordered, so the per-cycle hold covers a
later same-stream open; a failed open also re-arms `backfill_from` to its block
so a resubscribe re-covers it, and the held checkpoint makes a restart re-cover
it too. Removes checkpoint advancement from the topped_up/settled/close arms.

Also from the review:
- Add an end-to-end downtime-backfill phase to the anvil e2e (the headline #751
  proof): drop the service, `openChannel` while down, re-bootstrap against the
  same store, assert the channel is registered via the checkpoint-floored
  backfill.
- Document the deliberate `pub deposit`/`expires_at` encapsulation asymmetry and
  the `hydrate` positional-arg trust boundary (type-design review).
- Fix a module-header run-on and note the post-backfill checkpoint write never
  regresses (comment review).

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

* test(node): make the #751 downtime-backfill e2e a true discriminator

Re-review (pr-test-analyzer) found the new downtime-backfill e2e phase could
pass spuriously: without a block mined between the downtime `openChannel` and
the re-bootstrap, `head == down_block`, so the #762 within-session backfill
`[head, F]` already covers the channel — the test passed even when the #751
checkpoint floor was ignored.

- `evm_mine` after the downtime open so service2's bootstrap head is strictly
  above the channel's block; now `[head, F]` excludes it and only the persisted
  checkpoint floor (#751) can re-cover it. Verified by mutation: forcing
  `resolve_backfill_start` to ignore the checkpoint makes the phase FAIL with
  "#751 checkpoint backfill failed".
- Derive the channel id from the live `clientChannelNonce` (read pre-open)
  instead of hardcoding nonce 3, so the proof survives earlier-phase churn. Adds
  the `clientChannelNonce` getter to the `PaymentChannel` binding.
- Document (module header) that a failed *live* open-persist recovers on the
  next resubscribe/restart, not mid-cycle — a liveness window, never a strand
  (silent-failure-hunter LOW note).

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

* fix(node): address PR #781 review (Alper) — watcher recovery + doc accuracy (#751)

Review follow-ups from #781. The Gemini/Copilot items were already handled in
5fe7754; these are Alper's findings.

MEDIUM-1 (code): a live `ChannelOpened` persist failure on a healthy,
never-resubscribing stream stranded that client (vouchers rejected
`WrongChannel`) until an unrelated restart, because the re-armed backfill only
ran on the next resubscribe. `run_watcher_once` now returns a `CycleOutcome`;
on a persist failure it re-arms `backfill_from` and returns `RecoveryPending`,
so `watcher_loop` resubscribes and re-runs the backfill immediately — paced by
the existing backoff so a durable store failure backs off instead of
hot-looping. Returning on the first failure makes the in-cycle `checkpoint_hold`
redundant (the checkpoint stays <= the failed block via sole-`opened`-arm
advancement + block-ordering + the early return), so it is removed.

MEDIUM-2 (doc): spell out the load-bearing caller contract on
`advance_checkpoint` (sole caller = `opened` arm on success; `opened` stream is
block-ordered) so a refactor that feeds blocks out of order or from a second
event source is warned at the function it would break.

MEDIUM-3 (issue + doc): file #784 to debounce the `Durability::Immediate`
checkpoint write (one fsync/block on backlog drain); note the amplification and
the idempotent-floor rationale at `record_last_seen_block`. Left immediate at
testnet fan-out.

HIGH (doc): correct the `redeem_sweep` doc — the `withdrawn_cache` starts empty,
so the first sweep after boot issues one `getChannel` per above-threshold
channel (O(channels) fan-out), not "cheap on a warm cache."

LOW (doc): clarify the `redeem_hint` drop metric counts `Full` (real drop) and
deliberately not `Closed` (expected at shutdown); soften the `quiesce_redeemer`
claim from eliminating to narrowing the withdraw-vs-`closeChannel` race (an
already-broadcast tx can still mine); note `MAX_BACKFILL_BLOCK_SPAN` bounds block
span, not result count.

Gates: clippy/fmt/doc clean; 380 node tests + anvil e2e pass.

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.

Implement on-chain CapacityBond and PaymentChannel contract integration

3 participants