Skip to content

txconfirm: recover fee splits across daemon restarts - #1654

Merged
bhandras merged 1 commit into
mainfrom
issue-1651-durable-fee-splits
Nov 27, 2026
Merged

bhandras merged 1 commit into
mainfrom
issue-1651-durable-fee-splits

Conversation

@bhandras

@bhandras bhandras commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

A wallet can split a confirmed coin to fund several recovery packages. If the daemon restarts after Bitcoin Core accepts the split, the original input may disappear from the wallet before the daemon learns which outputs to use. A lost publication reply can leave the same uncertainty.

Store the signed transaction, each output's assigned parent and a confirmation height hint in a single wallet row before submitting. Duplicate saves must match the recorded candidate. At startup the broadcaster restores its input exclusions, rejoins the split confirmation watch and watches each original wallet input for its confirmed spender from the saved height. A confirmed competing transaction releases the original candidate and its predicted outputs. Ambiguous broadcast errors retain the signed bytes. The wallet supplies the previous-output scripts from its transaction history, including after an input has been spent. A failed journal clear after confirmation is retried on a later block. The split outputs are available to fee children once confirmation arrives. Size the outputs for the wallet's child script family so that a taproot fee input can fund the package assigned to it.

This builds on #1652. Schema version 33 adds the wallet journal. The scope is the fee-output split. Durable batch approval and aggregate CPFP fee commitments are separate parts of #1651.

Verification included a database ownership test and a race-tested restart case with lost storage and publication receipts. On Bitcoin Core regtest with an LND wallet, a single confirmed funding output produced a four-output split. The daemon restarted before mining, the same txid confirmed, and three later v3 fee children spent distinct split outputs. All three exits completed.

Bitcoin Core regtest also confirmed a competing spend while the daemon was offline with each of the three wallet backends (LND, lwwallet and btcwallet). On restart the daemon built a different split from output zero of the confirmed competitor. At least two v3 fee children spent distinct outputs of that replacement in later blocks. The exits completed and the recovered wallet balance swept to the external destination.

@bhandras

Copy link
Copy Markdown
Member Author

/gateway review

Trace the split journal and startup path across lost DB receipts, a lost first broadcast, daemon restart, a confirmed split, parent eviction and journal cleanup. Check that the same candidate is recovered, that owned inputs stay excluded, and that a backend or journal failure cannot promote an unconfirmed output. Evaluate the script-aware split sizing. Review the changes on top of #1652. Batch approval and the total fee cap are separate work.

@lightninglabs-gateway

lightninglabs-gateway Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

❌ gateway review failed: code-review skill failed across all auth modes: You've hit your org's monthly spend limit · ask your admin to raise it at https://claude.ai/admin-settings/usage · your weekly limit resets Nov 29, 6am (UTC)

See workflow logs for details.

@bhandras

Copy link
Copy Markdown
Member Author

Claude: Verdict: approve. No reachable blocker found.

The split row is written before every publish. Restart restores the exact signed bytes. A failed save or clear is retried at block pace. I found one follow-up and two small nits.

What I checked

Area Result
Exact signed bytes Correct. encodeFeeSplit stores the height hint, the serialized wire.MsgTx and one owner hash per output. restoreFeeSplit rebuilds tx, txid and watchScript from those bytes, and journalEntry keeps the raw row. Every rebroadcast sends pending.tx. TestFeeSplitJournalRestart checks that the bytes after restart are identical to the first submit.
Commit before submit Correct. submitFeeSplit calls saveFeeSplit before broadcastFanout, so a failed save never reaches the backend. The rejection branches are gated on journal == nil || pending.saved, so an error from the database alone cannot trigger a rebuild.
Lost DB receipt Correct. With the same bytes, SaveWalletFeeSplit updates the row (1 row affected). With different bytes, the WHERE makes it a no-op (0 rows). So retrying a save that committed but lost its reply is safe on both SQLite and Postgres. The DB test covers both cases.
Lost broadcast receipt Correct. A transport or unknown error is not treated as a rejection. The candidate stays pending, keeps its watch and input exclusion, and is rebroadcast at block pace.
Restore across restart Correct. RestoreFeeSplit runs before the actor is registered. It sets FanoutPending, fanoutInputs and the predicted inputs per parent. ResumeFeeSplit starts the FSM, then the block subscription, then the watch with the original heightHint, so a split that confirmed while the daemon was down is still seen. lastBroadcastHeight restores as 0, so the first block rebroadcasts. A failed watch registration is retried in handleBlockObserved via fanoutWatchActive.
Output eligibility Safe. Restored outputs only go into PredictedFeeInputs, which excludes them for other parents. No parent can spend them until a confirmation promotes them. On confirmation, handleFanoutConfirmed drops parent state for parents that are no longer tracked, so their outputs fall back to plain wallet UTXOs.
Last-parent eviction Correct change. A signed split may already be in the mempool. Releasing its inputs while it is still unconfirmed would let a later split or child double-spend it. Keeping it pending until it confirms or is rejected is right. Evict already removes the parent's predicted entries, so nothing leaks.
Retry after clear failure Correct. On confirmation, a failed clear sets confirmed, and the next processDemands call retries processConfirmed. After a restart, the watch replays the confirmation. On rejection, a failed clear keeps the candidate and retries at the next rebroadcast interval. The test covers the confirmation case.

