Repository navigation
feat(node): buyer-side PaymentChannel openChannel for cache-miss settlement (#744) - #753
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]>
…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]>
…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]>
… 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]>
… 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]>
…lement (#744) Split out from #327 (PR #743, seller settlement). Implements the buyer-side on-chain path from ADR 003 §node→node: when a node pulls content from an upstream provider on a cache miss it acts as the client — opening a channel, signing cumulative vouchers (the voucher signer already existed in client_requester), and reclaiming its deposit if the upstream abandons the channel. Scope is the channel-management layer; wiring the cache engine's miss path to call it needs provider-discovery (ADR 001/022) and stays out of scope, so the service is bootstrapped (approval + reclaim sweep) but the hook that drives buys is not yet wired. What's in this PR: - incentive: sol! bindings for openChannel/topUp/reclaimExpired + clientChannelNonce/minDeposit + ChannelExpiredReclaimed; a minimal ERC-20 binding (erc20.rs) for the one-time USDC approval; provider-keyed BuyerChannelState (+ advance() monotonic mutator), BuyerChannelStore trait (incl. forget_if_channel compare-and-delete) and MemoryBuyerChannelStore. - node: PersistentBuyerChannelStore as a second redb table on the shared store handle (redb forbids two handles to one file), exposed via BuyerChannelStoreHandle; BuyerChannelService (one-time max approve at startup, lazy open + per-provider reuse with channelId derived under a serialization lock and cross-checked on-chain, record_progress, top_up, and a background reclaim sweep using forget_if_channel to avoid lost updates); ChannelContext::for_buyer_channel resume helper; runtime bootstrap (non-fatal — a buyer failure never blocks the seller path). - common: buyer_deposit_micro_usdc (default 10 USDC) + buyer_max_approve config. Verification: fmt, clippy --workspace --all-targets -D warnings, 1289 tests, rustdoc -D warnings, cargo deny; anvil e2e extended to drive the buyer path end-to-end (approve → openChannel → voucher delivery → reuse → top_up → reclaimExpired full-deposit refund). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request implements the on-chain buyer-side payment-channel service, bookkeeping, and storage to support paid cache-miss pulls. It introduces configuration parameters, ERC-20 bindings for one-time USDC approvals, persistent buyer-channel storage using redb, and a background sweep task to reclaim expired deposits. Feedback on the implementation highlights two key improvements: first, to avoid orphaned channels and double-deposits on transient RPC failures, the service should decode the ChannelOpened event directly from the transaction receipt logs instead of making an extra getChannel query; second, the reclaim sweep should explicitly handle zeroed client addresses for settled channels to prevent misleading 'bogus record' warnings.
…eclaim-before-reopen - open_or_reuse_channel: decode the ChannelOpened event from the openChannel tx receipt for channelId + expiresAt instead of a follow-up getChannel. The read was non-atomic — a transient RPC failure after a successful open left the on-chain deposit escrowed but untracked (orphaned, re-opened on the next miss). Decoding the receipt log is atomic with the open. This also removes the clientChannelNonce read, local channelId derivation, and the open_lock (all only needed for the now-gone derive path), plus the clientChannelNonce binding. (gemini-code-assist, high) - open_or_reuse_channel: when a tracked channel is expired, reclaim it BEFORE opening a replacement. The store is provider-keyed, so the old reuse-then- overwrite path dropped the expired record before the reclaim sweep could see it — silently abandoning a refundable deposit. Now try_reclaim runs inline and, if the record can't be cleared, the open errors instead of overwriting. - Document the per-provider concurrency requirement on open_or_reuse_channel. - Doc fixes: openChannel + ChannelOpened binding docs now describe the receipt- decode path (not local derivation). Not changed: the "settled channel returns zeroed client" medium comment is a false positive — PaymentChannel sets status=Closed but never deletes the struct, so a settled channel keeps client==self and is handled by the status check; client==0 means a genuinely phantom record where the warning is correct. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Review — buyer-side openChannel (#753)Reviewed the incremental diff against #752. The store layering (two redb tables, distinct key widths, CAS-on-delete), the receipt-event channelId derivation, and the 1. One corrupt buyer record silently disables the entire buyer path + all reclaims —
|
a6b85c7 to
5b6295c
Compare
…annel # Conflicts: # crates/cli/tests/config_validate.rs # crates/common/src/config/mod.rs # crates/common/src/config/resolved.rs # crates/common/src/config/types.rs # crates/incentive/src/lib.rs # crates/incentive/src/payment_channel.rs # crates/incentive/src/store.rs # crates/node/src/channel_store.rs # crates/node/src/payment_settlement.rs # crates/node/src/runtime/mod.rs # crates/node/src/runtime/reload.rs # crates/node/tests/anvil_settlement_e2e.rs # crates/node/tests/sighup_signal.rs
… + per-provider open guard Item 1 (real bug): `buyer_load_all` propagated an error on a single undecodable record, so one corrupt/forward-incompatible row failed buyer bootstrap *before* the reclaim sweep was spawned (and the runtime makes buyer bootstrap non-fatal). Net effect: one bad row left every other tracked channel's deposit unreclaimable and blocked all new opens. Now skip-and-`warn!` per record during hydration (the seller `load_all` still fails loud because its bootstrap is fatal — the #527 replay window). The point lookup `get_by_provider` still surfaces the precise decode error. Existing `*_rejected` tests retargeted to assert the skip-keeps-healthy contract. Item 2 (make the documented invariant real): per-provider in-flight-open set (`opens_in_flight`) serializes opens — a concurrent `open_or_reuse_channel` for a provider already mid-open bails for retry rather than escrowing a second deposit whose `record` would orphan the first. Fast-path reuse never touches the set (no contention for the common many-pulls-to-one-open-provider case); the open path claims the slot then re-checks reuse to close the TOCTOU. RAII guard releases on every exit path. Item 3 (clock-skew bail): kept as-is — the documented "never drop funds" tradeoff stands. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Thanks @alpergundogdu — all three addressed in eff580c (on top of a 1. One corrupt buyer record disables the whole buyer path + all reclaims — fixed, this was real. 2. Stale lock narrative + unenforced per-provider serialization — both fixed. The PR description/design-notes no longer describe the removed 3. Clock-skew boundary refuses a still-usable channel — kept as-is, as you flagged it [your call]. The "never drop funds" tradeoff stands: prioritizing not-orphaning an escrowed deposit over buy-availability during the rare skew window is the right default while the cache-miss hook isn't wired yet. Easy to revisit (reuse-when-chain-still-open) if buy-availability turns out to matter more in practice. Verification: |
Coverage reportTotal: 86.94% (was 87.79%, ▼ 0.85%) — 25076/28844 lines
History
|
…tion, type-enforced open guard, comment rot - **Comment rot** (comment-analyzer): `BuyerChannelState` field docs still described the removed `getChannel`-at-open cross-check; corrected to the receipt-event derivation actually used. - **Type-enforced open guard** (type-design + pr-test, convergent): fold the set-insert and the RAII guard into one `InFlightOpenGuard::claim` constructor, so the one-open-per-provider invariant can't be violated by construction. The unit test now exercises that production constructor instead of a hand-copied claim closure (the prior test was a tautology). - **Orphaned-deposit escalation** (silent-failure C1): once `openChannel` escrows the deposit, the two post-escrow failure paths (missing `ChannelOpened` event, persist failure) now `error!` with the tx hash so an operator can reconcile/reclaim manually — the buyer path has no chain-log reconciliation yet (tracked as follow-up to the cache-miss hook). Extracted the open+persist tail into `open_and_persist`. - **Hydration skip severity** (silent-failure I1): `buyer_load_all` logs a skipped undecodable record at `error!` (was `warn!`) — its escrowed deposit is unreclaimable until repaired, so it must not be filtered from alerting. Deferred as follow-ups (need the not-yet-wired cache-miss hook / anvil infra): bootstrap chain-log reconciliation scan; anvil e2e concurrent-open and mixed corrupt/healthy multi-row reclaim-sweep coverage. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Deferred follow-ups from the multi-agent review (orphan-deposit bootstrap reconciliation + anvil e2e for concurrent-open / mixed-corrupt multi-row reclaim) are tracked in #763 — both gated on the not-yet-wired cache-miss hook. The post-escrow |
…tion, type-enforced open guard, comment rot - **Comment rot** (comment-analyzer): `BuyerChannelState` field docs still described the removed `getChannel`-at-open cross-check; corrected to the receipt-event derivation actually used. - **Type-enforced open guard** (type-design + pr-test, convergent): fold the set-insert and the RAII guard into one `InFlightOpenGuard::claim` constructor, so the one-open-per-provider invariant can't be violated by construction. The unit test now exercises that production constructor instead of a hand-copied claim closure (the prior test was a tautology). - **Orphaned-deposit escalation** (silent-failure C1): once `openChannel` escrows the deposit, the two post-escrow failure paths (missing `ChannelOpened` event, persist failure) now `error!` with the tx hash so an operator can reconcile/reclaim manually — the buyer path has no chain-log reconciliation yet (tracked in #763, gated on the cache-miss hook). Extracted the open+persist tail into `open_and_persist`. - **Hydration skip severity** (silent-failure I1): `buyer_load_all` logs a skipped undecodable record at `error!` (was `warn!`) — its escrowed deposit is unreclaimable until repaired, so it must not be filtered from alerting. Deferred as follow-ups in #763 (need the not-yet-wired cache-miss hook / anvil infra): bootstrap chain-log reconciliation scan; anvil e2e concurrent-open and mixed corrupt/healthy multi-row reclaim-sweep coverage. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
c0073ea to
9031c34
Compare
…re into a shared table (#1246) (#1257) * test(incentive): pin the buyer record encoding with a golden-bytes test The buyer record's on-disk layout is shared by two independent stores — `incentive`'s `buyer-channels.redb` and the node's `channels.redb` — but the contract between them is asserted only by a doc comment ("Byte-compatible with the node's buyer table", buyer_channel_redb.rs). Nothing tested it, so the two encoders could drift silently. Postcard encodes struct fields positionally and unnamed, so reordering or retyping a field rewrites the bytes with no compile error and no test failure: every suite builds a fresh tempdir store, so they all still pass while every record an older binary wrote is orphaned. Pin the layout with a golden. The fixture is byte-for-byte the state the node's `buyer_sample(7)` builds, so the golden also pins the two crates' encoders to each other — verified: incentive's encoder reproduces the node's bytes exactly, so the byte-compat claim held. Lands ahead of #1246, which hoists this codec into a shared module, so the tripwire is in place before the code moves. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(incentive): add the shared buyer-channel table codec and ops (#1246) The buyer-channel redb store exists twice: once in `decdn-node`'s `channel_store` (combined seller+buyer `channels.redb`) and once here as `RedbBuyerChannelStore` (buyer-only `buyer-channels.redb`). They differ only in which file they own — redb forbids two `Database` handles on one file, so the node cannot adopt the buyer-only store — but that file-ownership difference costs a second copy of the record codec AND of every table operation, with byte-compatibility maintained by hand. Add `buyer_channel_table`: the on-disk codec plus the seven table ops, parameterized over the caller's `&Database` + `TableDefinition`. Both stores can now delegate and keep only their own file wiring. Design notes: - One module, not two: the codec's only non-test consumer is the ops, so keeping them together lets `StoredBuyerChannelState` stay fully private — the on-disk shape is unnameable outside this module. - The table *name* is shared (`BUYER_CHANNEL_TABLE_NAME`) while each store keeps its own `TableDefinition` built from it, so name drift is structurally impossible and the key/value types are pinned by the `BuyerTableDef` signature. - A `BuyerChannelTable` handle rather than free functions: binding (db, table) once keeps `advance_progress` under too_many_arguments, which a free fn would sit exactly at. - `insert_raw` is pub, not cfg(test): a cross-crate cfg(test) does not propagate, so a gated seam could not serve the node's own `insert_raw_buyer_record` (#763 e2e). It needs a `&Database`, which neither store exposes. - `begin_durable_write` makes `Durability::Immediate` structural rather than repeated at six call sites where it could be forgotten. - `TableDefinition` has no `Debug` impl, so `BuyerChannelTable` needs a hand-written one to satisfy missing_debug_implementations. New `buyer-store-core` feature holds this; `redb` now implies it and adds only `RedbBuyerChannelStore`, so a bare `decdn-incentive` build still links neither redb nor postcard (verified via cargo tree). Ports the node's bodies verbatim (they carry the richer rationale) with this crate's `table_exists` factoring. No caller is rewired yet — the transient duplication is deliberate so the follow-ups are pure deletion. Tests port the node's 12 buyer tests, plus two additions: - `no_row_ops_do_not_create_the_table`: the node's suite asserted the outcomes but never the "no table" half of its own claim — a dropped pre-check is exactly what this refactor could regress. - `load_all_returns_every_recorded_channel`, imported from this crate's suite (the only test with no node twin). Module doc links are fully qualified and `buyer_channel_redb` is a code span, not a link: rustdoc merges the outer `///` on the `lib.rs` module declaration with the inner `//!` docs and resolves in *that* scope, and linking a `redb`-gated item breaks a `buyer-store-core`-only doc build. Both failures are hidden by the workspace-wide CI doc job's feature unification; verified against each feature config separately. Co-Authored-By: Claude Fable 5 <[email protected]> * refactor(incentive): delegate RedbBuyerChannelStore to the shared buyer table Drop this store's private copy of the record codec (`StoredBuyerChannelState`, `From`, `into_state`, `decode_buyer_record`), its schema/trailer constants, `write_state`, `table_exists`, and all seven `BuyerChannelStore` bodies. Each method is now a one-line delegation to `buyer_channel_table`. What stays is what is actually specific to this store: it owns `buyer-channels.redb`, so it keeps `open()` verbatim — the zero-length-file guard (redb treats "empty" as "create fresh", which would silently wipe the watermark) and the DatabaseAlreadyOpen → StoreError::AlreadyOpen mapping (#942). The table const stays too, but is now built from the shared BUYER_CHANNEL_TABLE_NAME, so the on-disk name has one definition. 670 → 288 lines, with no change to the on-disk format: the golden test moves with the codec and still passes. Tests drop to the four that earn their place here: the two `open()` guards, the cross-invocation watermark resume (#940), and a new `store_delegates_every_op`. That last one covers the gap the shared suite structurally cannot — it proves the operations are correct but not that this store's seven delegations reach the matching one, so a transposition (`forget` wired to `forget_if_channel`) would otherwise pass everything. The five tests deleted here are subsumed by the shared suite, which also gives this store the decode-edge-case coverage (schema, trailer, key mismatch) it never had. Co-Authored-By: Claude Fable 5 <[email protected]> * refactor(node): delegate the buyer channel store to decdn-incentive (#1246) The buyer half of this file was a byte-identical re-implementation of `decdn-incentive`'s buyer store: same table name, same key/value types, same 9-field postcard record, same take_from_bytes decode, same skip-undecodable-row load_all. Only the *file* differed — this store needs the buyer table inside `channels.redb` next to the seller, pending-settle, and watcher-checkpoint tables, because redb forbids two `Database` handles on one file. That is wiring, not logic, so keep the wiring and drop the logic. Delete the codec (`StoredBuyerChannelState`, `From`, `into_state`, `decode_buyer_record`), `BUYER_SUPPORTED_SCHEMA_VERSION`, and the entire ~360-line inherent `buyer_*` block — whose only caller was `BuyerChannelStoreHandle`'s trait impl, which now delegates straight to `decdn_incentive::buyer_channel_table` via `&self.inner.db`. What stays: the `BUYER_CHANNEL_TABLE` const (now built from the shared `BUYER_CHANNEL_TABLE_NAME`, so the on-disk name has one definition), `SANE_TRAILER_MAX_BYTES` (the seller decode still uses it), and `insert_raw_buyer_record` with its signature verbatim — the #763 e2e depends on it — now a thin call to the shared `insert_raw`. `BuyerChannelStoreHandle` survives for the reason it was introduced: implementing `BuyerChannelStore` on `PersistentChannelStateStore` would collide with `ChannelStateStore`'s load_all/record/forget. Its rationale moves onto the type. Its `table()` cannot be const (it derefs an Arc). channel_store.rs: 2740 → 1926 lines. No on-disk change — the table name, key/value types, and record layout are unchanged, and the golden-bytes test pins the encoding. Tests: 12 of the 14 buyer tests move to the shared suite, where the code they cover now lives. Two stay, because only they test what this file still contributes: - `buyer_and_seller_tables_are_independent` — co-tenancy of five tables in one file; incentive has no seller table, so this is unreachable there. - `buyer_handle_delegates_every_op` (new) — the shared suite proves the ops are correct but not that these seven delegations reach the matching one; the co-tenancy test only exercises three of seven. Also drops a stale comment: the future-schema test's doc claimed the record "must refuse to load — same safety posture as the seller table", but buyer load_all deliberately *skips* it (PR #753) — the opposite of the seller's abort-on-error. That asymmetry is now documented on the shared `load_all`, with the reason it must not be "unified". decdn-node enables `decdn-incentive/buyer-store-core` (not `redb`), so it compiles the shared table without the client-only `RedbBuyerChannelStore`. Rewords the e2e `anvil-e2e` comment, whose claim that default builds skip the postcard code no longer holds (and never did: postcard arrives via decdn-protocol regardless). Co-Authored-By: Claude Fable 5 <[email protected]> * refactor(incentive,node): address review of the buyer-table hoist (#1246) Multi-agent review found several real defects. Each was reproduced before being fixed. **The hoist missed one operation.** `insert_raw_buyer_record` still hand-rolled its own begin_write/set_durability/open_table/insert/commit instead of delegating — the 8th write path, left duplicated. Worse, the doc on the shared `insert_raw` justified its `pub` by claiming that seam needed it, describing a call that did not exist. Node's seam now delegates, which makes the claim true, removes the last duplicated table op, and makes the file's "keeps only the wiring" banner literally true (verified: zero redb txn machinery remains in node's buyer section). **Drop the `TableDefinition` parameter.** Its parameter space had exactly one inhabitant — both stores and the tests passed the same value — while admitting `TableDefinition::new("typo_v1")`, which compiles, reads an empty table, and tells the reclaim sweep there is nothing to reclaim. That is worse than the duplicated code it replaced, where the name was a private const beside its use. The table is a frozen global, not a per-call knob: it is now one private const, `BuyerChannelTable::new(db)` takes only the file (the sole thing the two stores legitimately differ on), `BuyerTableDef`/`BUYER_CHANNEL_TABLE_NAME` are private, both stores' consts are gone, and the hand-written Debug reverts to a derive. The invariant became structural and the diff got smaller. **The golden test could not catch the swap that matters most.** With `state(7)`, `channel_id` is 32 bytes ending 07 and `last_nonce` is `U256::from(7)` — the same 32 bytes — so transposing them encoded identically and the tripwire passed. That is the catastrophic pair: `channel_id` guards the CAS in forget_if_channel and advance_progress. The fixture now uses a distinct pattern per field, regenerated from main's encoder so it still pins the format across the hoist. Verified it now fails all five same-typed swaps, including that one. **Two proven test gaps** (found by mutation, fixed, and re-verified — each mutant now fails where it previously survived): - The in-txn UnknownProvider branch (table present, row absent) was untested; only the table_exists() short-circuit was. A deleted test had covered it. - The delegation tests asserted only the outcome enum, so passing bytes_delivered where amount belongs — a payment-watermark corruption — passed. They now assert the row. Their rationale also named an impossible example: the types already reject `forget` wired to `forget_if_channel`; the reachable mistake is argument order among the U256s, which is exactly where they were weakest. **`insert_raw` moves behind a `test-util` feature** rather than shipping `pub`, matching decdn-client-pull's precedent. Confirmed absent from the public API docs with the feature off. **Comments that were false:** - `redb`/`buyer-store-core` never gated out postcard — decdn-protocol pulls it unconditionally. Two comments claimed otherwise while the e2e comment (correctly) said the opposite. - The `dep:redb` NOTE described a feature-name collision. Cargo actually rejects the manifest with "optional dependency `redb` is not included in any feature" — a maintainer would have hunted the wrong error. - The table_exists TOCTOU note said the op "falls through to a get miss"; it returns early. The race is real but different, and still benign. - `RedbBuyerChannelStore::open` lost its doc + # Errors in the rewrite. - The load_all skip claims the operator gets the provider address. True for the node, which installs a subscriber — but decdn-cli has no tracing dependency at all, so for the client store the skip is silent: `channel clean` can report "no tracked channels to clean" while the deposit is escrowed. Pre-existing and not fixable without changing the BuyerChannelStore trait, so the doc now says so plainly instead of implying coverage that isn't there. Follow-up issue to come. **Also:** a reciprocal "do not unify" note on the seller load_all (the asymmetry now spans two crates, and that is the direction a maintainer arrives from); a decode-direction golden (the encode golden couldn't catch a matched encoder/decoder drift); load_all asserts providers, not just a count; the outer /// docs on the lib.rs mod declarations are gone, which removes the rustdoc merged-scope trap at its root along with ten lines of commentary explaining it. **CI:** `--workspace` unifies features, so decdn-cli turns on incentive/redb for everyone and the two configurations this feature split exists to create were never compiled. Both are real (a plain `cargo build -p decdn-node`; any consumer taking decdn-incentive alone). Added two direct clippy runs. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
Closes #744.
Context
Split out from #327 (PR #743, seller settlement). Implements the buyer-side on-chain path from ADR 003 §node→node: when a node pulls content from an upstream provider on a cache miss it acts as the client — opens a
PaymentChannel, signs cumulative vouchers (the voucher signer already existed inclient_requester), and reclaims its deposit if the upstream abandons the channel.Stack collapsed: the lower PRs (#743 seller settlement, #752 anvil e2e) have merged to
main, andmainis now merged into this branch (the sellerPendingSettlesettlement-sweep work is integrated; the anvil e2e harness carries both seller and buyer coverage). This PR now diffs againstmaindirectly.Scope (channel-management layer only)
Wiring the cache engine's miss path to call
open_or_reuse_channelneeds provider-discovery (NodeId→eth-address, dialable target) whichclient_requesterdeclares out of scope (ADR 001/022). So the service is bootstrapped (one-time approval + reclaim sweep) and exposes the API that future hook will call, but the hook that drives buys is not yet wired. Dispute monitor deferred (#324).What's in this PR
sol!bindings foropenChannel/topUp/reclaimExpired+minDeposit+ChannelExpiredReclaimed; a minimal ERC-20 binding (erc20.rs) for the one-time USDC approval; provider-keyedBuyerChannelState(with anadvance()monotonic mutator),BuyerChannelStoretrait (incl.forget_if_channelcompare-and-delete) +MemoryBuyerChannelStore.PersistentBuyerChannelStoreas a second redb table (buyer_channel_state_v1) on the shared store handle (redb forbids twoDatabasehandles to one file), exposed viaBuyerChannelStoreHandle;BuyerChannelService— one-time max approve at startup, lazy open + per-provider reuse (channelId +expiresAtdecoded from theopenChanneltx-receiptChannelOpenedevent, atomic with the open),record_progress,top_up, and a background reclaim sweep that usesforget_if_channelto avoid clobbering a concurrently-reopened channel;ChannelContext::for_buyer_channelresume helper; runtime bootstrap that is non-fatal (a buyer-path failure never blocks the seller settlement path).buyer_deposit_micro_usdc(default 10 USDC, ADR 003 § Deposit Economics) +buyer_max_approveconfig.Design notes
openChanneltx mines, thechannelId+expiresAtare decoded from itsChannelOpenedevent log (filtered onclient/provider== self). This is atomic with the open — a successful tx guarantees the event is present, so the channel is always persistable; there is no localkeccak256(client, provider, nonce)derivation, noopen_lock, and no follow-upgetChannelwhose transient failure could orphan the escrowed deposit.opens_in_flight) serializes opens per provider — a concurrentopen_or_reuse_channelfor a provider already mid-open bails for retry rather than escrowing a second deposit whoserecordwould orphan the first. The reuse fast-path never touches the set (no contention when a channel already exists); the open path claims the slot then re-checks reuse to close the TOCTOU.buyer_load_allskips-and-warn!s on a single undecodable record rather than failing the whole load. Because buyer bootstrap is non-fatal and gates the reclaim-sweep spawn, a propagated error would otherwise leave every other tracked channel's deposit unreclaimable. (The sellerload_allstill fails loud — its bootstrap is fatal by design, guarding the incentive: no replay-protection window enforced on incoming voucher nonces, allowing a client to resubmit a previously accepted voucher after a node restart and receive a second byte-delivery for the same payment #527 replay window.)[u8;20]buyer vs[u8;32]seller); the buyer ops are inherentbuyer_*methods + a thinBuyerChannelStoreHandleadapter to avoid trait-method-name collisions on the shared concrete store.block.timestamp >= expiresAtcheck is the real gate, and a compare-and-delete (forget_if_channel) prevents a sweep from dropping a freshly-reopened channel.Review
Ran the multi-agent PR review toolkit; addressed the high-value findings (reclaim lost-update CAS fix, ownership assertion, actionable bootstrap warning, type-design encapsulation/invariant docs + promoted
advance, two binding-doc accuracy fixes, and added buyer-store corrupt/mismatch/trailing-bytes/CAS tests + e2etop_upcoverage).Verification
cargo fmt --check,clippy --workspace --all-targets -D warnings, 1302 tests pass (post-merge withmain),rustdoc -D warnings,cargo deny. The anvil e2e (--features anvil-e2e) drives the buyer path end-to-end:approve → openChannel → voucher delivery → reuse → top_up → reclaimExpiredwith a verified full-deposit refund andClosedstatus. No Solidity changes (the contract already ships these functions).🤖 Generated with Claude Code