Repository navigation
feat(node): on-chain PaymentChannel seller settlement + CapacityBond rename (#327) - #743
Conversation
…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]>
There was a problem hiding this comment.
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.
Coverage reportTotal: 87.79% (was 89.52%, ▼ 1.73%) — 24331/27715 lines
History
|
There was a problem hiding this comment.
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
PaymentChannelABI 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.
…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]>
Review — seller settlement (#743)Reviewed the incremental diff against
One thing worth a decision
The doc comments ( [your call] — if this is deliberately deferred to the dispute monitor (#324), fine; consider either (a) not 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]>
…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]>
…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]>
…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]>
* 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]>
Closes #327 (seller-side scope).
Context
Issue #327 had drifted heavily. The poc-blocking part — the
CapacityBondregistry read-path — was already implemented asChainStakerSet. The blocking dependencyPaymentChannel.sollanded in #716, so the real remaining work is the on-chainPaymentChannelclient (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 usesEIP712("PaymentChannel", "1"). EverycloseChannel/withdrawwould have reverted withInvalidVoucherSignaturedespite off-chain verification passing. Fixed and pinned with a regression test asserting the domain matches the contract literal.What's in this PR
incentive:PaymentChannelsol!bindings (reads + writes + lifecycle events), validated field-for-field against the compiled ABI.voucher: EIP-712 domain fix + regression test.getpoint-lookup to theChannelStateStoretrait.node:PaymentChannelService— watchesChannelOpened(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 thresholdwithdraw(hinted from the voucher-accept path) and best-effortcloseChannelon graceful shutdown, with on-chainv-byte normalization (0/1 → 27/28).usdc()startup self-check,redeem_threshold_micro_usdcconfig (default 1 USDC), shutdown close hook.Renames
StakingRegistry→CapacityBond(matching the on-chain contract):blockchain.staking_registry_address→blockchain.capacity_bond_address--staking-registry-address→--capacity-bond-addressDECDN_STAKING_REGISTRY_ADDRESS→DECDN_CAPACITY_BOND_ADDRESSAcceptable 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 compiledPaymentChannel.jsonABI (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)
openChannelfor node→node cache-miss pulls (ADR 003 §node→node)disputeChannel(Implement cdn/watchtower/v1 channel dispute monitoring protocol #324)🤖 Generated with Claude Code