Repository navigation
Conversation
There was a problem hiding this comment.
Pull request overview
This PR adds infrastructure for Ark-backed Lightning channel flows by introducing application-owned “recovery-only” VTXOs, a two-phase (prepare/commit) OOR transfer mode, and non-standard unroll policy handling (including recognizing a peer-published pre-signed final spend as successful completion). It also adds DB and codec support so these new states and artifacts survive restarts and actor reaping.
Changes:
- Add
VTXOStatusRecoveryOnlyplus store/manager logic to keep application-owned outputs out of wallet balance/selection/actors, while still allowing deterministic recovery and spend completion. - Extend unroll to support policy-kind dispatch and “pre-signed final spend” policies, treating the exact expected transaction as success even if published by the peer.
- Add prepared OOR sessions (prepare → commit/abort), persist richer outgoing snapshots (recipients + pre-PONR failure marker), and allow registry state reads after terminal children are reaped.
Reviewed changes
Copilot reviewed 34 out of 36 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| vtxo/manager.go | Allows actorless completion for recovery-only spends and confirms recovery-only exits gated by non-standard policy kind. |
| vtxo/manager_admission_test.go | Adds tests for actorless recovery-only completion and missing-actor rejection for normal VTXOs. |
| vtxo/interfaces.go | Introduces VTXOStatusRecoveryOnly and string form. |
| vtxo/filter.go | Excludes recovery-only from pending-balance accounting. |
| vtxo/filter_test.go | Verifies pending-balance exclusion for recovery-only descriptors. |
| unroll/policy_resolvers.go | Adds a composite resolver that dispatches exit spend policy by kind. |
| unroll/interfaces.go | Adds PreSignedExitSpendPolicy interface for immutable final spends. |
| unroll/actor.go | Recognizes the exact pre-signed final spend as a successful completion path. |
| unroll/actor_test.go | Adds harness seam + test verifying peer-published pre-signed spend completes the actor. |
| oor/transitions.go | Adds Prepared state handling, commit/abort events, and PrePONR tracking for failures. |
| oor/states.go | Introduces Prepared state and extends Failed with PrePONR. |
| oor/session.go | Adds APIs for prepared sessions and plumbs PrepareOnly through session creation. |
| oor/session_test.go | Tests prepared commit behavior and abort releasing inputs (pre-PONR). |
| oor/session_actor_handlers.go | Forwards PrepareOnly into session creation from actor handler. |
| oor/resume.go | Ensures Prepared state has no implied outbox side effects on resume. |
| oor/registry.go | Allows GetState to read persisted snapshots when a terminal child has been reaped. |
| oor/registry_test.go | Tests GetState reads persisted snapshot without spawning a child. |
| oor/outgoing_snapshot.go | Adds Prepared snapshot phase, recipient metadata persistence, and pre-PONR failure marker; adds recipient extraction helper. |
| oor/outgoing_snapshot_codec.go | Adds TLV records for recipient metadata + pre-PONR failure flag; decodes them with limits. |
| oor/outgoing_snapshot_codec_test.go | Extends TLV round-trip test coverage for new snapshot fields. |
| oor/events.go | Adds prepare-only start flag and commit/abort prepared events. |
| oor/actor_messages.go | Adds PrepareOnly to start-transfer request encode/decode. |
| oor/actor_durable_message.go | Adds durable mailbox encoding for prepare-only + prepared commit/abort events; refactors incoming transfer decode helper. |
| oor/actor_durable_message_test.go | Adds tests for prepare-only payload round-trip and prepared commit/abort durable round-trip. |
| lib/arkscript/channel_vtxo.go | Adds compiled policy construction/validation helpers for Ark-backed channel VTXO scripts. |
| lib/arkscript/channel_vtxo_test.go | Tests channel policy paths, reaction-window enforcement, and template validation. |
| db/vtxo_store.go | Adds SaveRecoveryOnlyVTXO and SetRecoveryOnlyVTXORelativeExpiry plus descriptor replay validation. |
| db/vtxo_store_test.go | Tests recovery-only descriptors are excluded from wallet sets and validates replay rules. |
| db/sqlc/vtxo.sql.go | Adds generated SQL for setting recovery-only relative expiry. |
| db/sqlc/schemas/generated_schema.sql | Documents new numeric status mapping for Expired/RecoveryOnly. |
| db/sqlc/queries/vtxo.sql | Adds SetRecoveryOnlyVTXORelativeExpiry query. |
| db/sqlc/querier.go | Exposes new query in the sqlc querier interface. |
| db/sqlc/migrations/000004_vtxos.up.sql | Documents new numeric status mapping for Expired/RecoveryOnly. |
| db/round_store.go | Plumbs the new query into the RoundStore interface. |
| db/oor_unroll_resolver.go | Adds session-id-based package resolution path and shares traversal logic. |
| db/oor_unroll_resolver_test.go | Tests resolving unroll packages by session ID before an outpoint binding exists. |
Files not reviewed (2)
- db/sqlc/querier.go: Generated file
- db/sqlc/vtxo.sql.go: Generated file
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 20dcd1c701
ℹ️ 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".
|
/gateway review |
There was a problem hiding this comment.
Gateway review — 5 findings
🔴 0 Blocker · 🟠 3 Major · 🟡 2 Minor · 🔵 0 Nit
Summary
This is layer 1 of the Ark channels stack: a RecoveryOnly VTXO status that keeps application-owned outputs out of wallet balance/selection/actors, a prepare/commit two-phase OOR mode so a channel coordinator can use a deterministic outpoint before any signature is released, and unroll support for recognizing a peer-published pre-signed final spend as success. The layering is clean and the new states are threaded through the snapshot codec, the registry, and the DB consistently.
Three things need attention before merge. The prepare-only mode creates a durable session that carries an idempotency key but no dispatch-attempt row, and validateOutgoingDispatchIdentity treats exactly that shape as a keyless admission — so a keyed prepared transfer becomes unretriable after a restart. SaveRecoveryOnlyVTXO's replay validation treats expiry as immutable while SetRecoveryOnlyVTXORelativeExpiry, ten lines above it, exists to mutate that column. And ValidateChannelVTXOTemplate compares an untrusted template only by its set of compiled leaf scripts, never by the output script that template actually derives.
The new channel-policy delay arithmetic (validate) is carefully bounded and well tested; the recovery-only exclusion from ListLiveVTXOs / ListRecoverableVTXOs / selection candidates is covered end to end.
Bot commands
/gateway re-review— re-run after pushing changes (maintainers)/gateway dismiss <id>— silence a finding (maintainers)/gateway explain <id>— elaborate on a finding (anyone)
|
🤖 gateway audit metadata for this PR — auto-generated, please don't edit. |
|
@bhandras: review reminder |
There was a problem hiding this comment.
Prepare/commit boundary is clean and abort-safe, and recovery-only never leaks into balance, selection, refresh or admission (checked all of them). Tests pass at this head. Two things I'd fix in this layer before the rest builds on it: the keyed Prepared lookup doesn't survive a restart, and ExitPolicyKind.Valid() never learned the channel kind, so the retirement path is dead at the tip. Inline.
Not anchorable (code this PR doesn't touch), oor/registry.go validateOutgoingDispatchIdentity / handleLookupTransfer, blocking: a keyed Prepared session has no dispatch-attempt row, pendingOutgoingKeys is same-boot only, and identity validation never compares record.IdempotencyKey. After a restart the lookup says "absent", we re-prepare, the wallet can't re-pick the still-reserved inputs, and the new commit collides with the unique key index. Open loops, inputs stranded until a manual abort. Compare the key in validateOutgoingDispatchIdentity and return the existing session, and fall back to a registry-row-by-key lookup in handleLookupTransfer. (Bots flagged this too; the restart consequence is the part I'd stress.)
Two design notes. Prepared has no TTL at the OOR layer, so if the coordinator record never gets created the reservations leak until someone aborts by session ID; AdmissionDeadlineUnixNanos is already plumbed, an auto-abort past it would make this self-healing. And ExitPolicyKind being two string types joined by a cast is what let the Valid() gap happen silently; a shared constant set with an exhaustiveness test would turn it into a test failure.
Long version: https://ark-channels.lightning.wiki/
20dcd1c to
a3dcce4
Compare
5a46e2c to
beb5137
Compare
|
The Go changes on this branch left the per-package docs for Proposed
|
7d18ae7 to
9b96e03
Compare
|
@sputn1ck, remember to re-request review from reviewers when ready |
5 similar comments
| // ChannelVTXOParams defines the key roles and relative delays of a VTXO that | ||
| // backs an unpublished Lightning channel point. | ||
| type ChannelVTXOParams struct { | ||
| ClientArkKey *btcec.PublicKey |
There was a problem hiding this comment.
Pls add godocs to these exported members, also generally everywhere.
There was a problem hiding this comment.
Added GoDocs for every exported member of ChannelVTXOParams and ChannelVTXOPolicy in 1d90beec, including signer roles and the immediate 3-of-3 in-Ark spend versus delayed 2-of-2 channel-funding and later funder-refund paths.
| NextState: failedState(reason, state), | ||
| NewEvents: fn.Some(EmittedEvent{ | ||
| Outbox: []OutboxEvent{ | ||
| &ReleaseInputsRequest{ |
There was a problem hiding this comment.
Can we pass ReserveEpochs here, and add Prepared to prePONRReserveEpochs?
The release runs before the OOR state commit. If the release goes through but the commit fails, the saved state stays in Prepared and the abort replays. If another transfer reserves the same coin in between, the replayed release has no epoch, so the manager releases unconditionally and drops the newer transfer's reservation. The coin goes back into selection while that transfer is still spending it.
Passing the original epoch makes the existing epoch guard catch this.
Can we also add a test for: abort → release ok → commit fails → coin re-reserved → abort replays?
There was a problem hiding this comment.
Still a blocker after re-review. The abort still omits ReserveEpochs, and prePONRReserveEpochs still skips Prepared.
For example:
- Transfer A holds coin X at epoch 41.
- A aborts. Releasing X succeeds, but committing the OOR snapshot fails. The saved state is still
Prepared. - Transfer B reserves X at epoch 42.
- A's abort replays without an epoch. The manager treats zero as an unconditional release and drops B's reservation.
X can now be selected again while B is spending it. The existing stale-release guard would reject epoch 41 against epoch 42, but this path never supplies it.
Pls pass prePONRReserveEpochs(state) here, add Prepared to the helper, and cover that exact replay sequence. The channel input builder also needs to carry the selected reservation epochs into TransferInput; otherwise the release still gets zero. My local regression probe still fails on the latest head. I haven't demonstrated fund loss.
There was a problem hiding this comment.
Fixed in bb2fe05f and daemon-layer commit 1ab931ba. Prepared abort/failure now forwards the original reservation epochs, and channel funding copies the wallet-selected epochs into its durable inputs. The regression uses the real wallet, reservation manager and SQL-backed VTXO store: release succeeds, snapshot commit fails, a new owner reserves the coin, then replay must preserve that newer reservation. The matching new epoch can still release it. Both abort and fail variants pass 20 repetitions with -race; the reordered two-input channel snapshot test also passes 20 repetitions.
| return fn.Err[ActorResp](err) | ||
| } | ||
| if child == nil { | ||
| if _, ok := msg.(*GetStateRequest); ok { |
There was a problem hiding this comment.
Can we reload the committed state before answering GetStateRequest when commitFailed is set? The early return is in oor/session_actor.go:391, outside this diff.
If an abort advances the in-memory FSM to Failed{PrePONR: true} but the commit fails, the saved state stays in Prepared. That early return still reports Failed.
The channel bridge re-reads state after a drive error and treats Failed.PrePONR as proof that the OOR aborted, allowing LND funding cleanup. So we can cancel the channel while the durable OOR is still prepared.
The reload in Receive already handles this for driving events. Can we move the state query after it, and add a test for: abort → commit fails → query before retry → must report Prepared?
There was a problem hiding this comment.
Still a blocker after re-review. The new persisted-state fallback handles a reaped child, but this failure is in a resident child: oor/session_actor.go:391 still answers GetStateRequest before the commitFailed reload.
For example:
- The saved state is
Prepared. - Abort advances the in-memory FSM to
Failed{PrePONR: true}. - The snapshot commit fails, so the saved state remains
Prepared. - A status query arrives before another driving event. It returns the uncommitted
Failedstate.
The channel bridge re-reads status after a drive error and treats that result as proof of abort. That allows funding cleanup while the durable OOR is still prepared.
Pls run the existing reload before answering the query, and add the abort → failed commit → immediate query test. My local test still gets Failed where it must get Prepared. A later driving event repairs the in-memory state, but that is too late for this query.
There was a problem hiding this comment.
Fixed in 5f28d4ff. GetStateRequest now passes through the existing committed-state reload when commitFailed is set. Added TestPreparedAbortQueryReloadsCommittedState: abort advances in memory, persistence fails, an immediate query returns the durable Prepared state without replaying release side effects. It failed before the fix and passes afterward with -race.
| // txid and record both its broadcast and confirmation so the durable | ||
| // actor converges regardless of which participant reached the chain | ||
| // first. | ||
| matched, err := b.ackPreSignedExitSpend(ctx, ax, msg) |
There was a problem hiding this comment.
This breaks external spend handling for asset VTXOs.
Case 4 now runs before the old Case 5 fail path. ackPreSignedExitSpend calls resolveExitSpendPolicy, which returns ErrAssetVTXORequiresTransition for any asset VTXO. We return that error, so the FailEvent is never reached. The actor errors on every redelivery instead of reaching PhaseFailed, and the VTXO manager never gets its exit outcome.
I have a test that fails here and passes with main's actor: asset VTXO, external spend of the target, expect PhaseFailed.
Can we return false, nil early when b.exitPolicyKind() == StandardVTXOTimeoutExitPolicyKind? Only non-standard kinds can be pre-signed. Pls also add the test.
There was a problem hiding this comment.
Still reproducible on the latest head.
Example: an asset VTXO has an active unroll, then another transaction spends its target. This new check calls resolveExitSpendPolicy, which returns ErrAssetVTXORequiresTransition. We return the error before reaching the existing external-spend FailEvent path. Redelivery repeats the same error instead of reaching PhaseFailed.
Pls return false, nil from ackPreSignedExitSpend for StandardVTXOTimeoutExitPolicyKind, before resolving the policy. Standard timeout exits have no pre-signed final spend to match.
The regression test is: start an asset unroll → report a foreign spend of its target → expect PhaseFailed. It still fails here and passes with main's actor. The earlier small guard also makes it pass. The demonstrated regression is the missing terminal failure; I haven't demonstrated fund loss.
There was a problem hiding this comment.
Fixed in b60f2be3. Standard timeout exits return (false, nil) before resolving a pre-signed final-spend policy. The real actor/registry regression covers both materializing and deferred asset exits, terminal persistence and recoverable manager feedback. Full unroll race coverage and the existing pre-signed channel completion regression pass.
| clientdb.OORSessionDirectionOutgoing && | ||
| record.Status == clientdb.OORSessionStatusFailed: | ||
| record.Status == clientdb.OORSessionStatusFailed && | ||
| (record.IdempotencyKey == "" || record.IdempotencyKey == key): |
There was a problem hiding this comment.
This changes behavior: a failed outgoing row can no longer be rebuilt under a different key. On main any failed row with the same session ID was replaceable. Now a new key gets ErrIdempotencyKeyConflict.
I think that's intended (it matches the oor/CLAUDE.md update), but can you confirm? There's no test for it. Can we add one: failed row with key A, retry with key B → conflict; retry with key A → rebuilds.
There was a problem hiding this comment.
Confirmed: this identity constraint is intentional. Added TestOORRegistryFailedSessionRetainsKey in 30d11515: an attemptless failed outgoing row with key A rejects key B, while key A rebuilds the child. An already immutable dispatch attempt remains non-replaceable; the existing legacy/keyless exception is unchanged. No production behavior change was needed for this item.
| // in SQL queries are unchanged. | ||
| VTXOStatusExpired | ||
|
|
||
| // VTXOStatusRecoveryOnly identifies an application-owned output whose |
There was a problem hiding this comment.
Pls spell out that the owning FSM also owns the batch deadline. Excluding RecoveryOnly from refresh and actor recovery means nothing in the wallet will refresh or unroll it before BatchExpiry. If the owner doesn't act, the operator sweeps the batch and the materialize tx becomes worthless.
Something like: "The owning FSM must refresh or unroll the output before its BatchExpiry."
As far as I can tell nothing in the stack does this yet for idle channels. I'll raise the actual deadline handling on #1192.
There was a problem hiding this comment.
Documented the owning FSM's absolute batch-expiry responsibility in 1d90beec. Neither CSV delay extends that deadline. Automatic idle-channel source-expiry protection is implemented and daemon-tested in a separate, still-unpublished local follow-up; I am not claiming this documentation patch closes the functional gap in the current published #1192. That remains a separate open requirement.
| ) | ||
|
|
||
| const ( | ||
| // DefaultChannelReactionWindow gives either channel endpoint roughly |
There was a problem hiding this comment.
Can we say in the godoc what each delay protects?
ChannelDelay: operator's exit delay, so the operator can still claim with a forfeit / checkpoint before materialize matures.FunderDelay = ChannelDelay + ReactionWindow: gives the non-funder time to materialize before the funder can refund.- Neither protects against
BatchExpiry. Both only start counting once the channel VTXO is on chain.
Also where 432 comes from (3 days of blocks), and whether it should be configurable.
There was a problem hiding this comment.
Clarified in 1d90beec: ChannelDelay preserves the Ark operator's checkpoint/forfeit recovery opportunity; the additional reaction window gives the non-funder time to materialize before refund eligibility. Both CSV clocks start from channel-policy VTXO confirmation, independently of absolute batch expiry. The default is 432 blocks (3 x 144), not a wall-clock guarantee. ReactionWindow is already a caller parameter; zero selects the default. Added a regression using a larger custom window.
|
Final validation of the focused review fixes is complete. The affected foundation race suites, full tagged channel/runtime/daemon/database race suites, native lint with actor-block checks, server runtime units and CLI harness units pass. One complete five-case real-daemon channel E2E run passed in 933.680 seconds, using GOWORK=off with published client ae1273a and server b81ed602. This covers send/receive, fresh receive-channel creation, vHTLC fallback/promotion, 3-of-3 in-Ark refresh, confirmed sweep resolution and offline-client hub recovery. All five client branches and all five server branches have been restacked and pushed with explicit old-head leases. The seven inline threads have individual fix/test replies; they are left for reviewer re-review rather than self-resolved. The lifecycle layer retains its 24 behavior-ordered patches. Latest-trunk conflicts remain, and the older unpublished runtime/security and automatic source-expiry work is not included in this focused patch. No green CI or merge-readiness claim is made. |
3c01fad to
44ec18b
Compare
|
@sputn1ck, remember to re-request review from reviewers when ready |
Let an operator recognize and bind a channel policy to the exact output without importing the native channel runtime or pinning its lnd fork.
Keep retry identity stable without sharing transport correlations. Scope durable ingress evidence to each reply mailbox so separate connectors cannot acknowledge another delivery stream.
The invoice deadline bounds mailbox delivery, not acceptance of an event that has already arrived. Persist accepted events with the caller context so an exhausted polling grace window cannot expire a valid receive. Keep parent cancellation effective for validation and storage. Set the overdue receive regression poll window to zero to cover the cached event path deterministically.
Keep the legacy checkpoint request intact. An explicit payout request binds the owner and destination to both transactions and gets a distinct signature for each spend.
Expose the additional proof and signature fields without changing any legacy field numbers or service methods.
Preserve source owners when explicitly requested and carry their independent payout signatures through durable preparation and signing. Reconstruct the package before signing so the local signer attests to the intended output, not just a checkpoint.
A capable client library is not evidence that its peer accepts a new payout format. Select the legacy checkpoint for ordinary refunds and require both signatures when the peer capability is explicitly known. Never treat partial payout authorization as a completed refund.
44ec18b to
1b42430
Compare
Carry the independently reviewed wallet observations and pending swap worker changes below the first channel feature. This comparison base is for review and integration; land the standalone PRs against main.
Persist deterministic OOR packages before signatures or transport are released so channel negotiation can commit or abort safely.
Keep application-owned channel VTXOs out of wallet balances while retaining enough policy and expiry state to resume materialization.
A prepare-only transfer persists its caller key before any dispatch attempt exists. Resolve retries through that durable registry row so a restart cannot admit a duplicate transfer in the gap before commit.
Channel recovery chooses its final-spend delay after registering the source VTXO. Treat that expiry as mutable so replaying source preparation does not reject the already-owned output.
Classify the release boundary from the FSM state instead of populated input pointers, and reject non-canonical boolean encodings at the durable message boundary.
Name the current outgoing snapshot version and fail closed when durable state was written by a newer schema. Continue accepting all older additive versions.
Recognize Ark channel backing as a valid recovery-only policy and preserve legacy resolver behavior when it is wrapped in the composite dispatcher.
When the peer publishes the exact CSV-delayed materialization transaction first, derive the latest possible parent confirmation height. Recording the spend height itself would make valid observed history appear immature.
A failed abort commit leaves the in-memory FSM ahead of its durable gate. Reload before reads as well as driving events so a status probe cannot authorize channel cleanup from a rolled-back abort.
An attemptless failed session may rebuild under its original caller key, but a different key must conflict. Cover both branches so immutable operation identity cannot regress during failed-session recovery.
Standard timeout exits have no pre-signed final spend. Skip custom exit policy resolution before handling a foreign spend so asset sweep safety does not prevent terminal persistence and manager feedback.
Document signer roles and the distinct operator recovery and funder reaction delays. Both CSV clocks begin at VTXO confirmation; neither extends batch expiry. Exercise the configurable reaction window.
Retain the original selection epoch when aborting a prepared transfer. A release may succeed before snapshot persistence fails, so a replay must not release another operation that subsequently reserved the same coin. Exercise both abort and fail events through the real reservation manager.
1b42430 to
1eae23a
Compare
Prepare and validate channel-backed OOR funding before commit. Preserve source lineage, prepared identity and reservation ownership across restart. Keep the foreign-asset regression with the pre-signed unroll path that introduced it.
Do not merge #1189 until the independently reviewed behavioral prerequisites land on
mainand this feature branch is rebased onto thatmain. GitHub anchors this native stack's bottom PR tomain. Its Files changed view is cumulative while prerequisites are unmerged; a channel-only comparison is for review, not permission to merge the bundle. The corrected stack also depends on the independent wallet backend (#1642) and pending-swap retry (#1643).Review the channel-only funding comparison. Its exact base is the aggregate of six independently reviewable main PRs: parser #1637, mailbox #1638, ordinary receive deadlines #1639, ordinary refund compatibility #1640, light-wallet backend #1642 and ordinary pending-swap retry #1643. Do not merge the aggregate as a bundle. The comparison excludes all six; the native PR Files changed view does not.
No native channel runtime, personal lnd replacement, generic worker retry or light-wallet backend change is introduced by the channel-only comparison. Package-level OOR, unroll, VTXO and database checks and changed-source lint passed locally. #1190 builds on this layer.