Skip to content

arkchannel: Add durable channel lifecycle - #1190

Open
sputn1ck wants to merge 7 commits into
kon/ark-channel-oor-fundingfrom
kon/ark-channel-lifecycle
Open

sputn1ck wants to merge 7 commits into
kon/ark-channel-oor-fundingfrom
kon/ark-channel-lifecycle

Conversation

@sputn1ck

@sputn1ck sputn1ck commented Aug 24, 2026 •

Copy link
Copy Markdown
Member

Summary

A client promotes its VTXOs to open a channel. The lifecycle records the exact source, backing transaction, and both endpoints' funding and recovery evidence before releasing the prepared OOR transfer. Opening a channel is separate from receiving a payment.

  • Persist revision-checked snapshots and recovery packages under the authenticated peer in one channel schema.
  • Resume the next action from durable state, including when the source approaches expiry while the peer is offline.
  • For a cooperative close, bind the receipt to the signatures on the actual payout. A transaction ID alone does not prove the client can collect.
  • Track the payment circuit separately from the channel that carries it.

Layer 2 of 5. Base: #1189. Next: #1191.

Copilot AI lite review requested due to automatic review settings August 24, 2026 14:37

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 introduces the core “Ark channel” lifecycle plumbing across transport, persistence, and protocol surfaces. It extends the mailbox connector to support per-connector reply mailboxes and runtime namespaces, and adds a new arkchannel domain package with durable coordination logic, DB storage/migrations, and RPC protos.

Changes:

  • Add RuntimeID + ReplyMailboxID support to serverconn so multiple independent connectors can share an authenticated identity while isolating ingress and durable state.
  • Introduce Ark-channel coordination domain (arkchannel) including actions/events, cooperative close + backing validation logic, and bridges to OOR + unroll subsystems.
  • Add SQL migrations + sqlc queries/models and protobuf definitions for Ark-channel control and peer protocols.

Reviewed changes

Copilot reviewed 49 out of 51 changed files in this pull request and generated no comments.

