Skip to content

staticaddr/withdraw: harden replacement monitoring - #1215

Draft
hieblmi wants to merge 28 commits into
lightninglabs:multi-address-corefrom
hieblmi:multi-address-withdrawal-hardening
Draft

staticaddr/withdraw: harden replacement monitoring#1215
hieblmi wants to merge 28 commits into
lightninglabs:multi-address-corefrom
hieblmi:multi-address-withdrawal-hardening

Conversation

@hieblmi

@hieblmi hieblmi commented Aug 27, 2026

Copy link
Copy Markdown
Collaborator

Summary

This is PR 3 of 3 in the static-address multi-address stack. It depends on
#1214 and is based on multi-address-address-hardening so this PR only shows
withdrawal replacement and monitor hardening.

This follow-up:

  • validates that a confirmed replacement transaction actually spends the
    selected deposits;
  • identifies static-address change by script instead of assuming a fixed
    output index;
  • reconciles partial conflicting spends without marking untouched deposits as
    withdrawn;
  • follows the output from the transaction that really replaced the original
    withdrawal; and
  • joins withdrawal monitor goroutines during shutdown and adds multi-address
    replacement coverage.

Stack

  1. staticaddr: multi-address #1139 — multi-address core
  2. staticaddr/address: harden multi-address startup #1214 — address startup hardening
  3. This PR — withdrawal replacement hardening

Testing

  • go test -race ./staticaddr/...
  • go vet ./...
  • git diff --check

Pull Request Checklist

  • Added an entry to docs/release-notes/release-notes-next.md.

@hieblmi
hieblmi force-pushed the multi-address-withdrawal-hardening branch from 0a947a5 to 9dd7f66 Compare August 27, 2026 10:28
@hieblmi
hieblmi force-pushed the multi-address-address-hardening branch from 56dcc74 to 7c226da Compare August 27, 2026 10:28
@hieblmi
hieblmi force-pushed the multi-address-withdrawal-hardening branch from 9dd7f66 to 93bbffa Compare August 27, 2026 10:40
@hieblmi
hieblmi force-pushed the multi-address-address-hardening branch from 7c226da to e85c0d3 Compare August 27, 2026 10:40
@hieblmi
hieblmi force-pushed the multi-address-withdrawal-hardening branch from 93bbffa to 942e440 Compare August 27, 2026 11:46
@hieblmi
hieblmi force-pushed the multi-address-address-hardening branch from e85c0d3 to 6f82255 Compare August 27, 2026 11:47
@hieblmi
hieblmi force-pushed the multi-address-withdrawal-hardening branch from 942e440 to 6245c73 Compare August 27, 2026 12:41
@hieblmi
hieblmi force-pushed the multi-address-address-hardening branch 2 times, most recently from c458192 to f709e0c Compare August 28, 2026 10:34
@hieblmi
hieblmi force-pushed the multi-address-withdrawal-hardening branch from 6245c73 to 82b5b00 Compare August 28, 2026 10:34
@hieblmi
hieblmi force-pushed the multi-address-withdrawal-hardening branch from 82b5b00 to 042bc9b Compare August 28, 2026 13:35
@hieblmi
hieblmi force-pushed the multi-address-address-hardening branch from f709e0c to 1179815 Compare August 28, 2026 13:35
@hieblmi
hieblmi changed the base branch from multi-address-address-hardening to multi-address-core August 28, 2026 13:35
@hieblmi
hieblmi force-pushed the multi-address-core branch 4 times, most recently from a1b5ec5 to c74ac6c Compare August 31, 2026 10:37
@hieblmi
hieblmi force-pushed the multi-address-withdrawal-hardening branch from 042bc9b to 8ab455f Compare August 31, 2026 12:27
Reserve separate key families for static receive and change addresses.
This keeps derived keys out of the legacy static-address and HTLC key
streams.
Associate every deposit with the static address parameters that created
it. This lets restored deposits recover the correct script and signing
keys instead of assuming the legacy root address.
Create receive and change addresses from locally derived client keys
while reusing the server key and expiry from the legacy seed. Persist,
import, and activate each script before returning it to callers.

Rebuild the active address index on startup and serialize issuance
without blocking address reads. Import only scripts missing from lnd,
and accept duplicate-import errors only when they identify the expected
Taproot output key.
Look up each newly discovered wallet UTXO by script and persist the
matching active-address parameters on the deposit. Reject unknown
scripts before allocating the timeout sweep address.

Use the per-deposit parameters when constructing the FSM, sign
descriptor, and unilateral expiry sweep so derived-address recovery uses
its owning script and key.
Register timeout-sweep confirmations by destination script instead of
the originally published txid. This lets recovery detect an RBF
replacement after restart with a stale txid.
Construct each cooperative MuSig2 session from the address parameters
stored on its deposit. This prepares loop-ins and withdrawals to sign
inputs belonging to different derived static addresses.

Clean up sessions created before a later setup failure. Reject duplicate
deposit outpoints to avoid leaking signer state.

Validate transaction inputs, session handles, and nonce counts before
signing so malformed responses fail before any signer operation.
Associate fractional loop-ins with their operation-specific static
change address so recovery restores the descriptor needed to reconstruct
signed transactions. Backfill legacy fractional swaps to the original
address.
Create a fresh static address for fractional loop-in change and send its
descriptor to the server. Reconstruct signed HTLCs with the persisted
parameters and verify cooperative batch change by output script.
Multi-address loop-ins sign and construct transactions from the
parameters attached to each deposit and their dedicated change address.
The legacy root address fields therefore became write-only, but
populating them could still abort signing, sweep handling, or recovery
when the root lookup failed.