Follow-up, not a blocker

A split whose inputs were spent by something else now stays pending forever.

  1. The split stays unconfirmed past DefaultFeeInputLeaseExpiry (1h). Restore does not take the lease again.
  2. Another spender in the wallet uses one of its inputs.
  3. Rebroadcast returns missing-or-spent. isAmbiguousSpendError maps that to nil, so the candidate is kept.
  4. The watch is on the split's txid, which will never confirm. The journal row survives restarts.
  5. The FSM stays in FanoutPending, so the wallet can never build another split.

Treating missing-or-spent as ambiguous was already the behavior before this PR, while any parent was live. What this PR removes is the two escapes: last-parent eviction and restart. It is still unlikely. It needs a long unconfirmed split, an expired lease, and a wallet spend that picks that exact coin. The cost is delay, not lost funds: CPFP still works from any confirmed wallet UTXO, and only the split path stops. A proper fix is a spend watch on the split's inputs that clears the row when a conflicting spend confirms. That belongs in its own PR, not this one.

Nits (optional)

  • db/CLAUDE.md still says LatestMigrationVersion = 31, and the migration list stops at 000031. Add 000032_fee_input_split.
  • driveFeeBump now reads a.feeBumpPending() for feeBumpWatchFanout instead of using out.txid/out.watchScript. That is fine as long as the FSM keeps running. Carrying heightHint on the outbox event would remove the dependency.

Minimal necessary fix

None.

@bhandras
bhandras force-pushed the issue-1651-durable-fee-splits branch from 8a131c3 to f39051c Compare November 27, 2026 10:18
@bhandras
bhandras added this pull request to stack #1660 November 27, 2026 10:18
@bhandras

Copy link
Copy Markdown
Member Author

/gateway review

Please review the current commit f39051c against its PR base. Focus on reachable ownership, confirmation gating, and wallet quote correctness within this layer.

@lightninglabs-gateway

lightninglabs-gateway Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

❌ gateway review failed: code-review skill failed across all auth modes: You've hit your org's monthly spend limit · ask your admin to raise it at https://claude.ai/admin-settings/usage · your weekly limit resets Nov 29, 6am (UTC)

See workflow logs for details.

@bhandras

Copy link
Copy Markdown
Member Author

Claude: No blocking issues at f39051cf for this layer. The split journal, migration 33 and restart input ownership all hold. I read the code but could not run the tests here: running them needed permission that wasn't granted.

Durable split journal and migration 33

The table has one row (singleton = 1) holding a candidate BLOB. Postgres works because db/migrate/migrations.go:49 maps BLOB to BYTEA.

Case What happens
Save succeeds but the reply is lost The retry sends the same bytes. They match, so the update counts one row and pending.saved is set.
Another split already holds the row The WHERE doesn't match, so zero rows change and saveFeeSplit returns an error before broadcasting.
Clear Deletes only the exact bytes this split saved.

Order before broadcast (submitFeeSplit)

  • The split is saved before broadcastFanout is called.
  • A save error is never read as a rejection: the rejection branch needs journal == nil || pending.saved. The split stays pending with its inputs excluded, and the save is retried on the next rebroadcast block.
  • A rejection clears the journal before the outputs are released or the split is rebuilt. If that clear fails, the split stays pending and retries.
  • So the journal row exists whenever the split's bytes could have reached the chain backend.

Restart

  • RestoreFeeSplit runs before RegisterWithSystem. It puts the FSM straight into the pending state and sets fanoutInputs before any new submission can arrive. So a new fee child cannot reuse the split's inputs.
  • ResumeFeeSplit starts the FSM and the block subscription, then registers the watch with the saved heightHint. A confirmation that happened while the daemon was offline is still caught.
  • handleBlockObserved retries a failed watch registration. It also drives the FSM even when no job is live, so a restored split keeps being rebroadcast and resolved after every exit job has finished.
  • A confirmation whose journal clear fails keeps confirmed = true and retries on the next block. The row is never left behind with the FSM idle.
  • processParentEvicted keeps the split pending even with no parents left, so the row always matches FSM state.

Output ownership after restart

  • The saved record lists each output's owner by index, so outputs with equal amounts keep their original parents.
  • Restored outputs stay predicted until the watch fires.
  • If the split confirms before the jobs re-register, handleFanoutConfirmed drops the state of parents that are no longer live. Those outputs become ordinary confirmed wallet coins, which the wallet can hand to the restored jobs.