Show a summary per file
File Description
serverconn/unary_facade.go Set RPC ReplyTo using the configured reply mailbox.
serverconn/unary_facade_test.go Assert default and isolated reply-mailbox behavior.
serverconn/types.go Add RuntimeID/ReplyMailboxID and helper replyMailboxID().
serverconn/runtime.go Namespace durable actor IDs via runtimeID().
serverconn/runtime_test.go Verify distinct runtime IDs don’t collide across runtimes.
serverconn/ingress.go Pull/Ack/log using reply mailbox; namespace checkpoints by runtime ID.
serverconn/ingress_error_test.go Verify ingress uses ReplyMailboxID for Pull/Ack.
serverconn/heartbeat.go Use reply mailbox for heartbeat RPC ReplyTo.
serverconn/actor.go Add runtimeID() helper; use reply mailbox for client event/unary sends.
scripts/gen_protos.sh Generate protos for the new rpc/arkchannelrpc package.
rpc/arkchannelrpc/ark_channel.proto Define Ark-channel local control RPCs + authenticated peer services/messages.
db/store.go Add NewArkChannelStore constructor on db.Store.
db/sqlc/schemas/generated_schema.sql Include ark_channels table and indexes in generated schema output.
db/sqlc/queries/ark_channels.sql Add sqlc queries for Ark channel CRUD/CAS/list operations.
db/sqlc/querier.go Extend sqlc Querier with Ark channel query methods.
db/sqlc/models.go Add sqlc model struct for ArkChannel.
db/sqlc/migrations/000019_ark_channels.up.sql Create initial ark_channels table + indexes.
db/sqlc/migrations/000019_ark_channels.down.sql Drop ark_channels table.
db/sqlc/migrations/000020_ark_channel_recovery.up.sql Add recovery-related columns to ark_channels.
db/sqlc/migrations/000020_ark_channel_recovery.down.sql Remove recovery-related columns.
db/sqlc/migrations/000021_ark_channel_pre_ponr_expiry.up.sql Add pre_ponr_started_at and backfill for existing rows.
db/sqlc/migrations/000021_ark_channel_pre_ponr_expiry.down.sql Drop pre_ponr_started_at.
db/migrations.go Bump LatestMigrationVersion to 21.
db/ark_channel_store_test.go End-to-end coverage for Ark channel store persistence + CAS behavior.
arkchannel/unrollbridge/controller.go Bridge Ark channel materialization to the unroll registry + policy resolver.
arkchannel/unrollbridge/controller_test.go Unit tests for unroll bridge admission + resolver behavior.
arkchannel/types.go Define core Ark-channel terms, phases, bindings, backing validation, and cloning.
arkchannel/service.go Service layer coordinating durable state transitions + executing actions.
arkchannel/service_test.go Service workflow tests including replay/resume/error aggregation.
arkchannel/recovery.go Define/export recovery package structures + validation/cloning.
arkchannel/recovery_test.go Validate deep clone behavior for recovery packages.
arkchannel/payment_bridge_test.go Add tests covering payment-bridge invariants and transitions (test-only changes shown).
arkchannel/oorbridge/preparer.go Implement durable OOR preparation/lookup flow for channel-policy VTXO creation.
arkchannel/oorbridge/controller.go Implement commit/abort control + terminal result mapping for prepared OOR sessions.
arkchannel/native_executor.go Route Ark-channel durable actions into native subsystems (OOR/unroll/lnd adapters).
arkchannel/native_executor_test.go Verify executor dispatch + funder-only fencing of OOR control paths.
arkchannel/events.go Define sealed event + action types for the Ark-channel FSM boundary.
arkchannel/coordinator.go Durable coordinator for CAS-based event application and resumable actions.
arkchannel/cooperative_close.go Deterministic cooperative close proposal/template + signature verification.
arkchannel/cooperative_close_test.go Cooperative close invariants + canonical proposal/signature tests.
arkchannel/backing.go Validate/construct backing tx template and final signed backing record.
arkchannel/backing_test.go Backing template validation and negative-case tests.
Files not reviewed (1)
  • db/sqlc/ark_channels.sql.go: Generated file

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ebd9381555

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread arkchannel/types.go Resolved
Comment thread arkchannel/state.go Resolved
@sputn1ck sputn1ck changed the title kon/ark channel lifecycle arkchannel: Add durable channel lifecycle Aug 24, 2026
@litbot-9000

litbot-9000 commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

📚 Per-package doc advisory

This PR's Go changes touch four documented packages — db, db/sqlc, mailbox/rpc, and serverconn. db, db/sqlc and serverconn were already updated in the PR; the remaining drift is the new correlation-ID/idempotency-key split in serverconn.UnaryFacade.SendRPC (undocumented in both serverconn and mailbox/rpc), the relaxed RetryWithKey contract in mailbox/rpc, and the migration list in db/CLAUDE.md, where 000022–000024 were inserted ahead of 000021 (and 000020 was never listed).

diff --git a/db/AGENTS.md b/db/AGENTS.md
index 8fede44f..63158871 100644
--- a/db/AGENTS.md
+++ b/db/AGENTS.md
@@ -407,6 +407,17 @@ when adding one.
   post-step detects the old refresh/exit collision and reconstructs the
   missing net exit-send row from the surviving refresh-send and exit-fee rows,
   repairing the overstated VTXO balance atomically with the key rewrite.
+- `000020_taproot_asset_vtxo_state` — adds the asset columns on `vtxos`
+  (`taproot_asset_root`, `taproot_asset_ref`, `taproot_asset_amount`, and the
+  optional `taproot_asset_sealed_package`). Units are an 8-byte BLOB so the
+  full uint64 range survives on both SQLite and Postgres, and a column-group
+  check makes the asset identity all-or-nothing.
+- `000021_round_admission_deadlines` — records accepted attempt expiry and
+  closure separately from signature checkpoints. Deadline constraints only
+  shorten the saved budget. Startup closes interrupted admissions without
+  changing checkpoints or releasing reservations; the existing VTXO recovery
+  boundary remains authoritative. `CommitState` closes admission atomically
+  with its signature-bearing checkpoint.
 - `000022_ark_channels` — creates `ark_channels`, one revisioned row per
   Ark-to-lnd channel. It stores only facts that cross the two databases;
   Lightning commitments, HTLCs, invoices, and payment attempts remain in lnd.