Remove those fields and lookups, select the FSM from the protocol
version persisted with the swap, and set that version before
constructing new state machines. Keep the root-parameter lookup used by
autoloop expiry calculation and add regression coverage for recovery and
unsupported persisted versions.
Create a fresh static address for partial-withdrawal change and identify
it in the confirmed transaction through its active change-family script,
without assuming output order or count. Record withdrawn and change
amounts by script identity.

Keep all withdrawal outputs in the PSBT without separate signing
metadata while preserving full-withdrawal behavior.
Let loop static deposit create and fund a fresh receive address through
lnd SendCoins. Validate funding arguments before address creation and
require explicit confirmation unless --force is set, including for
non-interactive and first-use deposits.

Allow NewStaticAddress RPC callers to fund a requested existing static
address by resolving it through the active script index. Expose the
nested request through the client RPC, require swap:execute permission,
and cover the CLI new-address and daemon existing-address funding paths.
Regenerate RPC and CLI documentation.
Include the owning static address in every deposit RPC response and CLI
listing. Users can distinguish deposits created by different receive and
change addresses without reconstructing scripts externally.

Calculate blocks until expiry from each deposit owner instead of the
legacy root address, and reject deposits whose owning parameters are
missing. Centralize deposit response conversion and update generated RPC
artifacts, regression coverage, and command replay fixtures.
The CLI previously recognized an uninitialized static-address seed by
searching arbitrary gRPC error text. Any wrapping or wording change
could suppress the L402 backup warning before a user funded a newly
derived address.

Map ErrNoStaticAddress to codes.NotFound at the RPC boundary and
classify that status in the CLI. Retain compatibility with older daemons
only for an exact Unknown-status message, avoiding the broad substring
match, and cover both sides with regression tests.
A static-address account can now receive deposits across multiple
derived addresses, so the singular summary field can no longer describe
the current receive address. Removing or repurposing field 1 would break
existing clients.

Keep the wire value as the legacy/root derivation address, formally
deprecate it, document the expiry as the shared CSV delay, and direct
CLI users to derive a fresh receive address. Rename the server locals to
make the compatibility behavior explicit and regenerate protobuf and
Swagger artifacts.
Cover per-deposit address ownership and operation-specific change
outputs across the shared SQL persistence boundary. Reconstruct the
deposit, loop-in, and withdrawal stores to verify ownership and change
metadata survive restart.
Document fresh receive-address derivation, lazy seed initialization,
funding-address lookup hardening, and the swap:execute permission
required by address creation. Regenerate the CLI, gRPC, Swagger, and
man-page documentation and add feature, breaking-change, and recovery
release notes.
Follow the transaction that actually spends the watched deposit, require
its confirmed form to spend every selected withdrawal input, persist
that transaction, and stop republishing both the original and
replacement.
Stop republishing an obsolete withdrawal when its confirmed spender
consumes only part of the deposit group. Finalize spent deposits,
release untouched deposits, and clear stale transaction references.
handleWithdrawal starts a long-lived spend and confirmation monitor, but
the manager did not own its lifecycle. Manager.Run could return while a
monitor was still transitioning deposits, updating withdrawal rows, or
reading package-level logging state.

Track every monitor with a WaitGroup and give the run loop a child
context that is canceled on every exit path. Close request delivery,
cancel the monitors, and join them before returning. Configure the test
logger once and make monitor tests cancel and wait so consecutive race
tests cannot overlap through the global logger.
Withdrawal spend monitoring followed an RBF replacement's txid while
retaining the original destination script. Confirmation requests match
both values, so a replacement paying a newly derived destination could
remain invisible and leave deposits stuck in Withdrawing.

Build the confirmation request from the actual spending transaction, use
a positive spending height as its historical hint with the startup
height as the mempool fallback, and identify change from the confirmed
transaction's own destination. Persist the confirmation's block height
and remove both original and replacement republish entries after
resolution.

Widen the manager store dependency to an interface so the complete
transition and persistence path can be covered without a database, and
add replacement, map-cleanup, and mempool-height regression tests.
Concurrent confirmation handlers opened deferred transactions to look up
their withdrawal IDs before writing terminal transaction data. On
SQLite, both handlers could acquire read snapshots and one would then
fail its write upgrade with SQLITE_BUSY.

Look up the immutable withdrawal association before issuing the update,
and persist the confirmed transaction before transitioning deposits to
Withdrawn. This prevents concurrent confirmations from losing their
history and keeps withdrawals recoverable if persistence fails.
@hieblmi
hieblmi force-pushed the multi-address-withdrawal-hardening branch from 8ab455f to e501056 Compare September 1, 2026 12:05
@hieblmi
hieblmi force-pushed the multi-address-core branch 5 times, most recently from ee1bbba to 5b4bd5b Compare September 3, 2026 06:16
Comment on lines 466 to 470
err = m.cfg.Store.CreateWithdrawal(ctx, deposits)
if err != nil {
log.Errorf("Error persisting "+
"withdrawal: %v", err)
}

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.

Please fail or reconcile when CreateWithdrawal fails. Continuing can report success without the association required to persist confirmation or recover history.

if err != nil {
if !strings.Contains(err.Error(), chain.ErrSameNonWitnessData.Error()) &&
!strings.Contains(err.Error(), "output already spent") &&
!strings.Contains(err.Error(), chain.ErrInsufficientFee.Error()) {

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.

Please return ErrInsufficientFee. Suppressing it makes a rejected withdrawal return success with an empty transaction hash and address.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants