Skip to content

lnruntime: Compose native Ark channel state machines - #1191

Open
sputn1ck wants to merge 10 commits into
kon/ark-channel-lifecyclefrom
kon/ark-channel-lnd-runtime
Open

sputn1ck wants to merge 10 commits into
kon/ark-channel-lifecyclefrom
kon/ark-channel-lnd-runtime

Conversation

@sputn1ck

@sputn1ck sputn1ck commented Aug 24, 2026 •

Copy link
Copy Markdown
Member

Integration only: do not merge on the personal lnd replacements. Land the required recovery and idle-worker behavior upstream. Select official versions of both github.com/lightningnetwork/lnd and github.com/lightningnetwork/lnd/kvdb, remove both personal replacements, and verify both resolved versions from an external main module with GOWORK=off and no replacements. Build native, mobile and WASM and run both default mixed-version directions and the enabled daemon suite on those official versions. A passing fork-pinned matrix is not release clearance.

Compose native lnd funding, links, invoices and chain resolution without starting a separate lnd daemon. Accept funding only for a registered promotion and validate the signed backing before link activation. Authenticated peers share the engine, not channel ownership or recovery evidence. On force close, materialize the backing before handing resolution to lnd.

Review boundary: #1190 is the GitHub stack base. The three-file dependency change is independently reviewable in #1641. The runtime-only comparison excludes those pins and their lint allow-list. #1192 adds daemon ownership.

The seven shared light-wallet files and generic pending-swap retry are independent main PRs #1642 and #1643. The runtime-only comparison changes no lwwallet or swapclientserver files. The actual native PR base remains #1190 and includes the separately reviewed three-file dependency change from #1641.

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

@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: 5e0f7c6a9f

ℹ️ 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 chainbackends/backend_notifier.go Resolved
Comment thread chainbackends/backend_notifier.go Resolved
Comment thread chainbackends/backend_notifier.go Resolved
Comment thread chainbackends/backend_notifier.go Resolved
Copilot stopped reviewing on behalf of sputn1ck due to an error August 24, 2026 14:58
@sputn1ck sputn1ck changed the title kon/ark channel lnd runtime lnruntime: Compose native Ark channel state machines Aug 24, 2026
@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lnd-runtime branch from eacb4d1 to 13aac6e Compare August 24, 2026 15:35
@litbot-9000

Copy link
Copy Markdown
Collaborator

@sputn1ck, remember to re-request review from reviewers when ready

@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.

Much more faithful than the usual embedded-lnd attempt: sweeper, nursery, breach arb, blockbeat, sphinx replay log, forwarding log, restart admission all real and in server.go order. Build/vet/tests pass; -race fails TestNativeFundingFlowPaysBothDirections 3/3 (see external_close.go / close.go).

Two fund-loss grade issues with small fixes (legacy commitments, above-tip height hints), one barrier/blockbeat interaction that needs a decided contract, and the race failure comes from a dead adapter. Inline.

Fork: minimal and honors the no-Ark rule. Commits 1-3 look upstreamable as-is. One caveat for the funding one: handler return isn't durably-applied for channel_ready (handleChannelReady defers behind localDiscoverySignals), so a durable transport can ack one whose effect is lost on crash; we're fine only because virtual-confirmation replay retransmits. FundingOutput duplicates script derivation from the funding path, share it when upstreaming. Commit 4 (contractcourt) is the rebase liability: resolveContracts now spawns a goroutine even with a nil hook (keep the inline path when nil), loadOpenChannels fails the whole arbitrator when ShouldWatchChannel errors for one channel (skip-and-log), and the resume path returns (nil, nil) for an already-advanced arbitrator (document it). Retryability itself is sound. Also go.mod pins a personal fork; org-owned before prod.

Smaller: a duplicate channel_reestablish between two live links can ping-pong recycles (rate-limit, or ignore when it matches the completed sync); LegacyPayload: true and featureless invoices ride surfaces upstream is removing; the witness beacon drops on a full 16-slot buffer; NewSigPool(1) wants a constant; backend_notifier.go maps every reorg to NegativeConf <- 0 and RegisterBlockEpochNtfn ignores bestBlock catch-up (beyond the four Codex comments, all valid); hold invoices expire at 1h wall-clock while bridge horizons are block-based.

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

Comment thread lnruntime/node.go Resolved
Comment thread lnruntime/virtual_notifier.go Resolved
Comment thread chainbackends/backend_notifier.go Resolved
Comment thread lnruntime/onchain.go Resolved
Comment thread lnruntime/ark_funding.go Resolved
Comment thread lnruntime/external_close.go Resolved
Comment thread lnruntime/close.go Resolved
Comment thread lnruntime/peer_ingress.go Resolved
Comment thread lnruntime/recovery.go Resolved
Comment thread lnruntime/intent_acceptor.go Resolved
@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lnd-runtime branch from 13aac6e to edb12eb Compare September 8, 2026 19:29
@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lnd-runtime branch from edb12eb to 3192158 Compare September 8, 2026 20:50
@litbot-9000

Copy link
Copy Markdown
Collaborator

Doc drift check: this PR's Go changes leave the per-package docs for
chainbackends, chainfees, and lwwallet stale — the new
BackendChainNotifier and BackendEstimator lnd adapters, the new
chainfees → chainsource dependency, and Rescan's terminal
chain.RescanFinished requirement are not documented yet.

diff --git a/chainbackends/AGENTS.md b/chainbackends/AGENTS.md
index 78a24bee..07515148 100644
--- a/chainbackends/AGENTS.md
+++ b/chainbackends/AGENTS.md
@@ -6,6 +6,11 @@ Concrete implementations of the `chainsource.ChainBackend` interface. Provides
 `LNDBackend` wrapping lnd's chainntnfs for real-time chain notifications, fee
 estimation, and optional v3 package relay via a pluggable `PackageSubmitter`.
 
+Also adapts the reverse direction: `BackendChainNotifier` re-exposes any
+process-owned `chainsource.ChainBackend` through lnd's
+`chainntnfs.ChainNotifier` interface, so the in-process channel runtime can
+consume Wavelength's chain source directly.
+
 ## Key Types
 
 - `LNDBackend` — Full-node backend wrapping lnd's chain notification and fee
@@ -26,6 +31,12 @@ estimation, and optional v3 package relay via a pluggable `PackageSubmitter`.
   `chainntnfs.ChainNotifier` using lndclient. Uses a 15-second registration
   timeout and goroutine-based forwarding to bridge lndclient's height-only
   block events to the full `chainntnfs` interface.
+- `BackendChainNotifier` / `NewBackendChainNotifier(backend)` — Implements
+  `chainntnfs.ChainNotifier` on top of a `chainsource.ChainBackend` that is
+  already running. Translates `RegisterConf`/`RegisterSpend`/`RegisterBlocks`
+  registrations into lnd's `ConfirmationEvent`, `SpendEvent`, and
+  `BlockEpochEvent` shapes, seeding the current tip on block-epoch
+  registration.
 - `LNDBackendFromLndClientConfig` — Config struct for building an `LNDBackend`
   from lndclient services (notifier, wallet kit, chain kit).
 - `NewLNDBackendFromLndClient(cfg)` — Factory constructing a full `LNDBackend`
@@ -66,6 +77,25 @@ estimation, and optional v3 package relay via a pluggable `PackageSubmitter`.
   `chainbackends/lndsubmitter.New(lndSvc.WalletKit)` as the default.
 - `LndClientChainNotifier` enforces a 15-second timeout on registration to
   prevent hanging under LND block load.
+- `BackendChainNotifier` never starts or stops the chain backend it wraps: the
+  embedding wallet owns that lifecycle and other subsystems share the same
+  backend. `Stop()` therefore only cancels adapter-owned registrations and
+  waits for their forwarder goroutines to exit.
+- `RegisterBlockEpochNtfn` seeds the backend's current tip itself. Wavelength
+  backends only stream *newly connected* blocks, but lnd consumers treat the
+  first epoch as their startup barrier, so a quiet chain would otherwise stall
+  them forever. A backend that also re-seeds the same tip is deduplicated, and
+  epochs below the registration height are dropped, so the stream never
+  regresses after the snapshot.
+- Confirmation and spend height hints are clamped to the current tip. Virtual
+  (hash-derived) SCIDs decode to heights far above the real chain, and a hint
+  above tip suppresses the backend's historical scan entirely, so the
+  registration would never confirm.
+- Confirmation/spend forwarding enforces the backend's shared `Seq` ordering
+  rather than trusting the `select`. Go picks randomly among ready channels, so
+  a reorg queued alongside a confirmation could otherwise be delivered after
+  the event it invalidates. `Seq == 0` denotes a backend without reorg
+  ordering and is always forwarded.
 - Log messages use canonical txid strings (not reversed byte slices).
 - **A `Canceled` status is only shutdown noise when the owning context is also
   done.** Round completion stops each VTXO's block subscription, and a block
diff --git a/chainbackends/CLAUDE.md b/chainbackends/CLAUDE.md
index 78a24bee..07515148 100644
--- a/chainbackends/CLAUDE.md
+++ b/chainbackends/CLAUDE.md
@@ -6,6 +6,11 @@ Concrete implementations of the `chainsource.ChainBackend` interface. Provides
 `LNDBackend` wrapping lnd's chainntnfs for real-time chain notifications, fee
 estimation, and optional v3 package relay via a pluggable `PackageSubmitter`.
 
+Also adapts the reverse direction: `BackendChainNotifier` re-exposes any
+process-owned `chainsource.ChainBackend` through lnd's
+`chainntnfs.ChainNotifier` interface, so the in-process channel runtime can
+consume Wavelength's chain source directly.
+
 ## Key Types
 
 - `LNDBackend` — Full-node backend wrapping lnd's chain notification and fee
@@ -26,6 +31,12 @@ estimation, and optional v3 package relay via a pluggable `PackageSubmitter`.
   `chainntnfs.ChainNotifier` using lndclient. Uses a 15-second registration
   timeout and goroutine-based forwarding to bridge lndclient's height-only
   block events to the full `chainntnfs` interface.
+- `BackendChainNotifier` / `NewBackendChainNotifier(backend)` — Implements
+  `chainntnfs.ChainNotifier` on top of a `chainsource.ChainBackend` that is
+  already running. Translates `RegisterConf`/`RegisterSpend`/`RegisterBlocks`
+  registrations into lnd's `ConfirmationEvent`, `SpendEvent`, and
+  `BlockEpochEvent` shapes, seeding the current tip on block-epoch
+  registration.
 - `LNDBackendFromLndClientConfig` — Config struct for building an `LNDBackend`
   from lndclient services (notifier, wallet kit, chain kit).
 - `NewLNDBackendFromLndClient(cfg)` — Factory constructing a full `LNDBackend`
@@ -66,6 +77,25 @@ estimation, and optional v3 package relay via a pluggable `PackageSubmitter`.
   `chainbackends/lndsubmitter.New(lndSvc.WalletKit)` as the default.
 - `LndClientChainNotifier` enforces a 15-second timeout on registration to
   prevent hanging under LND block load.
+- `BackendChainNotifier` never starts or stops the chain backend it wraps: the
+  embedding wallet owns that lifecycle and other subsystems share the same
+  backend. `Stop()` therefore only cancels adapter-owned registrations and
+  waits for their forwarder goroutines to exit.
+- `RegisterBlockEpochNtfn` seeds the backend's current tip itself. Wavelength
+  backends only stream *newly connected* blocks, but lnd consumers treat the
+  first epoch as their startup barrier, so a quiet chain would otherwise stall
+  them forever. A backend that also re-seeds the same tip is deduplicated, and
+  epochs below the registration height are dropped, so the stream never
+  regresses after the snapshot.
+- Confirmation and spend height hints are clamped to the current tip. Virtual
+  (hash-derived) SCIDs decode to heights far above the real chain, and a hint
+  above tip suppresses the backend's historical scan entirely, so the
+  registration would never confirm.
+- Confirmation/spend forwarding enforces the backend's shared `Seq` ordering
+  rather than trusting the `select`. Go picks randomly among ready channels, so
+  a reorg queued alongside a confirmation could otherwise be delivered after
+  the event it invalidates. `Seq == 0` denotes a backend without reorg
+  ordering and is always forwarded.
 - Log messages use canonical txid strings (not reversed byte slices).
 - **A `Canceled` status is only shutdown noise when the owning context is also
   done.** Round completion stops each VTXO's block subscription, and a block
diff --git a/chainfees/AGENTS.md b/chainfees/AGENTS.md
index 659ec05e..f66120c4 100644
--- a/chainfees/AGENTS.md
+++ b/chainfees/AGENTS.md
@@ -18,11 +18,18 @@ on-chain transactions from wallet and daemon chain backends.
 - `MinEstimator` — composes multiple `NamedEstimator` children and returns the
   lowest successful estimate, logging when providers diverge.
 - `NamedEstimator` — pairs a `chainfee.Estimator` with a stable name for logs.
+- `BackendEstimator` — adapts a `chainsource.ChainBackend` to
+  `chainfee.Estimator` for the in-process channel runtime. Converts the
+  backend's sat/vbyte answer to lnd's sat/kw unit and enforces a relay floor
+  supplied at construction. `Start`/`Stop` are no-ops: the shared chain
+  backend's lifecycle stays with its owner.
+  Constructor: `NewBackendEstimator(backend, relayFee)`.
 
 ## Relationships
 
 - **Depends on**: `lndclient` (WalletKit RPC client), `lnd/lnwallet/chainfee`