@@ -425,13 +436,6 @@ when adding one.
   Existing rows are backfilled from `updated_at` only when preparation had
   begun: phase 1 or 2 with an OOR session.
 
-- `000021_round_admission_deadlines` — records accepted attempt expiry and
-  closure separately from signature checkpoints. Deadline constraints only
-  shorten the saved budget. Startup closes interrupted admissions without
-  changing checkpoints or releasing reservations; the existing VTXO recovery
-  boundary remains authoritative. `CommitState` closes admission atomically
-  with its signature-bearing checkpoint.
-
 ## Deep Docs
 
 - [ARCHITECTURE.md](../ARCHITECTURE.md) — System-wide package map.
diff --git a/db/CLAUDE.md b/db/CLAUDE.md
index 8fede44f..63158871 100644
--- a/db/CLAUDE.md
+++ b/db/CLAUDE.md
@@ -407,6 +407,17 @@ when adding one.
   post-step detects the old refresh/exit collision and reconstructs the
   missing net exit-send row from the surviving refresh-send and exit-fee rows,
   repairing the overstated VTXO balance atomically with the key rewrite.
+- `000020_taproot_asset_vtxo_state` — adds the asset columns on `vtxos`
+  (`taproot_asset_root`, `taproot_asset_ref`, `taproot_asset_amount`, and the
+  optional `taproot_asset_sealed_package`). Units are an 8-byte BLOB so the
+  full uint64 range survives on both SQLite and Postgres, and a column-group
+  check makes the asset identity all-or-nothing.
+- `000021_round_admission_deadlines` — records accepted attempt expiry and
+  closure separately from signature checkpoints. Deadline constraints only
+  shorten the saved budget. Startup closes interrupted admissions without
+  changing checkpoints or releasing reservations; the existing VTXO recovery
+  boundary remains authoritative. `CommitState` closes admission atomically
+  with its signature-bearing checkpoint.
 - `000022_ark_channels` — creates `ark_channels`, one revisioned row per
   Ark-to-lnd channel. It stores only facts that cross the two databases;
   Lightning commitments, HTLCs, invoices, and payment attempts remain in lnd.
@@ -425,13 +436,6 @@ when adding one.
   Existing rows are backfilled from `updated_at` only when preparation had
   begun: phase 1 or 2 with an OOR session.
 
-- `000021_round_admission_deadlines` — records accepted attempt expiry and
-  closure separately from signature checkpoints. Deadline constraints only
-  shorten the saved budget. Startup closes interrupted admissions without
-  changing checkpoints or releasing reservations; the existing VTXO recovery
-  boundary remains authoritative. `CommitState` closes admission atomically
-  with its signature-bearing checkpoint.
-
 ## Deep Docs
 
 - [ARCHITECTURE.md](../ARCHITECTURE.md) — System-wide package map.
diff --git a/mailbox/rpc/AGENTS.md b/mailbox/rpc/AGENTS.md
index 26787ed6..a790cf23 100644
--- a/mailbox/rpc/AGENTS.md
+++ b/mailbox/rpc/AGENTS.md
@@ -65,6 +65,19 @@ and server-side routing need without including any transport implementation.
   `Retry`/`RetryWithKey` (or thread an explicit `RPCOptions.IdempotencyKey`);
   leaving the field empty makes the transport mint a fresh key per attempt,
   which defeats operator-side deduplication.
+- `RPCOptions.CorrelationID` and `RPCOptions.IdempotencyKey` are separate
+  identities and must not be aliased. Correlation matches one response to one
+  transport attempt; idempotency spans every attempt of the logical operation.
+  A transport that defaulted the correlation ID to the key would give the
+  server response a repeated mailbox message ID, so an acknowledged earlier
+  attempt could tombstone the retry's answer. `serverconn.UnaryFacade` defaults
+  an empty correlation ID to the envelope's fresh `MsgId` for that reason.
+  (The `CorrelationID` field comment in `options.go` still describes the older
+  key-as-correlation-ID convention and no longer matches the transport.)
+- `RetryWithKey`'s key must not already be in flight elsewhere: operator
+  deduplication assumes one active attempt per logical operation, so concurrent
+  requests under one key can observe an in-doubt execution rather than its
+  eventual result. Nothing in the package enforces that serialization.
 - A `KIND_RESPONSE` envelope carrying `HeaderGRPCStatusB64` signals a failed
   RPC; receivers must decode it via `DecodeErrorHeaders` before attempting to
   unmarshal the body.
