From e966e83e45368e5b553affcd3438e0efbb52710e Mon Sep 17 00:00:00 2001 From: Andras Banki-Horvath Date: Thu, 26 Nov 2026 18:10:25 +0100 Subject: [PATCH] txconfirm: recover fee splits across daemon restarts 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. --- db/AGENTS.md | 5 +- db/CLAUDE.md | 5 +- db/migrations.go | 2 +- .../000033_fee_input_split.down.sql | 1 + .../migrations/000033_fee_input_split.up.sql | 6 + db/sqlc/models.go | 5 + db/sqlc/querier.go | 3 + db/sqlc/queries/wallet_fee_split.sql | 10 + db/sqlc/schemas/generated_schema.sql | 5 + db/sqlc/wallet_fee_split.sql.go | 44 +++ db/wallet_fee_split_test.go | 36 ++ txconfirm/AGENTS.md | 4 + txconfirm/CLAUDE.md | 4 + txconfirm/actor.go | 75 +++- txconfirm/broadcaster_test.go | 6 +- txconfirm/fee_bump_fsm_logic.go | 94 ++++- txconfirm/fee_bump_fsm_types.go | 42 ++- txconfirm/fee_input_actor.go | 31 +- txconfirm/fee_split_journal.go | 335 ++++++++++++++++++ txconfirm/fee_split_journal_test.go | 187 ++++++++++ waved/server.go | 44 +++ waved/wallet_sign_itest.go | 28 ++ 22 files changed, 930 insertions(+), 42 deletions(-) create mode 100644 db/sqlc/migrations/000033_fee_input_split.down.sql create mode 100644 db/sqlc/migrations/000033_fee_input_split.up.sql create mode 100644 db/sqlc/queries/wallet_fee_split.sql create mode 100644 db/sqlc/wallet_fee_split.sql.go create mode 100644 db/wallet_fee_split_test.go create mode 100644 txconfirm/fee_split_journal.go create mode 100644 txconfirm/fee_split_journal_test.go create mode 100644 waved/wallet_sign_itest.go diff --git a/db/AGENTS.md b/db/AGENTS.md index 76b6e7e93..144741a96 100644 --- a/db/AGENTS.md +++ b/db/AGENTS.md @@ -165,7 +165,7 @@ For field-level detail, use `go doc github.com/lightninglabs/wavelength/db. 0 { + + if req.spender == pending.txid { + a.handleFanoutConfirmed( + ctx, &confirmationObservedMsg{ + txid: pending.txid, + }, + ) + } else { + a.driveFeeBump(ctx, &feeBumpFanoutResolved{ + txid: pending.txid, + spender: req.spender, + }) + } + } + + return fn.Ok[Resp](&EnsureConfirmedResp{}) + case *confirmationObservedMsg: a.handleConfirmationObserved(ctx, req) @@ -1437,6 +1493,23 @@ func (a *TxBroadcasterActor) handleBlockObserved(ctx context.Context, a.hasBestHeight = true } + // A recorded split remains wallet work even if every original + // subscriber stopped or the daemon restarted before any job resumed. + if pending := a.feeBumpPending(); pending != nil && + a.cfg.FeeSplitJournal != nil { + + if err := a.watchFeeSplit(ctx, pending); err != nil { + a.log.WarnS(ctx, "Unable to restore fee split watch", + err, + ) + } + a.driveFeeBump(ctx, &feeBumpDemandsObserved{ + height: msg.height, retryInterval: a. + cfg. + FeeBumpIntervalBlocks, + }) + } + for _, entry := range a.tracked { if a.retryPendingFailure(ctx, entry) { continue diff --git a/txconfirm/broadcaster_test.go b/txconfirm/broadcaster_test.go index 84416d542..9d880504b 100644 --- a/txconfirm/broadcaster_test.go +++ b/txconfirm/broadcaster_test.go @@ -3719,8 +3719,8 @@ func (c *testFeeBump) OnFanoutConfirmed(ctx context.Context, c.t.Helper() - _, err := c.fsm.AskEvent(ctx, &feeBumpFanoutConfirmedEvent{ - txid: txid, + _, err := c.fsm.AskEvent(ctx, &feeBumpFanoutResolved{ + txid: txid, spender: txid, }).Await(ctx).Unpack() require.NoError(c.t, err) } @@ -3742,7 +3742,7 @@ func (c *testFeeBump) PruneParent(ctx context.Context, parent chainhash.Hash) { func newTestFeeBumpController(t *testing.T, b *CPFPBroadcaster) *testFeeBump { t.Helper() - fsm, env := newFeeBumpStateMachine(b, btclog.Disabled) + fsm, env := newFeeBumpStateMachine(b, btclog.Disabled, nil) fsm.Start(t.Context()) t.Cleanup(fsm.Stop) diff --git a/txconfirm/fee_bump_fsm_logic.go b/txconfirm/fee_bump_fsm_logic.go index 14094e324..93668f917 100644 --- a/txconfirm/fee_bump_fsm_logic.go +++ b/txconfirm/fee_bump_fsm_logic.go @@ -105,7 +105,7 @@ func (s *feeBumpStateIdle) ProcessEvent(ctx context.Context, event feeBumpEvent, return s.idleTransition(), nil // Nothing is in flight, so a late confirmation needs no action. - case *feeBumpFanoutConfirmedEvent: + case *feeBumpFanoutResolved: return &feeBumpStateTransition{ NextState: s, }, nil @@ -244,13 +244,29 @@ func (s *feeBumpStateIdle) processDemands(ctx context.Context, watchScript: watchScript, assignments: assignments, lastBroadcastHeight: height, + heightHint: height, } - err = env.broadcastFanout(ctx, pending) - if fanoutRejected(err) { - env.releasePredictedFanoutOutputs(assignments) + if env.journal != nil { + pending.journalEntry, err = encodeFeeSplit(pending) + if err != nil { + env.releasePredictedFanoutOutputs(assignments) - return s.stayIdle(env, err) + return s.stayIdle(env, err) + } + } + err = env.submitFeeSplit(ctx, pending) + if (env.journal == nil || pending.saved) && fanoutRejected(err) { + if clearErr := env.clearFeeSplit( + ctx, pending, + ); clearErr != nil { + + err = clearErr + } else { + env.releasePredictedFanoutOutputs(assignments) + + return s.stayIdle(env, err) + } } env.lastErr = err @@ -328,8 +344,8 @@ func (s *feeBumpStateFanoutPending) ProcessEvent(ctx context.Context, case *feeBumpDemandsObserved: return s.processDemands(ctx, event, env) - case *feeBumpFanoutConfirmedEvent: - return s.processConfirmed(ctx, event, env) + case *feeBumpFanoutResolved: + return s.processResolved(ctx, event, env) case *feeBumpParentEvicted: return s.processParentEvicted(ctx, event, env) @@ -350,6 +366,11 @@ func (s *feeBumpStateFanoutPending) processDemands(ctx context.Context, *feeBumpStateTransition, error) { pending := s.pending + if pending.confirmedSpender != nil { + return s.processResolved(ctx, &feeBumpFanoutResolved{ + txid: pending.txid, spender: *pending.confirmedSpender, + }, env) + } height := event.height retryInterval := event.retryInterval if retryInterval <= 0 { @@ -364,11 +385,21 @@ func (s *feeBumpStateFanoutPending) processDemands(ctx context.Context, }, nil } - err := env.broadcastFanout(ctx, pending) - if fanoutRejected(err) { + err := env.submitFeeSplit(ctx, pending) + if (env.journal == nil || pending.saved) && fanoutRejected(err) { env.log.WarnS(ctx, "Pending fee-input fanout rejected; "+ "rebuilding", err, "txid", pending.txid) + if clearErr := env.clearFeeSplit( + ctx, pending, + ); clearErr != nil { + + env.lastErr = clearErr + + //nolint:nilerr // The actor retries lastErr. + return env.refreshRebroadcast(ctx, pending, height), nil + } + return env.clearAndRebuild(ctx, pending, event), nil } @@ -377,6 +408,17 @@ func (s *feeBumpStateFanoutPending) processDemands(ctx context.Context, return env.refreshRebroadcast(ctx, pending, height), nil } +// submitFeeSplit saves the exact bytes before any call to the chain backend. +func (env *feeBumpEnvironment) submitFeeSplit(ctx context.Context, + pending *pendingFeeInputFanout) error { + + if err := env.saveFeeSplit(ctx, pending); err != nil { + return fmt.Errorf("journal fee split: %w", err) + } + + return env.broadcastFanout(ctx, pending) +} + // broadcastFanout submits the retained bytes. A malformed response or an // unknown transport result leaves the caller responsible for the same txid. func (env *feeBumpEnvironment) broadcastFanout(ctx context.Context, @@ -418,12 +460,10 @@ func fanoutRejected(err error) bool { ClassifyBroadcastFailure(err) != BroadcastFailureUnknown } -// processConfirmed promotes a confirmed fanout's predicted outputs into used -// fee inputs on each assigned parent and returns to idle. A confirmation for -// some other txid is a self-loop. On a match the actor is asked to tear down -// the watch and retry the parents that were stuck waiting on supply. -func (s *feeBumpStateFanoutPending) processConfirmed(ctx context.Context, - event *feeBumpFanoutConfirmedEvent, env *feeBumpEnvironment) ( +// processResolved clears the exact journal record before promoting confirmed +// split outputs or releasing reservations for a confirmed competing spender. +func (s *feeBumpStateFanoutPending) processResolved(ctx context.Context, + event *feeBumpFanoutResolved, env *feeBumpEnvironment) ( *feeBumpStateTransition, error) { pending := s.pending @@ -433,8 +473,26 @@ func (s *feeBumpStateFanoutPending) processConfirmed(ctx context.Context, }, nil } - env.broadcaster.fanoutInputs = nil - env.promoteConfirmedFanout(ctx, pending) + if err := env.clearFeeSplit(ctx, pending); err != nil { + env.lastErr = err + next := *pending + next.confirmedSpender = &event.spender + + //nolint:nilerr // Retry clearing the journal. + return &feeBumpStateTransition{ + NextState: &feeBumpStateFanoutPending{ + pending: &next, + }, + }, nil + } + // Only our own confirmed transaction created the predicted outputs. + // A confirmed competitor makes the split impossible on this chain. + if event.spender == pending.txid { + env.broadcaster.fanoutInputs = nil + env.promoteConfirmedFanout(ctx, pending) + } else { + env.releasePendingFanout(ctx, pending) + } // Returning to idle: tell the actor to tear down the confirmation watch // and retry every parent that was stuck waiting on the now-available @@ -483,7 +541,7 @@ func (s *feeBumpStateFanoutPending) processParentEvicted(ctx context.Context, next.assignments[parent] = outpoints } - if len(next.assignments) > 0 { + if len(next.assignments) > 0 || env.journal != nil { return &feeBumpStateTransition{ NextState: &feeBumpStateFanoutPending{ pending: &next, diff --git a/txconfirm/fee_bump_fsm_types.go b/txconfirm/fee_bump_fsm_types.go index a71d57a9c..004e4724a 100644 --- a/txconfirm/fee_bump_fsm_types.go +++ b/txconfirm/fee_bump_fsm_types.go @@ -73,6 +73,7 @@ type feeBumpOutboxEvent interface { // accounting stays consistent with the CPFP-child build path, exactly as the // old controller did. type feeBumpEnvironment struct { + journal FeeSplitJournal // transitionTimeout bounds wallet and chainsource IO while the actor // joins a transition. Tests may shorten it before the first event. transitionTimeout time.Duration @@ -143,6 +144,19 @@ type feeInputDemand struct { // broadcast and awaiting confirmation. It is the payload carried by the // fanout-pending FSM state. type pendingFeeInputFanout struct { + // journalEntry retains the exact database record for compare-and-clear. + journalEntry []byte + + // saved records whether the journal acknowledged the candidate. + saved bool + + // heightHint anchors the confirmation watch across restart. + heightHint int32 + + // confirmedSpender retains a one-shot spend or confirmation callback + // while retrying a failed journal clear. + confirmedSpender *chainhash.Hash + // txid is the fanout transaction hash used to match the confirmation // callback and the rebroadcast response. txid chainhash.Hash @@ -188,17 +202,18 @@ type feeBumpDemandsObserved struct { // feeBumpEventSealed marks feeBumpDemandsObserved as a fanout event. func (e *feeBumpDemandsObserved) feeBumpEventSealed() {} -// feeBumpFanoutConfirmedEvent is fed to the FSM when a confirmation callback is -// observed. If the txid matches the in-flight fanout, the fanout-pending state -// promotes its predicted outputs into used fee inputs and returns to idle; -// otherwise it is a no-op self-loop. -type feeBumpFanoutConfirmedEvent struct { - // txid identifies the transaction whose confirmation was observed. +// feeBumpFanoutResolved identifies the confirmed spender of a candidate +// input. A confirmation of the split itself provides the same evidence. +type feeBumpFanoutResolved struct { + // txid identifies the watched candidate, excluding stale callbacks. txid chainhash.Hash + + // spender is the confirmed transaction consuming the input. + spender chainhash.Hash } -// feeBumpEventSealed marks feeBumpFanoutConfirmedEvent as a fanout event. -func (e *feeBumpFanoutConfirmedEvent) feeBumpEventSealed() {} +// feeBumpEventSealed marks feeBumpFanoutResolved as a fanout event. +func (e *feeBumpFanoutResolved) feeBumpEventSealed() {} // feeBumpParentEvicted is fed to the FSM when a tracked parent reaches a // terminal state or is otherwise evicted. The fanout-pending state drops that @@ -267,8 +282,9 @@ func (r *feeBumpErrorReporter) ReportError(err error) { // The environment is returned alongside the machine so the actor can read back // the per-turn operational error (env.takeLastErr) that transitions stash // rather than return. -func newFeeBumpStateMachine(broadcaster *CPFPBroadcaster, - log btclog.Logger) (*feeBumpStateMachine, *feeBumpEnvironment) { +func newFeeBumpStateMachine(broadcaster *CPFPBroadcaster, log btclog.Logger, + pending *pendingFeeInputFanout) (*feeBumpStateMachine, + *feeBumpEnvironment) { env := &feeBumpEnvironment{ transitionTimeout: 30 * time.Second, @@ -276,6 +292,10 @@ func newFeeBumpStateMachine(broadcaster *CPFPBroadcaster, log: log, } + var initial feeBumpState = &feeBumpStateIdle{} + if pending != nil { + initial = &feeBumpStateFanoutPending{pending: pending} + } cfg := protofsm.StateMachineCfg[ feeBumpEvent, feeBumpOutboxEvent, *feeBumpEnvironment, ]{ @@ -283,7 +303,7 @@ func newFeeBumpStateMachine(broadcaster *CPFPBroadcaster, ErrorReporter: &feeBumpErrorReporter{ log: log, }, - InitialState: &feeBumpStateIdle{}, + InitialState: initial, Env: env, } diff --git a/txconfirm/fee_input_actor.go b/txconfirm/fee_input_actor.go index 930536266..96ed4c17f 100644 --- a/txconfirm/fee_input_actor.go +++ b/txconfirm/fee_input_actor.go @@ -112,8 +112,8 @@ func (a *TxBroadcasterActor) driveFeeBump(ctx context.Context, // the actor learns when its outputs mature into usable fee // inputs. case *feeBumpWatchFanout: - if err := a.registerFanoutConfWatch( - ctx, out.txid, out.watchScript, + if err := a.watchFeeSplit( + ctx, a.feeBumpPending(), ); err != nil { a.log.WarnS(ctx, "Unable to watch fee-input "+ @@ -122,6 +122,8 @@ func (a *TxBroadcasterActor) driveFeeBump(ctx context.Context, // The fanout confirmed or was abandoned: tear down its watch. case *feeBumpUnwatchFanout: + a.stopSplitSpendWatches(ctx, out.txid) + a.fanoutWatchActive = false if err := a.unregisterFanoutConfWatch( ctx, out.txid, out.watchScript, ); err != nil { @@ -208,8 +210,17 @@ func (a *TxBroadcasterActor) activeFeeInputDemands(ctx context.Context) ( continue } - fee, err := EstimatePackageFee( + // Split outputs and the CPFP change are wallet-managed scripts. + // Price that script family exactly as the next child builder + // does. The generic P2WPKH estimate can undersize every split + // output in a P2TR wallet. + change, err := a.broadcaster.parentChangePkScript(ctx, txid) + if err != nil { + return nil, 0, err + } + fee, err := computePackageFee( entry.data.Tx, btcutil.Amount(feeRate), + estimateChildVSize(change, change), ) if err != nil { return nil, 0, err @@ -230,7 +241,7 @@ func (a *TxBroadcasterActor) activeFeeInputDemands(ctx context.Context) ( // into handleFanoutConfirmed. The watch is keyed by both txid and pkScript so // it round-trips symmetrically with unregisterFanoutConfWatch. func (a *TxBroadcasterActor) registerFanoutConfWatch(ctx context.Context, - txid chainhash.Hash, watchScript []byte) error { + txid chainhash.Hash, watchScript []byte, heightHint uint32) error { if len(watchScript) == 0 { return nil @@ -251,6 +262,7 @@ func (a *TxBroadcasterActor) registerFanoutConfWatch(ctx context.Context, _, err := a.cfg.ChainSource.Ask( ctx, &chainsource.RegisterConfRequest{ CallerID: a.fanoutConfCallerID(txid), + HeightHint: heightHint, Txid: &txid, PkScript: watchScript, TargetConfs: 1, @@ -303,8 +315,15 @@ func (a *TxBroadcasterActor) handleFanoutConfirmed(ctx context.Context, return false } - a.driveFeeBump(ctx, &feeBumpFanoutConfirmedEvent{ - txid: msg.txid, + // Restored assignments can outlive a job which finished while the + // daemon was offline. Only live parents keep the confirmed output. + for parent := range pending.assignments { + if _, live := a.tracked[parent]; !live { + delete(a.broadcaster.parentStates, parent) + } + } + a.driveFeeBump(ctx, &feeBumpFanoutResolved{ + txid: msg.txid, spender: msg.txid, }) return true diff --git a/txconfirm/fee_split_journal.go b/txconfirm/fee_split_journal.go new file mode 100644 index 000000000..f12c118ef --- /dev/null +++ b/txconfirm/fee_split_journal.go @@ -0,0 +1,335 @@ +package txconfirm + +import ( + "bytes" + "context" + "encoding/binary" + "errors" + "fmt" + "io" + "time" + + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/baselib/actor" + "github.com/lightninglabs/wavelength/chainsource" + fn "github.com/lightningnetwork/lnd/fn/v2" +) + +// FeeSplitJournal stores the single signed fee split for this wallet. Writes +// must commit independently of the caller's RPC or actor transaction. +type FeeSplitJournal interface { + // SaveWalletFeeSplit accepts identical bytes or an empty slot. A zero + // row count means a different candidate owns the slot. + SaveWalletFeeSplit(context.Context, []byte) (int64, error) + + // ClearWalletFeeSplit deletes only the exact candidate supplied. + ClearWalletFeeSplit(context.Context, []byte) error +} + +// encodeFeeSplit stores a height hint and the full signed transaction. On +// recovery wallet enumeration supplies confirmed outputs to the live parents. +func encodeFeeSplit(pending *pendingFeeInputFanout) ([]byte, error) { + var buf bytes.Buffer + if err := binary.Write( + &buf, binary.BigEndian, pending.heightHint, + ); err != nil { + return nil, err + } + if err := pending.tx.Serialize(&buf); err != nil { + return nil, err + } + + // One owner slot per signed output preserves the assignment even if + // wallet synchronization delivers the split before its watch fires. + owners := make([]chainhash.Hash, len(pending.tx.TxOut)) + for parent, outputs := range pending.assignments { + for _, op := range outputs { + owners[op.Index] = parent + } + } + for _, parent := range owners { + buf.Write(parent[:]) + } + + return buf.Bytes(), nil +} + +// restoreFeeSplit returns a candidate with its original input exclusion and +// watch script. No output becomes eligible based on the journal alone. +func restoreFeeSplit(raw []byte) (*pendingFeeInputFanout, error) { + reader := bytes.NewReader(raw) + var height int32 + if err := binary.Read(reader, binary.BigEndian, &height); err != nil { + return nil, err + } + + var tx wire.MsgTx + if err := tx.Deserialize(reader); err != nil { + return nil, err + } + + // The record carries one owner slot per output, including change. + if reader.Len() != len(tx.TxOut)*chainhash.HashSize || + height < 0 || len(tx.TxOut) == 0 || len(tx.TxIn) == 0 || + len(tx.TxOut[0].PkScript) == 0 { + return nil, fmt.Errorf("invalid stored fee split") + } + + // Restore ownership by output index so identical amounts keep their + // original parents when the transaction is replayed. + assignments := make(map[chainhash.Hash][]wire.OutPoint) + id := tx.TxHash() + for index := range tx.TxOut { + var owner chainhash.Hash + if _, err := io.ReadFull(reader, owner[:]); err != nil { + return nil, err + } + if owner != (chainhash.Hash{}) { + op := wire.OutPoint{Hash: id, Index: uint32(index)} + assignments[owner] = append(assignments[owner], op) + } + } + + return &pendingFeeInputFanout{ + assignments: assignments, + txid: id, + tx: &tx, + watchScript: tx.TxOut[0].PkScript, + heightHint: height, + journalEntry: raw, + saved: true, + }, nil +} + +// RestoreFeeSplit installs the durable candidate before registering the actor. +// The caller sends ResumeFeeSplit once chainsource can deliver callbacks. +func (a *TxBroadcasterActor) RestoreFeeSplit(raw []byte) error { + pending, err := restoreFeeSplit(raw) + if err != nil { + return err + } + + // Reserve the original inputs before new submissions reach the actor. + a.feeBumpFSM, a.feeBumpEnv = newFeeBumpStateMachine( + a.broadcaster, a.log, pending, + ) + a.feeBumpEnv.journal = a.cfg.FeeSplitJournal + a.broadcaster.fanoutInputs = pending.tx.TxIn + + // Restored assignments remain predictions until the watch confirms. + for parent, ops := range pending.assignments { + state := a.broadcaster.parentState(parent) + for _, op := range ops { + out := pending.tx.TxOut[op.Index] + state.PredictedFeeInputs[op] = &FeeInput{ + Outpoint: op, + Output: cloneTxOut(out), + } + } + } + + return nil +} + +// ResumeFeeSplit reattaches the chain subscriptions for a restored candidate. +type ResumeFeeSplit struct { + // BaseMessage supplies the actor envelope for the startup request. + actor.BaseMessage +} + +// MessageType identifies the startup recovery request. +func (*ResumeFeeSplit) MessageType() string { + return "ResumeFeeSplit" +} + +// txConfirmMsgSealed restricts the recovery request to this package. +func (*ResumeFeeSplit) txConfirmMsgSealed() {} + +// resumeFeeSplit subscribes before rebroadcast. A later block retries a lost +// receipt or watch registration independently of the restored exit jobs. +func (a *TxBroadcasterActor) resumeFeeSplit(ctx context.Context) error { + a.ensureFeeBumpStarted(ctx) + if err := a.ensureBlockSubscription(ctx); err != nil { + return err + } + pending := a.feeBumpPending() + if pending == nil { + return nil + } + + if err := a.watchFeeSplit(ctx, pending); err != nil { + a.log.WarnS(ctx, "Retrying fee split watch on next block", err) + } + + return nil +} + +// watchFeeSplit uses the original funding height to catch confirmation while +// the daemon was offline. An unsuccessful registration is retried on a block. +func (a *TxBroadcasterActor) watchFeeSplit(ctx context.Context, + pending *pendingFeeInputFanout) error { + + var registrationErr error + if !a.fanoutWatchActive { + registrationErr = a.registerFanoutConfWatch( + ctx, pending.txid, pending.watchScript, + uint32(pending.heightHint), + ) + a.fanoutWatchActive = registrationErr == nil + } + + if a.cfg.FeeSplitInputScript == nil { + return registrationErr + } + + // Each input can invalidate the split independently. Keep successful + // watches while retrying individual lookup or registration failures. + if a.splitSpendWatches == nil { + a.splitSpendWatches = make(map[wire.OutPoint][]byte) + } + for _, input := range pending.tx.TxIn { + op := input.PreviousOutPoint + if _, ok := a.splitSpendWatches[op]; ok { + continue + } + + script, err := a.cfg.FeeSplitInputScript(ctx, op) + if err != nil { + registrationErr = errors.Join(registrationErr, err) + + continue + } + + a.splitSpendWatches[op] = script + a.registerSplitSpend(ctx, pending, op, script) + } + + return registrationErr +} + +// splitSpendObserved carries a confirmed spender from a watch registered for +// a particular candidate. Messages for a replaced candidate are ignored. +type splitSpendObserved struct { + // BaseMessage supplies the actor envelope. + actor.BaseMessage + + candidate chainhash.Hash + spender chainhash.Hash + height int32 +} + +// MessageType identifies the spend callback to the actor runtime. +func (*splitSpendObserved) MessageType() string { return "splitSpendObserved" } + +// txConfirmMsgSealed restricts the callback to the broadcaster. +func (*splitSpendObserved) txConfirmMsgSealed() {} + +// splitWatchResult carries the registration receipt for one input. A failed +// registration becomes eligible for retry on the next block. +type splitWatchResult struct { + // BaseMessage supplies the actor envelope. + actor.BaseMessage + + candidate chainhash.Hash + input wire.OutPoint + err error +} + +// MessageType identifies the registration receipt. +func (*splitWatchResult) MessageType() string { return "splitWatchResult" } + +// txConfirmMsgSealed restricts the receipt to the broadcaster. +func (*splitWatchResult) txConfirmMsgSealed() {} + +// splitWatchTimeout bounds the asynchronous chainsource registration. +const splitWatchTimeout = 30 * time.Second + +// registerSplitSpend watches a candidate input starting at the original +// funding height so a spend mined during downtime is replayed. +func (a *TxBroadcasterActor) registerSplitSpend(ctx context.Context, + pending *pendingFeeInputFanout, op wire.OutPoint, script []byte) { + + id := pending.txid + ref := chainsource.MapSpendEvent( + a.selfRef, + func(event chainsource.SpendEvent) Msg { + return &splitSpendObserved{ + candidate: id, + spender: event.SpendingTxid, + height: event.SpendingHeight, + } + }, + ) + + var req chainsource.ChainSourceMsg = &chainsource.RegisterSpendRequest{ + CallerID: a.fanoutConfCallerID(id), + Outpoint: &op, + PkScript: script, + HeightHint: uint32(pending.heightHint), + NotifyActor: fn.Some(ref), + } + actor.AskThen( + ctx, a.cfg.ChainSource, req, a.selfRef, splitWatchTimeout, + func(result fn.Result[chainsource.ChainSourceResp]) Msg { + return &splitWatchResult{ + candidate: id, + input: op, + err: result.Err(), + } + }, + ) +} + +// stopSplitSpendWatches releases the input subscriptions for the resolved +// split. +func (a *TxBroadcasterActor) stopSplitSpendWatches(ctx context.Context, + id chainhash.Hash) { + + for op, script := range a.splitSpendWatches { + req := &chainsource.UnregisterSpendRequest{ + CallerID: a.fanoutConfCallerID(id), + Outpoint: &op, + PkScript: script, + } + if err := a.cfg.ChainSource.Tell(ctx, req); err != nil { + a.log.WarnS(ctx, "Unregister split input spend", err, + "outpoint", op) + } + } + clear(a.splitSpendWatches) +} + +// saveFeeSplit commits a candidate before its first publish. Retrying the +// exact record also reconciles a committed write whose receipt was lost. +func (env *feeBumpEnvironment) saveFeeSplit(ctx context.Context, + pending *pendingFeeInputFanout) error { + + if env.journal == nil || pending.saved { + return nil + } + + count, err := env.journal.SaveWalletFeeSplit(ctx, pending.journalEntry) + if err != nil { + return err + } + if count != 1 { + return fmt.Errorf("another signed split owns the wallet " + + "journal") + } + + pending.saved = true + + return nil +} + +// clearFeeSplit forgets only the candidate that has resolved. +func (env *feeBumpEnvironment) clearFeeSplit(ctx context.Context, + pending *pendingFeeInputFanout) error { + + if env.journal == nil { + return nil + } + + return env.journal.ClearWalletFeeSplit(ctx, pending.journalEntry) +} diff --git a/txconfirm/fee_split_journal_test.go b/txconfirm/fee_split_journal_test.go new file mode 100644 index 000000000..30bd1df35 --- /dev/null +++ b/txconfirm/fee_split_journal_test.go @@ -0,0 +1,187 @@ +package txconfirm + +import ( + "bytes" + "context" + "testing" + + "github.com/btcsuite/btcd/chainhash/v2" + "github.com/lightninglabs/wavelength/walletcore" + "github.com/stretchr/testify/require" +) + +// faultSplitJournal injects a lost write receipt and a transient failure +// clearing the record after confirmation. +type faultSplitJournal struct { + record []byte + loseSaveReceipt bool + failClear bool +} + +// SaveWalletFeeSplit can commit the record but lose its response. +func (j *faultSplitJournal) SaveWalletFeeSplit(ctx context.Context, + candidate []byte) (int64, error) { + + if j.record != nil && !bytes.Equal(candidate, j.record) { + return 0, nil + } + j.record = bytes.Clone(candidate) + if j.loseSaveReceipt { + j.loseSaveReceipt = false + + return 0, context.DeadlineExceeded + } + + return 1, nil +} + +// ClearWalletFeeSplit can fail before deleting the record. +func (j *faultSplitJournal) ClearWalletFeeSplit(ctx context.Context, + candidate []byte) error { + + if j.failClear { + j.failClear = false + + return context.DeadlineExceeded + } + if bytes.Equal(candidate, j.record) { + j.record = nil + } + + return nil +} + +// TestFeeSplitJournalRestart proves that a committed candidate survives lost +// receipts, new wallet supply, and a restart before confirmation. +func TestFeeSplitJournalRestart(t *testing.T) { + t.Parallel() + + t.Run("split confirmed", func(t *testing.T) { + testFeeSplitJournalResolution(t, false) + }) + t.Run("competing spender confirmed", func(t *testing.T) { + testFeeSplitJournalResolution(t, true) + }) +} + +// testFeeSplitJournalResolution restores an ambiguous split and fails its +// first journal clear. Only the winning transaction may supply fee outputs. +func testFeeSplitJournalResolution(t *testing.T, competitor bool) { + t.Helper() + + ctx := t.Context() + journal := &faultSplitJournal{loseSaveReceipt: true} + chain := newFakeChainSourceRef(100) + wallet := &allocatingWallet{fakeWallet: &fakeWallet{ + utxos: []*walletcore.Utxo{ + makeWalletUTXOWithAmount(100_000, 7), + }, + }} + demands := []feeInputDemand{ + { + parentTxid: chainhash.Hash{ + 1, + }, + minAmount: 10_000, + }, + { + parentTxid: chainhash.Hash{ + 2, + }, + minAmount: 10_000, + }, + } + first := newTestFeeBumpController( + t, + NewCPFPBroadcaster( + BroadcasterConfig{ + ChainSource: chain, + Wallet: wallet, + }, + ), + ) + first.env.journal = journal + _, err := first.EnsureSupply(ctx, demands, 5, 100, 1) + require.ErrorIs(t, err, context.DeadlineExceeded) + require.Empty(t, chain.broadcastCalls) + + raw := bytes.Clone(journal.record) + require.NotEmpty(t, raw) + + chain.broadcastErr = context.DeadlineExceeded + _, err = first.EnsureSupply(ctx, demands, 5, 101, 1) + require.ErrorIs(t, err, context.DeadlineExceeded) + require.Len(t, chain.broadcastCalls, 1) + signed := chain.broadcastCalls[0].Tx.Copy() + + // Start another actor with only the database and fresh wallet supply. + wallet.utxos = []*walletcore.Utxo{makeWalletUTXOWithAmount(100_000, 8)} + actor := NewTxBroadcasterActor( + Config{ + ChainSource: chain, + Wallet: wallet, + FeeSplitJournal: journal, + }, + ) + require.NoError(t, actor.RestoreFeeSplit(raw)) + actor.ensureFeeBumpStarted(ctx) + t.Cleanup(actor.feeBumpFSM.Stop) + restored := &testFeeBump{ + t: t, + fsm: actor.feeBumpFSM, + env: actor.feeBumpEnv, + } + pending := restored.PendingFanout() + require.Equal(t, first.PendingFanout().assignments, pending.assignments) + require.Equal(t, int32(100), pending.heightHint) + require.Equal(t, signed.TxHash(), pending.txid) + chain.broadcastErr = nil + _, err = restored.EnsureSupply(ctx, demands, 5, 102, 1) + require.NoError(t, err) + require.Len(t, chain.broadcastCalls, 2) + var before, after bytes.Buffer + require.NoError(t, signed.Serialize(&before)) + require.NoError(t, chain.broadcastCalls[1].Tx.Serialize(&after)) + require.Equal(t, before.Bytes(), after.Bytes()) + require.Len(t, wallet.fundedTemplates, 1) + + // A delayed callback from an older split cannot release this one. + _, err = restored.fsm.AskEvent(ctx, &feeBumpFanoutResolved{ + txid: chainhash.Hash{8}, spender: chainhash.Hash{9}, + }).Await(ctx).Unpack() + require.NoError(t, err) + require.Equal(t, raw, journal.record) + + journal.failClear = true + spender := signed.TxHash() + if competitor { + spender = chainhash.Hash{22} + } + _, err = restored.fsm.AskEvent(ctx, &feeBumpFanoutResolved{ + txid: signed.TxHash(), spender: spender, + }).Await(ctx).Unpack() + require.NoError(t, err) + require.ErrorIs(t, restored.env.takeLastErr(), context.DeadlineExceeded) + require.NotNil(t, restored.PendingFanout()) + _, err = restored.EnsureSupply(ctx, nil, 5, 103, 1) + require.NoError(t, err) + require.Nil(t, restored.PendingFanout()) + require.Len(t, chain.broadcastCalls, 2) + require.Empty(t, journal.record) + + if competitor { + // A real conflict invalidates every predicted output. The + // next demand must be able to use the fresh wallet coin. + for parent := range pending.assignments { + state := restored.env.broadcaster.parentState(parent) + require.Empty(t, state.UsedFeeInputs) + require.Empty(t, state.PredictedFeeInputs) + } + replacement, err := restored.EnsureSupply( + ctx, demands, 5, 104, 1, + ) + require.NoError(t, err) + require.NotNil(t, replacement) + require.NotEqual(t, signed.TxHash(), replacement.txid) + } +} diff --git a/waved/server.go b/waved/server.go index ba201cfa0..69c3e23c0 100644 --- a/waved/server.go +++ b/waved/server.go @@ -5,6 +5,7 @@ import ( "context" "crypto/tls" "crypto/x509" + "database/sql" "encoding/hex" "errors" "fmt" @@ -6323,6 +6324,26 @@ func leaseFundedInputs(ctx context.Context, leaser walletcore.OutputLeaser, return nil } +// feeSplitInputScript looks up the funding script in wallet history even +// after a competing spend has removed the input from ListUnspent. +func feeSplitInputScript( + backend wallet.BoardingBackend, +) func(context.Context, wire.OutPoint) ([]byte, error) { + + return func(ctx context.Context, op wire.OutPoint) ([]byte, error) { + info, err := backend.GetTransaction(ctx, op.Hash) + if err != nil { + return nil, err + } + if info == nil || info.Tx == nil || + uint64(op.Index) >= uint64(len(info.Tx.TxOut)) { + return nil, fmt.Errorf("missing fee split input %s", op) + } + + return info.Tx.TxOut[op.Index].PkScript, nil + } +} + // initUnrollSubsystem registers shared tx confirmation, the unroll registry, // and recovery services before mailbox ingress. Durable replay and the VTXO // expiry handoff wait until ingress can answer authenticated material lookups. @@ -6346,6 +6367,7 @@ func (s *Server) initUnrollSubsystem(ctx context.Context, // Build the wallet adapter shared by txconfirm and unroll // sweep signing. + var splitBackend wallet.BoardingBackend var unrollWallet interface { txconfirm.Wallet unroll.SweepWallet @@ -6369,6 +6391,7 @@ func (s *Server) initUnrollSubsystem(ctx context.Context, scripts: s.ownedWalletScripts(), } unrollWallet = w + splitBackend = boardingBackend case WalletTypeLwwallet: lww := s.lwWallet.UnsafeFromSome() @@ -6377,6 +6400,7 @@ func (s *Server) initUnrollSubsystem(ctx context.Context, scripts: s.ownedWalletScripts(), } unrollWallet = w + splitBackend = lww.BoardingBackend() case WalletTypeBtcwallet: btcw := s.btcwWallet.UnsafeFromSome() @@ -6385,22 +6409,42 @@ func (s *Server) initUnrollSubsystem(ctx context.Context, scripts: s.ownedWalletScripts(), } unrollWallet = w + splitBackend = btcw.BoardingBackend() } // 1. Create and register the shared tx confirmation actor. + split, err := dbStore.Queries().LoadWalletFeeSplit(ctx) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return fmt.Errorf("load wallet fee split: %w", err) + } txConfirm := txconfirm.NewTxBroadcasterActor(txconfirm.Config{ + FeeSplitJournal: dbStore.Queries(), + FeeSplitInputScript: feeSplitInputScript(splitBackend), ChainSource: chainSourceRef, Wallet: unrollWallet, Log: fn.Some(s.subLogger("TXCF")), MaxFeeRateSatPerVByte: s.unrollMaxFeeRate(), FeeBumpIntervalBlocks: s.unrollBumpAfterBlocks(), }) + if len(split) > 0 { + if err := txConfirm.RestoreFeeSplit(split); err != nil { + return fmt.Errorf("restore wallet fee split: %w", err) + } + } txConfirmKey := txconfirm.NewServiceKey() txConfirmRef := actor.RegisterWithSystem( s.actorSystem, txconfirm.ServiceKeyName, txConfirmKey, txConfirm, ) txConfirm.SetSelfRef(txConfirmRef) + if len(split) > 0 { + if _, err := txConfirmRef. + Ask(ctx, &txconfirm.ResumeFeeSplit{}). + Await(ctx). + Unpack(); err != nil { + return fmt.Errorf("resume wallet fee split: %w", err) + } + } // The unroll children use this ref to submit proof/sweep txs. In tests // it may be wrapped to reject broadcasts pre-mempool so the diff --git a/waved/wallet_sign_itest.go b/waved/wallet_sign_itest.go new file mode 100644 index 000000000..c2e7d47f9 --- /dev/null +++ b/waved/wallet_sign_itest.go @@ -0,0 +1,28 @@ +//go:build itest + +package waved + +import ( + "context" + "fmt" + + "github.com/btcsuite/btcd/wire/v2" + "github.com/lightninglabs/wavelength/wallet" +) + +// FinalizeTestWalletPSBT lets an integration harness retain a valid competing +// spend before the fee broadcaster leases its inputs. It never publishes it. +func (s *Server) FinalizeTestWalletPSBT(ctx context.Context, packet []byte) ( + *wire.MsgTx, error) { + + signer, err := s.newSweepWallet() + if err != nil { + return nil, err + } + sweeper, ok := signer.(wallet.WalletBackingSweeper) + if !ok { + return nil, fmt.Errorf("wallet cannot finalize test PSBT") + } + + return sweeper.FinalizePsbt(ctx, packet) +}