-  (the `Estimator` interface and `SatPerKWeight`/`FeePerKwFloor` types).
+  (the `Estimator` interface and `SatPerKWeight`/`FeePerKwFloor` types),
+  `chainsource` (the `ChainBackend` fee source behind `BackendEstimator`).
 - **Depended on by**: `chainbackends` (wires these estimators into chain
   backend adapters), `waved` (server wiring and logging subsystem
   registration).
@@ -38,6 +45,15 @@ on-chain transactions from wallet and daemon chain backends.
   estimate yet" (see `WalletKitEstimator.cachedRate`).
 - `MempoolSpaceEstimator` rejects non-HTTPS URLs except for loopback hosts, to
   avoid tampering with fee data in transit.
+- `BackendEstimator` is deliberately fail-*soft*, unlike
+  `NewWalletKitEstimator`: a backend error or a non-positive estimate returns
+  the configured relay floor with a nil error. It prices channel operations,
+  and lnd treats an estimator error as a fatal negotiation failure, so a
+  transient fee-source outage would otherwise disable channel funding and
+  cooperative close. For the same reason it must not be composed into
+  `MinEstimator`, where a floor answer would beat every live provider.
+- `NewBackendEstimator` raises a below-floor `relayFee` argument to
+  `chainfee.FeePerKwFloor`, so the fallback rate is always relay-valid.
 - **Log severity in `MinEstimator` tracks whether an operator must act.** A
   single provider failing is logged at info: the estimator queries several
   providers precisely so it can continue past one, and a later provider can
diff --git a/chainfees/CLAUDE.md b/chainfees/CLAUDE.md
index 659ec05e..f66120c4 100644
--- a/chainfees/CLAUDE.md
+++ b/chainfees/CLAUDE.md
@@ -18,11 +18,18 @@ on-chain transactions from wallet and daemon chain backends.
 - `MinEstimator` — composes multiple `NamedEstimator` children and returns the
   lowest successful estimate, logging when providers diverge.
 - `NamedEstimator` — pairs a `chainfee.Estimator` with a stable name for logs.
+- `BackendEstimator` — adapts a `chainsource.ChainBackend` to
+  `chainfee.Estimator` for the in-process channel runtime. Converts the
+  backend's sat/vbyte answer to lnd's sat/kw unit and enforces a relay floor
+  supplied at construction. `Start`/`Stop` are no-ops: the shared chain
+  backend's lifecycle stays with its owner.
+  Constructor: `NewBackendEstimator(backend, relayFee)`.
 
 ## Relationships
 
 - **Depends on**: `lndclient` (WalletKit RPC client), `lnd/lnwallet/chainfee`
-  (the `Estimator` interface and `SatPerKWeight`/`FeePerKwFloor` types).
+  (the `Estimator` interface and `SatPerKWeight`/`FeePerKwFloor` types),
+  `chainsource` (the `ChainBackend` fee source behind `BackendEstimator`).
 - **Depended on by**: `chainbackends` (wires these estimators into chain
   backend adapters), `waved` (server wiring and logging subsystem
   registration).
@@ -38,6 +45,15 @@ on-chain transactions from wallet and daemon chain backends.
   estimate yet" (see `WalletKitEstimator.cachedRate`).
 - `MempoolSpaceEstimator` rejects non-HTTPS URLs except for loopback hosts, to
   avoid tampering with fee data in transit.
+- `BackendEstimator` is deliberately fail-*soft*, unlike
+  `NewWalletKitEstimator`: a backend error or a non-positive estimate returns
+  the configured relay floor with a nil error. It prices channel operations,
+  and lnd treats an estimator error as a fatal negotiation failure, so a
+  transient fee-source outage would otherwise disable channel funding and
+  cooperative close. For the same reason it must not be composed into
+  `MinEstimator`, where a floor answer would beat every live provider.
+- `NewBackendEstimator` raises a below-floor `relayFee` argument to
+  `chainfee.FeePerKwFloor`, so the fallback rate is always relay-valid.
 - **Log severity in `MinEstimator` tracks whether an operator must act.** A
   single provider failing is logged at info: the estimator queries several
   providers precisely so it can continue past one, and a later provider can