diff --git a/mailbox/rpc/CLAUDE.md b/mailbox/rpc/CLAUDE.md
index 26787ed6..a790cf23 100644
--- a/mailbox/rpc/CLAUDE.md
+++ b/mailbox/rpc/CLAUDE.md
@@ -65,6 +65,19 @@ and server-side routing need without including any transport implementation.
   `Retry`/`RetryWithKey` (or thread an explicit `RPCOptions.IdempotencyKey`);
   leaving the field empty makes the transport mint a fresh key per attempt,
   which defeats operator-side deduplication.
+- `RPCOptions.CorrelationID` and `RPCOptions.IdempotencyKey` are separate
+  identities and must not be aliased. Correlation matches one response to one
+  transport attempt; idempotency spans every attempt of the logical operation.
+  A transport that defaulted the correlation ID to the key would give the
+  server response a repeated mailbox message ID, so an acknowledged earlier
+  attempt could tombstone the retry's answer. `serverconn.UnaryFacade` defaults
+  an empty correlation ID to the envelope's fresh `MsgId` for that reason.
+  (The `CorrelationID` field comment in `options.go` still describes the older
+  key-as-correlation-ID convention and no longer matches the transport.)
+- `RetryWithKey`'s key must not already be in flight elsewhere: operator
+  deduplication assumes one active attempt per logical operation, so concurrent
+  requests under one key can observe an in-doubt execution rather than its
+  eventual result. Nothing in the package enforces that serialization.
 - A `KIND_RESPONSE` envelope carrying `HeaderGRPCStatusB64` signals a failed
   RPC; receivers must decode it via `DecodeErrorHeaders` before attempting to
   unmarshal the body.
diff --git a/serverconn/AGENTS.md b/serverconn/AGENTS.md
index 850369ea..a65ddccd 100644
--- a/serverconn/AGENTS.md
+++ b/serverconn/AGENTS.md
@@ -142,6 +142,13 @@ background ingress polling with event routing.
   the logical request (see `mailboxrpc.Retry`). `SendRPC` mints a fresh key
   only when the caller leaves `RPCOptions.IdempotencyKey` empty, which is
   correct for a single-shot call and defeats deduplication for a retry.
+- Correlation identifies one transport attempt; the idempotency key identifies
+  the logical operation across attempts. `SendRPC` defaults an empty
+  `RPCOptions.CorrelationID` to the freshly minted **`MsgId`**, never to the
+  idempotency key. Deriving it from the key would also reuse the server
+  response's mailbox message ID, so once an earlier attempt's response had been
+  acknowledged the mailbox tombstone would suppress the cached response and the
+  retry's waiter would block until its deadline.
 - Ingress loop checkpoints pull cursor and ack state; on restart, resumes from checkpoint.
 - **A mailbox outage warns once per episode, not once per retry.** `pullPhase`
   carries a dedicated `pullFailCount` alongside the shared backoff `failCount`:
diff --git a/serverconn/CLAUDE.md b/serverconn/CLAUDE.md
index 850369ea..a65ddccd 100644
--- a/serverconn/CLAUDE.md
+++ b/serverconn/CLAUDE.md
@@ -142,6 +142,13 @@ background ingress polling with event routing.
   the logical request (see `mailboxrpc.Retry`). `SendRPC` mints a fresh key
   only when the caller leaves `RPCOptions.IdempotencyKey` empty, which is
   correct for a single-shot call and defeats deduplication for a retry.