Non-blocking

  • Restore watches TxOut[0].PkScript, which can differ from the script chosen at build time. This is safe: the watch is keyed by txid, and any output script of that transaction works as the filter.
  • Wallet leases on the split inputs are not restored. If another wallet spend takes those inputs, the split is rejected on rebroadcast, the row is cleared, and the split is rebuilt. No funds are at risk.
  • The fee estimate now prices the child using the wallet's change script (parentChangePkScript). The script is cached per parent, so this adds no address churn.

@bhandras
bhandras force-pushed the issue-1651-durable-fee-splits branch from f39051c to bb6e720 Compare November 27, 2026 12:54
@bhandras

Copy link
Copy Markdown
Member Author

/gateway review

Re-review bb6e720 against its immediate parent. Check confirmed-spender ownership and per-entry admission within the scope of this PR. Report concrete blockers and distinguish them from follow-ups.

@lightninglabs-gateway

lightninglabs-gateway Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

❌ gateway review failed: code-review skill failed across all auth modes: You've hit your org's monthly spend limit · ask your admin to raise it at https://claude.ai/admin-settings/usage · your weekly limit resets Nov 29, 6am (UTC)

See workflow logs for details.

@bhandras
bhandras force-pushed the issue-1651-durable-fee-splits branch from bb6e720 to 08ab3a9 Compare November 27, 2026 13:05
@bhandras

Copy link
Copy Markdown
Member Author

/gateway review

Review 08ab3a9 against its immediate parent. Check confirmed-spender recovery and the wallet preview semantics in their respective PRs.

@lightninglabs-gateway

lightninglabs-gateway Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

❌ gateway review failed: code-review skill failed across all auth modes: You've hit your org's monthly spend limit · ask your admin to raise it at https://claude.ai/admin-settings/usage · your weekly limit resets Nov 29, 6am (UTC)

See workflow logs for details.

@bhandras

Copy link
Copy Markdown
Member Author

Claude: I approve 08ab3a9 (compared against f7ecd19). It has no reachable merge blockers in spend-watch registration (AskThen) or cancellation (Tell). I read the code only; I ran no tests, as asked.

Review of 08ab3a9 against f7ecd19: approved, no merge blockers

Checked:

  • Ordering of register and unregister: actor.AskThen calls ref.Ask before it returns (baselib/actor/ask_then.go:164). So the RegisterSpendRequest is already in chainsource's mailbox before any later UnregisterSpendRequest Tell from the same actor. Chainsource handles registration inside its own turn (chainsource/chainsource.go:396-427). A stop that follows a register therefore always tears it down. No registration can outlive its candidate this way.
  • Rebuild ordering: in clearAndRebuild, protofsm adds the outbox entries in order (baselib/protofsm/state_machine.go:540). The old candidate's unwatch runs before the new candidate's watch, which reads feeBumpPending() after the whole turn. fanoutWatchActive and splitSpendWatches are reset before the new registrations, so they never carry over to the wrong candidate.
  • Stale receipts: success receipts are ignored. A failure receipt only removes its map entry when req.candidate == pending.txid, so a late failure from a replaced candidate cannot cause a retry. splitSpendObserved uses the same candidate check, so a callback from an old candidate is dropped.
  • Retry after a failed or timed-out registration: the failed outpoint is removed from splitSpendWatches and registered again on the next block by handleBlockObserved calling watchFeeSplit. If the first attempt actually succeeded but its reply timed out, chainsource's spawnReplacing replaces it, so retrying leaves one subscription, not two. While a receipt is still pending, the map entry stops a duplicate registration on each block.
  • Every way out of the pending state emits an unwatch: processResolved, clearPendingFanout and clearAndRebuild all emit feeBumpUnwatchFanout. Unwatch always clears the map, so stopSplitSpendWatches(out.txid) only unregisters watches made under that candidate's caller ID.
  • height > 0 filter: all three backends (lwwallet/Esplora, lnd, btcwbackend) report spends only once confirmed. The one-shot spend watch therefore cannot be used up by an unconfirmed spend that the handler then drops.

Not blocking:

  • If the unregister Tell fails, the map is still cleared and the chainsource sub-actor leaks until it fires. Its callback is then filtered by the candidate check. The cost is one idle subscription, not a wrong state.

Base automatically changed from issue-1651-wallet-exit-queue to main November 27, 2026 13:35
Store the signed split and output assignments before submission. Restore
the original inputs and confirmation watch before new exits can spend.
Match output values to the child script type and reuse the candidate
after lost storage or network receipts.
@bhandras
bhandras force-pushed the issue-1651-durable-fee-splits branch from 08ab3a9 to e966e83 Compare November 27, 2026 13:35
@bhandras
bhandras merged commit 70d48f5 into main Nov 27, 2026
29 of 30 checks passed
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.

1 participant