diff --git a/lwwallet/AGENTS.md b/lwwallet/AGENTS.md
index c7e1e757..3031b657 100644
--- a/lwwallet/AGENTS.md
+++ b/lwwallet/AGENTS.md
@@ -122,6 +122,12 @@ base logic with the neutrino-backed `btcwbackend` sibling via the extracted
   lags, btcwallet can advance `PutSyncedTo` past unindexed activity
   permanently. Avoid load-balanced public endpoints; point `EsploraURL` at a
   self-consistent instance you control.
+- `Rescan` must end with a `chain.RescanFinished` notification. btcwallet only
+  marks its chain view synchronized once it sees that terminal message, and an
+  unsynchronized view disables channel funding even though every block in the
+  range was already processed. `Rescan` also rejects a start height above the
+  current tip up front instead of emitting a finished notification for a range
+  it never scanned.
 - UTXO enumeration queries Esplora directly rather than btcwallet's internal
   UTXO set, because btcwallet does not credit-mark non-default scope outputs.
 - `Stop()` explicitly closes btcwallet's internal database to prevent resource
diff --git a/lwwallet/CLAUDE.md b/lwwallet/CLAUDE.md
index c7e1e757..3031b657 100644
--- a/lwwallet/CLAUDE.md
+++ b/lwwallet/CLAUDE.md
@@ -122,6 +122,12 @@ base logic with the neutrino-backed `btcwbackend` sibling via the extracted
   lags, btcwallet can advance `PutSyncedTo` past unindexed activity
   permanently. Avoid load-balanced public endpoints; point `EsploraURL` at a
   self-consistent instance you control.
+- `Rescan` must end with a `chain.RescanFinished` notification. btcwallet only
+  marks its chain view synchronized once it sees that terminal message, and an
+  unsynchronized view disables channel funding even though every block in the
+  range was already processed. `Rescan` also rejects a start height above the
+  current tip up front instead of emitting a finished notification for a range
+  it never scanned.
 - UTXO enumeration queries Esplora directly rather than btcwallet's internal
   UTXO set, because btcwallet does not credit-mark non-default scope outputs.
 - `Stop()` explicitly closes btcwallet's internal database to prevent resource

How to apply

Save the diff above and git apply it, or regenerate it locally with the
doc-gardening skill scoped to the three packages:

/doc-gardening chainbackends
/doc-gardening chainfees
/doc-gardening lwwallet

Each CLAUDE.md must stay byte-identical to its sibling AGENTS.md, and
make doc-check should pass afterwards.

This check is advisory only — it does not block the merge.


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

@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lnd-runtime branch from 3192158 to 1ce52cf Compare September 9, 2026 10:31
@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lnd-runtime branch 2 times, most recently from e2f75d1 to 76427bf Compare September 15, 2026 17:07
@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lnd-runtime branch from 76427bf to 6435822 Compare September 15, 2026 17:40
@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lnd-runtime branch from 6435822 to 23717af 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

@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lnd-runtime branch 3 times, most recently from b060b79 to b96f05a Compare November 17, 2026 21:46
@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lnd-runtime branch from b96f05a to ca31a4e Compare November 17, 2026 21:58
@litbot-9000

Copy link
Copy Markdown
Collaborator

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

Keep the root runtime and portable database on the same recovery and
idle-worker revision for integration tests. Do not merge on these
personal replacements. Replace both with verified official upstream
versions before supporting a downstream release.
Use the same channel database on both hosts without importing or
rewriting prototype stores at startup.
Expose backend-neutral confirmation and spend notifications so a
channel can be recovered without a dedicated chain connection.
Bind a logical peer to its authenticated transport and retain inbound
messages until the native link can accept them.
Keep preimages available across restarts and derive virtual chain
notifications from the channel's actual funding state.
Tie the virtual funding point to a durable reservation and let the
chain arbitrator take over when the backing reaches the chain.
Admit only the registered initiator and reconcile funding progress
against the signed backing before activating either endpoint.
Route each peer to its owned links without duplicating the switch,
wallet, invoice registry or on-chain subscriptions.
Require both parties to see enforceable settlement evidence before
archiving the native channel and releasing its replacement payouts.
Use the same authenticated ownership for funding, payment and close
messages. Exercise lost replies, concurrent peers and restart recovery
through the composed native runtime.
@sputn1ck
sputn1ck force-pushed the kon/ark-channel-lnd-runtime branch from 90e8558 to 8c81939 Compare November 24, 2026 17:11
@litbot-9000

Copy link
Copy Markdown
Collaborator

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

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.

3 participants