+- Correlation identifies one transport attempt; the idempotency key identifies
+  the logical operation across attempts. `SendRPC` defaults an empty
+  `RPCOptions.CorrelationID` to the freshly minted **`MsgId`**, never to the
+  idempotency key. Deriving it from the key would also reuse the server
+  response's mailbox message ID, so once an earlier attempt's response had been
+  acknowledged the mailbox tombstone would suppress the cached response and the
+  retry's waiter would block until its deadline.
 - Ingress loop checkpoints pull cursor and ack state; on restart, resumes from checkpoint.
 - **A mailbox outage warns once per episode, not once per retry.** `pullPhase`
   carries a dedicated `pullFailCount` alongside the shared backoff `failCount`:

How to apply: save the block above to a file and git apply it, or run the doc-gardening skill locally over db db/sqlc mailbox/rpc serverconn. The CLAUDE.md/AGENTS.md pairs stay byte-identical, so make doc-check passes either way.

This is advisory only — nothing here blocks merge.


https://github.com/lightninglabs/wavelength/actions

@darioAnongba darioAnongba left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Strongest part of the stack for me: illegal persisted combinations are unrepresentable, the CAS is single-statement and race-tested, commit/abort races resolve to the OOR actor's gate, post-PONR failure parks instead of inventing an abort. Tests pass.

Two things I think belong in this PR because they define the durable model: Backing.Validate accepts any non-empty witness, and the peer can assert facts (including the single-bit RecoveryReady) that only local evidence should set. Plus no in-process retry after the CAS. Inline.

Three stack-level design points, parked here since this is the FSM:

Expiry. recovery.go stores BatchExpiry but nothing acts on it: no expiry-driven close, no renewal, and recovery-only sources are excluded from auto-refresh. If the source batch expires under a live channel the sweep kills the backing and the balance becomes a claim on the hub. So a channel is currently shorter-lived than a refreshed VTXO and close+reopen is the only lifecycle. Even a minimal ladder (warn, coop close, force close as expiry nears, hub-driven if the client is gone) would do for now; long-expiry funding batches or in-place renewal later.

Backing fee. Fixed at prepare time, single output, no anchor. Bumping the materialization spend relies entirely on CPFP via the commitment anchors, which don't exist yet (see the legacy-commitment comment on #1191), and even with anchors a fee spike inside the 432-block window favors the funder, who can just wait. A floor on the reserve, or at least state the CPFP dependency in the terms.

Event origin. We fence who may execute (commit/abort are funder-only) but not who may assert. An origin x event matrix at the Service boundary would stop later handlers from forgetting it. Specifics inline.

Smaller: PendingAction for backing_ready has an unreachable CommitOOR branch (make it explicit or return ActivateChannel); applyPrePONRExpiry errors on an empty reason (the reaper must never send one); proto max_fee_sat is uint64 while other amounts are int64, artifacts have no version field, CooperativeCloseProposal has no channel_id; ListNonTerminal keeps closed-with-artifact rows forever so the startup scan only grows; the bridge controllers poll at 50/100ms with no backoff and execution is re-entrant on the caller's ctx; dead close_fee_rate_sat_per_kw column and positional $20/$52 in InsertArkChannel; FSM phase constants duplicated as SQL literals in migration 21 and ListNonTerminal.

Long version: https://ark-channels.lightning.wiki/

Comment thread arkchannel/types.go Resolved
Comment thread rpc/arkchannelrpc/ark_channel.proto Resolved
Comment thread arkchannel/state.go Resolved
Comment thread arkchannel/state.go Resolved
Comment thread arkchannel/state.go Resolved
Comment thread arkchannel/state.go Resolved
Comment thread serverconn/ingress.go Resolved
Comment thread arkchannel/payment_bridge.go Resolved
Comment thread arkchannel/cooperative_close.go Resolved
@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lifecycle branch from ebd9381 to f32ead8 Compare September 8, 2026 19:28
@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lifecycle branch from f32ead8 to 2a4838f Compare September 8, 2026 20:49
@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lifecycle branch 2 times, most recently from 81bdc50 to a4bf321 Compare September 14, 2026 15:31
@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lifecycle branch from a4bf321 to 59aa2de Compare September 15, 2026 17:07
@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lifecycle branch 2 times, most recently from 51d14a5 to 54d0ba8 Compare September 15, 2026 19:42
@litbot-9000

Copy link
Copy Markdown
Collaborator

@litbot-9000: review reminder
@sputn1ck, remember to re-request review from reviewers when ready

@litbot-9000

Copy link
Copy Markdown
Collaborator

@bhandras: review reminder
@Roasbeef: review reminder
@litbot-9000: review reminder
@sputn1ck, remember to re-request review from reviewers when ready

3 similar comments
@litbot-9000

Copy link
Copy Markdown
Collaborator

@bhandras: review reminder
@Roasbeef: review reminder
@litbot-9000: review reminder
@sputn1ck, remember to re-request review from reviewers when ready

@litbot-9000

Copy link
Copy Markdown
Collaborator

@bhandras: review reminder
@Roasbeef: review reminder
@litbot-9000: review reminder
@sputn1ck, remember to re-request review from reviewers when ready

@litbot-9000

Copy link
Copy Markdown
Collaborator

@bhandras: review reminder
@Roasbeef: review reminder
@litbot-9000: review reminder
@sputn1ck, remember to re-request review from reviewers when ready

@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lifecycle branch 3 times, most recently from e2c20c4 to caeba2d Compare November 9, 2026 21:00
@litbot-9000

Copy link
Copy Markdown
Collaborator

@bhandras: review reminder
@litbot-9000: review reminder
@sputn1ck, remember to re-request review from reviewers when ready

@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lifecycle branch from caeba2d to aaafc65 Compare November 16, 2026 15:15
@sputn1ck

Copy link
Copy Markdown
Member Author

Checked the current commit story against this request. The lifecycle layer has 24 dependency-ordered commits rather than the superseded 13k-line handwritten commit. After restacking today, range-diff reports all 24 patches unchanged. The new review fixes live as separate behavior-sized commits in the OOR foundation and daemon layers; this update does not fold in the older uncommitted runtime refactor.

@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lifecycle branch 2 times, most recently from 76c3ca1 to 54db17a Compare November 17, 2026 21:46
@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lifecycle branch 2 times, most recently from 1b5e37f to 5e89112 Compare November 18, 2026 18:14
@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lifecycle branch from 5e89112 to 311acdb Compare November 19, 2026 16:04
@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lifecycle branch from 311acdb to 5c6e05c Compare November 19, 2026 16:25
@litbot-9000

litbot-9000 commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Doc advisory: this PR changes the documented packages db and db/sqlc. db/sqlc/CLAUDE.md is already current. db/CLAUDE.md (and its AGENTS.md mirror) is missing the new ArkChannelStoreDB peer scoping and funding-authorization APIs.

diff --git a/db/AGENTS.md b/db/AGENTS.md
index e7300a64..1bb048fa 100644
--- a/db/AGENTS.md
+++ b/db/AGENTS.md
@@ -79,12 +79,27 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/db.<Symb
   transaction and channel point, per-party finalization and recovery flags,
   and the cooperative-close request and result. Methods: `Create` (insert at
   revision one, `ON CONFLICT (channel_id) DO NOTHING`), `Get`,
-  `GetByPendingChannelID`, `GetByChannelPoint`, `ListNonTerminal`, and
-  `CompareAndSwap`. `Create` and `CompareAndSwap` run each snapshot through
-  `arkchannel.RestoreState`, so the store cannot write a row that the domain
-  FSM would refuse to restore. `arkchannel.ErrNotFound` and
-  `arkchannel.ErrConflict` report typed misses; a write that affects no rows
-  is a conflict, not a silent success.
+  `GetByPendingChannelID`, `GetBySCID`, `GetByChannelPoint`,
+  `ListNonTerminal`, `RecoveryPeers`, `BindFundingTxID`,
+  `RecordFundingSignature`, and `CompareAndSwap`. `Create` and
+  `CompareAndSwap` run each snapshot through `arkchannel.RestoreState`, so
+  the store cannot write a row that the domain FSM would refuse to restore.
+  `arkchannel.ErrNotFound` and `arkchannel.ErrConflict` report typed misses;
+  a write that affects no rows is a conflict, not a silent success.
+- `ArkChannelStoreDB.ForPeer(peer)` — returns a view scoped to one
+  authenticated client node key that borrows the shared executor. Reads of a
+  foreign channel return `arkchannel.ErrNotFound`, exactly like an absent
+  one, whichever unique key was used. Writes for a foreign snapshot or terms
+  are refused the same way. `ListNonTerminal` and `RecoveryPeers` return only
+  that peer's channels. The unscoped store lists every owner with native,
+  unroll or refresh-defense work.
+- `BindFundingTxID` / `RecordFundingSignature` — two revisioned claims on the
+  canonical backing transaction, each bumping `revision`. The first records
+  `authorized_backing_txid` once, in phase 2, at the revision whose terms and
+  source authorized signing. The second commits the single 64-byte
+  `funding_signature` for that exact txid before the caller may release it,
+  so a concurrent cancellation that advances the revision turns the write
+  into `arkchannel.ErrConflict`.
 - `LedgerStoreDB` — implements `ledger.LedgerStore`. Wraps
   `sqlc.InsertClientLedgerEntry` (ON CONFLICT DO NOTHING followed by an exact
   winner-payload comparison, so contradictory key reuse fails). Joins the
@@ -327,7 +342,13 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/db.<Symb
   and is incremented by the update. A zero-row update means that the caller's
   expected revision is stale, so the store returns
   `arkchannel.ErrConflict`. Immutable terms are absent from the update and
-  cannot be rewritten by a stale writer.
+  cannot be rewritten by a stale writer. Every update also matches
+  `client_node_key` against the owner key, so a transition can change only
+  the authenticated peer's channel.
+- `authorized_backing_txid` and `funding_signature` are write-once. Check
+  constraints require an OOR source for an authorized txid, require it to equal
+  the channel point txid once one is recorded, and allow a signature only
+  alongside an authorized txid.
 - `pre_ponr_started_at` uses
   `COALESCE(pre_ponr_started_at, <arg>)`. The first checkpoint after OOR
   preparation begins stamps it, while later state changes preserve it. This
@@ -517,9 +538,11 @@ when adding one.
   missing net exit-send row from the surviving refresh-send and exit-fee rows,
   repairing the overstated VTXO balance atomically with the key rewrite.
 - `000032_ark_channels` — creates the channel record and its uniqueness and
-  recovery indexes. It stores signed Ark backing, each peer's recovery
-  readiness, observed source spends, preparation start time, and cooperative
-  settlement. Lightning commitments, HTLCs and payment attempts stay in lnd.
+  recovery indexes. It stores signed Ark backing, the authorized backing txid
+  and its funding signature, each peer's recovery readiness, observed source
+  spends, preparation start time, and cooperative settlement.
+  `idx_ark_channels_client_created` serves per-peer listing. Lightning
+  commitments, HTLCs and payment attempts stay in lnd.
 
 - `000021_round_admission_deadlines` — records accepted attempt expiry and
   closure separately from signature checkpoints. Deadline constraints only
diff --git a/db/CLAUDE.md b/db/CLAUDE.md
index e7300a64..1bb048fa 100644
--- a/db/CLAUDE.md
+++ b/db/CLAUDE.md
@@ -79,12 +79,27 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/db.<Symb
   transaction and channel point, per-party finalization and recovery flags,
   and the cooperative-close request and result. Methods: `Create` (insert at
   revision one, `ON CONFLICT (channel_id) DO NOTHING`), `Get`,
-  `GetByPendingChannelID`, `GetByChannelPoint`, `ListNonTerminal`, and
-  `CompareAndSwap`. `Create` and `CompareAndSwap` run each snapshot through
-  `arkchannel.RestoreState`, so the store cannot write a row that the domain
-  FSM would refuse to restore. `arkchannel.ErrNotFound` and
-  `arkchannel.ErrConflict` report typed misses; a write that affects no rows
-  is a conflict, not a silent success.
+  `GetByPendingChannelID`, `GetBySCID`, `GetByChannelPoint`,
+  `ListNonTerminal`, `RecoveryPeers`, `BindFundingTxID`,
+  `RecordFundingSignature`, and `CompareAndSwap`. `Create` and
+  `CompareAndSwap` run each snapshot through `arkchannel.RestoreState`, so
+  the store cannot write a row that the domain FSM would refuse to restore.
+  `arkchannel.ErrNotFound` and `arkchannel.ErrConflict` report typed misses;
+  a write that affects no rows is a conflict, not a silent success.
+- `ArkChannelStoreDB.ForPeer(peer)` — returns a view scoped to one
+  authenticated client node key that borrows the shared executor. Reads of a
+  foreign channel return `arkchannel.ErrNotFound`, exactly like an absent
+  one, whichever unique key was used. Writes for a foreign snapshot or terms
+  are refused the same way. `ListNonTerminal` and `RecoveryPeers` return only
+  that peer's channels. The unscoped store lists every owner with native,
+  unroll or refresh-defense work.
+- `BindFundingTxID` / `RecordFundingSignature` — two revisioned claims on the
+  canonical backing transaction, each bumping `revision`. The first records
+  `authorized_backing_txid` once, in phase 2, at the revision whose terms and
+  source authorized signing. The second commits the single 64-byte
+  `funding_signature` for that exact txid before the caller may release it,
+  so a concurrent cancellation that advances the revision turns the write
+  into `arkchannel.ErrConflict`.
 - `LedgerStoreDB` — implements `ledger.LedgerStore`. Wraps
   `sqlc.InsertClientLedgerEntry` (ON CONFLICT DO NOTHING followed by an exact
   winner-payload comparison, so contradictory key reuse fails). Joins the
@@ -327,7 +342,13 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/db.<Symb
   and is incremented by the update. A zero-row update means that the caller's
   expected revision is stale, so the store returns
   `arkchannel.ErrConflict`. Immutable terms are absent from the update and
-  cannot be rewritten by a stale writer.
+  cannot be rewritten by a stale writer. Every update also matches
+  `client_node_key` against the owner key, so a transition can change only
+  the authenticated peer's channel.
+- `authorized_backing_txid` and `funding_signature` are write-once. Check
+  constraints require an OOR source for an authorized txid, require it to equal
+  the channel point txid once one is recorded, and allow a signature only
+  alongside an authorized txid.
 - `pre_ponr_started_at` uses
   `COALESCE(pre_ponr_started_at, <arg>)`. The first checkpoint after OOR
   preparation begins stamps it, while later state changes preserve it. This
@@ -517,9 +538,11 @@ when adding one.
   missing net exit-send row from the surviving refresh-send and exit-fee rows,
   repairing the overstated VTXO balance atomically with the key rewrite.
 - `000032_ark_channels` — creates the channel record and its uniqueness and
-  recovery indexes. It stores signed Ark backing, each peer's recovery
-  readiness, observed source spends, preparation start time, and cooperative
-  settlement. Lightning commitments, HTLCs and payment attempts stay in lnd.
+  recovery indexes. It stores signed Ark backing, the authorized backing txid
+  and its funding signature, each peer's recovery readiness, observed source
+  spends, preparation start time, and cooperative settlement.
+  `idx_ark_channels_client_created` serves per-peer listing. Lightning
+  commitments, HTLCs and payment attempts stay in lnd.
 
 - `000021_round_admission_deadlines` — records accepted attempt expiry and
   closure separately from signature checkpoints. Deadline constraints only

How to apply: save the diff above and git apply it, or run the nightly /doc-gardening db skill locally.

Workflow run link unavailable: this advisory run could not read the run metadata.

Keep the first channel migration and the authenticated peer protocol
limited to the states used by active-channel settlement.
Generate the local and peer transports separately so the mailbox
accepts only the authenticated peer service.
Pin the source, signing parties and replacement allocation before
allowing either peer to advance a funding or close operation.
Gate activation, closure and expiry on durable evidence. Resume the
next action from that evidence after a process restart.
Bind each payment attempt to its circuit and persist the preimage
before allowing a retry or fallback.
Store revision-checked snapshots and recovery artifacts together so
restart never combines two owners or two versions of a channel.
Reconcile funding reservations with durable OOR ownership and hand
confirmed source conflicts to the recovery controller.
@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lifecycle branch from 3aa3937 to 7d2b7d5 Compare November 24, 2026 17:11
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.

5 participants