• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lightningnetwork / lnd / 17830307614

18 Sep 2025 01:29PM UTC coverage: 54.617% (-12.0%) from 66.637%
17830307614

Pull #10200

github

web-flow
Merge 181a0a7bc into b34fc964b
Pull Request #10200: github: change to form-based issue template

109249 of 200028 relevant lines covered (54.62%)

21896.43 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

49.12
/sweep/sweeper.go
1
package sweep
2

3
import (
4
        "errors"
5
        "fmt"
6
        "sync"
7
        "sync/atomic"
8

9
        "github.com/btcsuite/btcd/btcutil"
10
        "github.com/btcsuite/btcd/chaincfg/chainhash"
11
        "github.com/btcsuite/btcd/wire"
12
        "github.com/lightningnetwork/lnd/chainio"
13
        "github.com/lightningnetwork/lnd/chainntnfs"
14
        "github.com/lightningnetwork/lnd/fn/v2"
15
        "github.com/lightningnetwork/lnd/input"
16
        "github.com/lightningnetwork/lnd/lnutils"
17
        "github.com/lightningnetwork/lnd/lnwallet"
18
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
19
)
20

21
var (
22
        // ErrRemoteSpend is returned in case an output that we try to sweep is
23
        // confirmed in a tx of the remote party.
24
        ErrRemoteSpend = errors.New("remote party swept utxo")
25

26
        // ErrFeePreferenceTooLow is returned when the fee preference gives a
27
        // fee rate that's below the relay fee rate.
28
        ErrFeePreferenceTooLow = errors.New("fee preference too low")
29

30
        // ErrExclusiveGroupSpend is returned in case a different input of the
31
        // same exclusive group was spent.
32
        ErrExclusiveGroupSpend = errors.New("other member of exclusive group " +
33
                "was spent")
34

35
        // ErrSweeperShuttingDown is an error returned when a client attempts to
36
        // make a request to the UtxoSweeper, but it is unable to handle it as
37
        // it is/has already been stopped.
38
        ErrSweeperShuttingDown = errors.New("utxo sweeper shutting down")
39

40
        // DefaultDeadlineDelta defines a default deadline delta (1 week) to be
41
        // used when sweeping inputs with no deadline pressure.
42
        DefaultDeadlineDelta = int32(1008)
43
)
44

45
// Params contains the parameters that control the sweeping process.
46
type Params struct {
47
        // ExclusiveGroup is an identifier that, if set, ensures this input is
48
        // swept in a transaction by itself, and not batched with any other
49
        // inputs.
50
        ExclusiveGroup *uint64
51

52
        // DeadlineHeight specifies an absolute block height that this input
53
        // should be confirmed by. This value is used by the fee bumper to
54
        // decide its urgency and adjust its feerate used.
55
        DeadlineHeight fn.Option[int32]
56

57
        // Budget specifies the maximum amount of satoshis that can be spent on
58
        // fees for this sweep.
59
        Budget btcutil.Amount
60

61
        // Immediate indicates that the input should be swept immediately
62
        // without waiting for blocks to come to trigger the sweeping of
63
        // inputs.
64
        Immediate bool
65

66
        // StartingFeeRate is an optional parameter that can be used to specify
67
        // the initial fee rate to use for the fee function.
68
        StartingFeeRate fn.Option[chainfee.SatPerKWeight]
69
}
70

71
// String returns a human readable interpretation of the sweep parameters.
72
func (p Params) String() string {
×
73
        deadline := "none"
×
74
        p.DeadlineHeight.WhenSome(func(d int32) {
×
75
                deadline = fmt.Sprintf("%d", d)
×
76
        })
×
77

78
        exclusiveGroup := "none"
×
79
        if p.ExclusiveGroup != nil {
×
80
                exclusiveGroup = fmt.Sprintf("%d", *p.ExclusiveGroup)
×
81
        }
×
82

83
        return fmt.Sprintf("startingFeeRate=%v, immediate=%v, "+
×
84
                "exclusive_group=%v, budget=%v, deadline=%v", p.StartingFeeRate,
×
85
                p.Immediate, exclusiveGroup, p.Budget, deadline)
×
86
}
87

88
// SweepState represents the current state of a pending input.
89
//
90
//nolint:revive
91
type SweepState uint8
92

93
const (
94
        // Init is the initial state of a pending input. This is set when a new
95
        // sweeping request for a given input is made.
96
        Init SweepState = iota
97

98
        // PendingPublish specifies an input's state where it's already been
99
        // included in a sweeping tx but the tx is not published yet.  Inputs
100
        // in this state should not be used for grouping again.
101
        PendingPublish
102

103
        // Published is the state where the input's sweeping tx has
104
        // successfully been published. Inputs in this state can only be
105
        // updated via RBF.
106
        Published
107

108
        // PublishFailed is the state when an error is returned from publishing
109
        // the sweeping tx. Inputs in this state can be re-grouped in to a new
110
        // sweeping tx.
111
        PublishFailed
112

113
        // Swept is the final state of a pending input. This is set when the
114
        // input has been successfully swept.
115
        Swept
116

117
        // Excluded is the state of a pending input that has been excluded and
118
        // can no longer be swept. For instance, when one of the three anchor
119
        // sweeping transactions confirmed, the remaining two will be excluded.
120
        Excluded
121

122
        // Fatal is the final state of a pending input. Inputs ending in this
123
        // state won't be retried. This could happen,
124
        // - when a pending input has too many failed publish attempts;
125
        // - the input has been spent by another party;
126
        // - unknown broadcast error is returned.
127
        Fatal
128
)
129

130
// String gives a human readable text for the sweep states.
131
func (s SweepState) String() string {
×
132
        switch s {
×
133
        case Init:
×
134
                return "Init"
×
135

136
        case PendingPublish:
×
137
                return "PendingPublish"
×
138

139
        case Published:
×
140
                return "Published"
×
141

142
        case PublishFailed:
×
143
                return "PublishFailed"
×
144

145
        case Swept:
×
146
                return "Swept"
×
147

148
        case Excluded:
×
149
                return "Excluded"
×
150

151
        case Fatal:
×
152
                return "Fatal"
×
153

154
        default:
×
155
                return "Unknown"
×
156
        }
157
}
158

159
// RBFInfo stores the information required to perform a RBF bump on a pending
160
// sweeping tx.
161
type RBFInfo struct {
162
        // Txid is the txid of the sweeping tx.
163
        Txid chainhash.Hash
164

165
        // FeeRate is the fee rate of the sweeping tx.
166
        FeeRate chainfee.SatPerKWeight
167

168
        // Fee is the total fee of the sweeping tx.
169
        Fee btcutil.Amount
170
}
171

172
// SweeperInput is created when an input reaches the main loop for the first
173
// time. It wraps the input and tracks all relevant state that is needed for
174
// sweeping.
175
type SweeperInput struct {
176
        input.Input
177

178
        // state tracks the current state of the input.
179
        state SweepState
180

181
        // listeners is a list of channels over which the final outcome of the
182
        // sweep needs to be broadcasted.
183
        listeners []chan Result
184

185
        // ntfnRegCancel is populated with a function that cancels the chain
186
        // notifier spend registration.
187
        ntfnRegCancel func()
188

189
        // publishAttempts records the number of attempts that have already been
190
        // made to sweep this tx.
191
        publishAttempts int
192

193
        // params contains the parameters that control the sweeping process.
194
        params Params
195

196
        // lastFeeRate is the most recent fee rate used for this input within a
197
        // transaction broadcast to the network.
198
        lastFeeRate chainfee.SatPerKWeight
199

200
        // rbf records the RBF constraints.
201
        rbf fn.Option[RBFInfo]
202

203
        // DeadlineHeight is the deadline height for this input. This is
204
        // different from the DeadlineHeight in its params as it's an actual
205
        // value than an option.
206
        DeadlineHeight int32
207
}
208

209
// String returns a human readable interpretation of the pending input.
210
func (p *SweeperInput) String() string {
28✔
211
        return fmt.Sprintf("%v (%v)", p.Input.OutPoint(), p.Input.WitnessType())
28✔
212
}
28✔
213

214
// terminated returns a boolean indicating whether the input has reached a
215
// final state.
216
func (p *SweeperInput) terminated() bool {
24✔
217
        switch p.state {
24✔
218
        // If the input has reached a final state, that it's either
219
        // been swept, or failed, or excluded, we will remove it from
220
        // our sweeper.
221
        case Fatal, Swept, Excluded:
9✔
222
                return true
9✔
223

224
        default:
15✔
225
                return false
15✔
226
        }
227
}
228

229
// isMature returns a boolean indicating whether the input has a timelock that
230
// has been reached or not. The locktime found is also returned.
231
func (p *SweeperInput) isMature(currentHeight uint32) (bool, uint32) {
5✔
232
        locktime, _ := p.RequiredLockTime()
5✔
233
        if currentHeight < locktime {
6✔
234
                log.Debugf("Input %v has locktime=%v, current height is %v",
1✔
235
                        p, locktime, currentHeight)
1✔
236

1✔
237
                return false, locktime
1✔
238
        }
1✔
239

240
        // If the input has a CSV that's not yet reached, we will skip
241
        // this input and wait for the expiry.
242
        //
243
        // NOTE: We need to consider whether this input can be included in the
244
        // next block or not, which means the CSV will be checked against the
245
        // currentHeight plus one.
246
        locktime = p.BlocksToMaturity() + p.HeightHint()
4✔
247
        if currentHeight+1 < locktime {
5✔
248
                log.Debugf("Input %v has CSV expiry=%v, current height is %v, "+
1✔
249
                        "skipped sweeping", p, locktime, currentHeight)
1✔
250

1✔
251
                return false, locktime
1✔
252
        }
1✔
253

254
        return true, locktime
3✔
255
}
256

257
// InputsMap is a type alias for a set of pending inputs.
258
type InputsMap = map[wire.OutPoint]*SweeperInput
259

260
// inputsMapToString returns a human readable interpretation of the pending
261
// inputs.
262
func inputsMapToString(inputs InputsMap) string {
×
263
        if len(inputs) == 0 {
×
264
                return ""
×
265
        }
×
266

267
        inps := make([]input.Input, 0, len(inputs))
×
268
        for _, in := range inputs {
×
269
                inps = append(inps, in)
×
270
        }
×
271

272
        return "\n" + inputTypeSummary(inps)
×
273
}
274

275
// pendingSweepsReq is an internal message we'll use to represent an external
276
// caller's intent to retrieve all of the pending inputs the UtxoSweeper is
277
// attempting to sweep.
278
type pendingSweepsReq struct {
279
        respChan chan map[wire.OutPoint]*PendingInputResponse
280
        errChan  chan error
281
}
282

283
// PendingInputResponse contains information about an input that is currently
284
// being swept by the UtxoSweeper.
285
type PendingInputResponse struct {
286
        // OutPoint is the identify outpoint of the input being swept.
287
        OutPoint wire.OutPoint
288

289
        // WitnessType is the witness type of the input being swept.
290
        WitnessType input.WitnessType
291

292
        // Amount is the amount of the input being swept.
293
        Amount btcutil.Amount
294

295
        // LastFeeRate is the most recent fee rate used for the input being
296
        // swept within a transaction broadcast to the network.
297
        LastFeeRate chainfee.SatPerKWeight
298

299
        // BroadcastAttempts is the number of attempts we've made to sweept the
300
        // input.
301
        BroadcastAttempts int
302

303
        // Params contains the sweep parameters for this pending request.
304
        Params Params
305

306
        // DeadlineHeight records the deadline height of this input.
307
        DeadlineHeight uint32
308

309
        // MaturityHeight is the block height that this input's locktime will
310
        // be expired at. For inputs with no locktime this value is zero.
311
        MaturityHeight uint32
312
}
313

314
// updateReq is an internal message we'll use to represent an external caller's
315
// intent to update the sweep parameters of a given input.
316
type updateReq struct {
317
        input        wire.OutPoint
318
        params       Params
319
        responseChan chan *updateResp
320
}
321

322
// updateResp is an internal message we'll use to hand off the response of a
323
// updateReq from the UtxoSweeper's main event loop back to the caller.
324
type updateResp struct {
325
        resultChan chan Result
326
        err        error
327
}
328

329
// UtxoSweeper is responsible for sweeping outputs back into the wallet
330
type UtxoSweeper struct {
331
        started uint32 // To be used atomically.
332
        stopped uint32 // To be used atomically.
333

334
        // Embed the blockbeat consumer struct to get access to the method
335
        // `NotifyBlockProcessed` and the `BlockbeatChan`.
336
        chainio.BeatConsumer
337

338
        cfg *UtxoSweeperConfig
339

340
        newInputs chan *sweepInputMessage
341
        spendChan chan *chainntnfs.SpendDetail
342

343
        // pendingSweepsReq is a channel that will be sent requests by external
344
        // callers in order to retrieve the set of pending inputs the
345
        // UtxoSweeper is attempting to sweep.
346
        pendingSweepsReqs chan *pendingSweepsReq
347

348
        // updateReqs is a channel that will be sent requests by external
349
        // callers who wish to bump the fee rate of a given input.
350
        updateReqs chan *updateReq
351

352
        // inputs is the total set of inputs the UtxoSweeper has been requested
353
        // to sweep.
354
        inputs InputsMap
355

356
        currentOutputScript fn.Option[lnwallet.AddrWithKey]
357

358
        relayFeeRate chainfee.SatPerKWeight
359

360
        quit chan struct{}
361
        wg   sync.WaitGroup
362

363
        // currentHeight is the best known height of the main chain. This is
364
        // updated whenever a new block epoch is received.
365
        currentHeight int32
366

367
        // bumpRespChan is a channel that receives broadcast results from the
368
        // TxPublisher.
369
        bumpRespChan chan *bumpResp
370
}
371

372
// Compile-time check for the chainio.Consumer interface.
373
var _ chainio.Consumer = (*UtxoSweeper)(nil)
374

375
// UtxoSweeperConfig contains dependencies of UtxoSweeper.
376
type UtxoSweeperConfig struct {
377
        // GenSweepScript generates a P2WKH script belonging to the wallet where
378
        // funds can be swept.
379
        GenSweepScript func() fn.Result[lnwallet.AddrWithKey]
380

381
        // FeeEstimator is used when crafting sweep transactions to estimate
382
        // the necessary fee relative to the expected size of the sweep
383
        // transaction.
384
        FeeEstimator chainfee.Estimator
385

386
        // Wallet contains the wallet functions that sweeper requires.
387
        Wallet Wallet
388

389
        // Notifier is an instance of a chain notifier we'll use to watch for
390
        // certain on-chain events.
391
        Notifier chainntnfs.ChainNotifier
392

393
        // Mempool is the mempool watcher that will be used to query whether a
394
        // given input is already being spent by a transaction in the mempool.
395
        Mempool chainntnfs.MempoolWatcher
396

397
        // Store stores the published sweeper txes.
398
        Store SweeperStore
399

400
        // Signer is used by the sweeper to generate valid witnesses at the
401
        // time the incubated outputs need to be spent.
402
        Signer input.Signer
403

404
        // MaxInputsPerTx specifies the default maximum number of inputs allowed
405
        // in a single sweep tx. If more need to be swept, multiple txes are
406
        // created and published.
407
        MaxInputsPerTx uint32
408

409
        // MaxFeeRate is the maximum fee rate allowed within the UtxoSweeper.
410
        MaxFeeRate chainfee.SatPerVByte
411

412
        // Aggregator is used to group inputs into clusters based on its
413
        // implemention-specific strategy.
414
        Aggregator UtxoAggregator
415

416
        // Publisher is used to publish the sweep tx crafted here and monitors
417
        // it for potential fee bumps.
418
        Publisher Bumper
419

420
        // NoDeadlineConfTarget is the conf target to use when sweeping
421
        // non-time-sensitive outputs.
422
        NoDeadlineConfTarget uint32
423
}
424

425
// Result is the struct that is pushed through the result channel. Callers can
426
// use this to be informed of the final sweep result. In case of a remote
427
// spend, Err will be ErrRemoteSpend.
428
type Result struct {
429
        // Err is the final result of the sweep. It is nil when the input is
430
        // swept successfully by us. ErrRemoteSpend is returned when another
431
        // party took the input.
432
        Err error
433

434
        // Tx is the transaction that spent the input.
435
        Tx *wire.MsgTx
436
}
437

438
// sweepInputMessage structs are used in the internal channel between the
439
// SweepInput call and the sweeper main loop.
440
type sweepInputMessage struct {
441
        input      input.Input
442
        params     Params
443
        resultChan chan Result
444
}
445

446
// New returns a new Sweeper instance.
447
func New(cfg *UtxoSweeperConfig) *UtxoSweeper {
20✔
448
        s := &UtxoSweeper{
20✔
449
                cfg:               cfg,
20✔
450
                newInputs:         make(chan *sweepInputMessage),
20✔
451
                spendChan:         make(chan *chainntnfs.SpendDetail),
20✔
452
                updateReqs:        make(chan *updateReq),
20✔
453
                pendingSweepsReqs: make(chan *pendingSweepsReq),
20✔
454
                quit:              make(chan struct{}),
20✔
455
                inputs:            make(InputsMap),
20✔
456
                bumpRespChan:      make(chan *bumpResp, 100),
20✔
457
        }
20✔
458

20✔
459
        // Mount the block consumer.
20✔
460
        s.BeatConsumer = chainio.NewBeatConsumer(s.quit, s.Name())
20✔
461

20✔
462
        return s
20✔
463
}
20✔
464

465
// Start starts the process of constructing and publish sweep txes.
466
func (s *UtxoSweeper) Start(beat chainio.Blockbeat) error {
×
467
        if !atomic.CompareAndSwapUint32(&s.started, 0, 1) {
×
468
                return nil
×
469
        }
×
470

471
        log.Info("Sweeper starting")
×
472

×
473
        // Retrieve relay fee for dust limit calculation. Assume that this will
×
474
        // not change from here on.
×
475
        s.relayFeeRate = s.cfg.FeeEstimator.RelayFeePerKW()
×
476

×
477
        // Set the current height.
×
478
        s.currentHeight = beat.Height()
×
479

×
480
        // Start sweeper main loop.
×
481
        s.wg.Add(1)
×
482
        go s.collector()
×
483

×
484
        return nil
×
485
}
486

487
// RelayFeePerKW returns the minimum fee rate required for transactions to be
488
// relayed.
489
func (s *UtxoSweeper) RelayFeePerKW() chainfee.SatPerKWeight {
×
490
        return s.relayFeeRate
×
491
}
×
492

493
// Stop stops sweeper from listening to block epochs and constructing sweep
494
// txes.
495
func (s *UtxoSweeper) Stop() error {
×
496
        if !atomic.CompareAndSwapUint32(&s.stopped, 0, 1) {
×
497
                return nil
×
498
        }
×
499

500
        log.Info("Sweeper shutting down...")
×
501
        defer log.Debug("Sweeper shutdown complete")
×
502

×
503
        close(s.quit)
×
504
        s.wg.Wait()
×
505

×
506
        return nil
×
507
}
508

509
// NOTE: part of the `chainio.Consumer` interface.
510
func (s *UtxoSweeper) Name() string {
20✔
511
        return "UtxoSweeper"
20✔
512
}
20✔
513

514
// SweepInput sweeps inputs back into the wallet. The inputs will be batched and
515
// swept after the batch time window ends. A custom fee preference can be
516
// provided to determine what fee rate should be used for the input. Note that
517
// the input may not always be swept with this exact value, as its possible for
518
// it to be batched under the same transaction with other similar fee rate
519
// inputs.
520
//
521
// NOTE: Extreme care needs to be taken that input isn't changed externally.
522
// Because it is an interface and we don't know what is exactly behind it, we
523
// cannot make a local copy in sweeper.
524
//
525
// TODO(yy): make sure the caller is using the Result chan.
526
func (s *UtxoSweeper) SweepInput(inp input.Input,
527
        params Params) (chan Result, error) {
×
528

×
529
        if inp == nil || inp.OutPoint() == input.EmptyOutPoint ||
×
530
                inp.SignDesc() == nil {
×
531

×
532
                return nil, errors.New("nil input received")
×
533
        }
×
534

535
        absoluteTimeLock, _ := inp.RequiredLockTime()
×
536
        log.Debugf("Sweep request received: out_point=%v, witness_type=%v, "+
×
537
                "relative_time_lock=%v, absolute_time_lock=%v, amount=%v, "+
×
538
                "parent=(%v), params=(%v)", inp.OutPoint(), inp.WitnessType(),
×
539
                inp.BlocksToMaturity(), absoluteTimeLock,
×
540
                btcutil.Amount(inp.SignDesc().Output.Value),
×
541
                inp.UnconfParent(), params)
×
542

×
543
        sweeperInput := &sweepInputMessage{
×
544
                input:      inp,
×
545
                params:     params,
×
546
                resultChan: make(chan Result, 1),
×
547
        }
×
548

×
549
        // Deliver input to the main event loop.
×
550
        select {
×
551
        case s.newInputs <- sweeperInput:
×
552
        case <-s.quit:
×
553
                return nil, ErrSweeperShuttingDown
×
554
        }
555

556
        return sweeperInput.resultChan, nil
×
557
}
558

559
// removeConflictSweepDescendants removes any transactions from the wallet that
560
// spend outputs included in the passed outpoint set. This needs to be done in
561
// cases where we're not the only ones that can sweep an output, but there may
562
// exist unconfirmed spends that spend outputs created by a sweep transaction.
563
// The most common case for this is when someone sweeps our anchor outputs
564
// after 16 blocks. Moreover this is also needed for wallets which use neutrino
565
// as a backend when a channel is force closed and anchor cpfp txns are
566
// created to bump the initial commitment transaction. In this case an anchor
567
// cpfp is broadcasted for up to 3 commitment transactions (local,
568
// remote-dangling, remote). Using neutrino all of those transactions will be
569
// accepted (the commitment tx will be different in all of those cases) and have
570
// to be removed as soon as one of them confirmes (they do have the same
571
// ExclusiveGroup). For neutrino backends the corresponding BIP 157 serving full
572
// nodes do not signal invalid transactions anymore.
573
func (s *UtxoSweeper) removeConflictSweepDescendants(
574
        outpoints map[wire.OutPoint]struct{}) error {
1✔
575

1✔
576
        // Obtain all the past sweeps that we've done so far. We'll need these
1✔
577
        // to ensure that if the spendingTx spends any of the same inputs, then
1✔
578
        // we remove any transaction that may be spending those inputs from the
1✔
579
        // wallet.
1✔
580
        //
1✔
581
        // TODO(roasbeef): can be last sweep here if we remove anything confirmed
1✔
582
        // from the store?
1✔
583
        pastSweepHashes, err := s.cfg.Store.ListSweeps()
1✔
584
        if err != nil {
1✔
585
                return err
×
586
        }
×
587

588
        // We'll now go through each past transaction we published during this
589
        // epoch and cross reference the spent inputs. If there're any inputs
590
        // in common with the inputs the spendingTx spent, then we'll remove
591
        // those.
592
        //
593
        // TODO(roasbeef): need to start to remove all transaction hashes after
594
        // every N blocks (assumed point of no return)
595
        for _, sweepHash := range pastSweepHashes {
1✔
596
                sweepTx, err := s.cfg.Wallet.FetchTx(sweepHash)
×
597
                if err != nil {
×
598
                        return err
×
599
                }
×
600

601
                // Transaction wasn't found in the wallet, may have already
602
                // been replaced/removed.
603
                if sweepTx == nil {
×
604
                        // If it was removed, then we'll play it safe and mark
×
605
                        // it as no longer need to be rebroadcasted.
×
606
                        s.cfg.Wallet.CancelRebroadcast(sweepHash)
×
607
                        continue
×
608
                }
609

610
                // Check to see if this past sweep transaction spent any of the
611
                // same inputs as spendingTx.
612
                var isConflicting bool
×
613
                for _, txIn := range sweepTx.TxIn {
×
614
                        if _, ok := outpoints[txIn.PreviousOutPoint]; ok {
×
615
                                isConflicting = true
×
616
                                break
×
617
                        }
618
                }
619

620
                if !isConflicting {
×
621
                        continue
×
622
                }
623

624
                // If it is conflicting, then we'll signal the wallet to remove
625
                // all the transactions that are descendants of outputs created
626
                // by the sweepTx and the sweepTx itself.
627
                log.Debugf("Removing sweep txid=%v from wallet: %v",
×
628
                        sweepTx.TxHash(), lnutils.SpewLogClosure(sweepTx))
×
629

×
630
                err = s.cfg.Wallet.RemoveDescendants(sweepTx)
×
631
                if err != nil {
×
632
                        log.Warnf("Unable to remove descendants: %v", err)
×
633
                }
×
634

635
                // If this transaction was conflicting, then we'll stop
636
                // rebroadcasting it in the background.
637
                s.cfg.Wallet.CancelRebroadcast(sweepHash)
×
638
        }
639

640
        return nil
1✔
641
}
642

643
// collector is the sweeper main loop. It processes new inputs, spend
644
// notifications and counts down to publication of the sweep tx.
645
func (s *UtxoSweeper) collector() {
×
646
        defer s.wg.Done()
×
647

×
648
        for {
×
649
                // Clean inputs, which will remove inputs that are swept,
×
650
                // failed, or excluded from the sweeper and return inputs that
×
651
                // are either new or has been published but failed back, which
×
652
                // will be retried again here.
×
653
                s.updateSweeperInputs()
×
654

×
655
                select {
×
656
                // A new inputs is offered to the sweeper. We check to see if
657
                // we are already trying to sweep this input and if not, set up
658
                // a listener to spend and schedule a sweep.
659
                case input := <-s.newInputs:
×
660
                        err := s.handleNewInput(input)
×
661
                        if err != nil {
×
662
                                log.Criticalf("Unable to handle new input: %v",
×
663
                                        err)
×
664

×
665
                                return
×
666
                        }
×
667

668
                        // If this input is forced, we perform an sweep
669
                        // immediately.
670
                        //
671
                        // TODO(ziggie): Make sure when `immediate` is selected
672
                        // as a parameter that we only trigger the sweeping of
673
                        // this specific input rather than triggering the sweeps
674
                        // of all current pending inputs registered with the
675
                        // sweeper.
676
                        if input.params.Immediate {
×
677
                                inputs := s.updateSweeperInputs()
×
678
                                s.sweepPendingInputs(inputs)
×
679
                        }
×
680

681
                // A spend of one of our inputs is detected. Signal sweep
682
                // results to the caller(s).
683
                case spend := <-s.spendChan:
×
684
                        s.handleInputSpent(spend)
×
685

686
                // A new external request has been received to retrieve all of
687
                // the inputs we're currently attempting to sweep.
688
                case req := <-s.pendingSweepsReqs:
×
689
                        s.handlePendingSweepsReq(req)
×
690

691
                // A new external request has been received to bump the fee rate
692
                // of a given input.
693
                case req := <-s.updateReqs:
×
694
                        resultChan, err := s.handleUpdateReq(req)
×
695
                        req.responseChan <- &updateResp{
×
696
                                resultChan: resultChan,
×
697
                                err:        err,
×
698
                        }
×
699

×
700
                        // Perform an sweep immediately if asked.
×
701
                        if req.params.Immediate {
×
702
                                inputs := s.updateSweeperInputs()
×
703
                                s.sweepPendingInputs(inputs)
×
704
                        }
×
705

706
                case resp := <-s.bumpRespChan:
×
707
                        // Handle the bump event.
×
708
                        err := s.handleBumpEvent(resp)
×
709
                        if err != nil {
×
710
                                log.Errorf("Failed to handle bump event: %v",
×
711
                                        err)
×
712
                        }
×
713

714
                // A new block comes in, update the bestHeight, perform a check
715
                // over all pending inputs and publish sweeping txns if needed.
716
                case beat := <-s.BlockbeatChan:
×
717
                        // Update the sweeper to the best height.
×
718
                        s.currentHeight = beat.Height()
×
719

×
720
                        // Update the inputs with the latest height.
×
721
                        inputs := s.updateSweeperInputs()
×
722

×
723
                        log.Debugf("Received new block: height=%v, attempt "+
×
724
                                "sweeping %d inputs:%s", s.currentHeight,
×
725
                                len(inputs),
×
726
                                lnutils.NewLogClosure(func() string {
×
727
                                        return inputsMapToString(inputs)
×
728
                                }))
×
729

730
                        // Attempt to sweep any pending inputs.
731
                        s.sweepPendingInputs(inputs)
×
732

×
733
                        // Notify we've processed the block.
×
734
                        s.NotifyBlockProcessed(beat, nil)
×
735

736
                case <-s.quit:
×
737
                        return
×
738
                }
739
        }
740
}
741

742
// removeExclusiveGroup removes all inputs in the given exclusive group except
743
// the input specified by the outpoint. This function is called when one of the
744
// exclusive group inputs has been spent or updated. The other inputs won't ever
745
// be spendable and can be removed. This also prevents them from being part of
746
// future sweep transactions that would fail. In addition sweep transactions of
747
// those inputs will be removed from the wallet.
748
func (s *UtxoSweeper) removeExclusiveGroup(group uint64, op wire.OutPoint) {
×
749
        for outpoint, input := range s.inputs {
×
750
                outpoint := outpoint
×
751

×
752
                // Skip the input that caused the exclusive group to be removed.
×
753
                if outpoint == op {
×
754
                        log.Debugf("Skipped removing exclusive input %v", input)
×
755

×
756
                        continue
×
757
                }
758

759
                // Skip inputs that aren't exclusive.
760
                if input.params.ExclusiveGroup == nil {
×
761
                        continue
×
762
                }
763

764
                // Skip inputs from other exclusive groups.
765
                if *input.params.ExclusiveGroup != group {
×
766
                        continue
×
767
                }
768

769
                // Skip inputs that are already terminated.
770
                if input.terminated() {
×
771
                        log.Tracef("Skipped sending error result for "+
×
772
                                "input %v, state=%v", outpoint, input.state)
×
773

×
774
                        continue
×
775
                }
776

777
                log.Debugf("Removing exclusive group for input %v", input)
×
778

×
779
                // Signal result channels.
×
780
                s.signalResult(input, Result{
×
781
                        Err: ErrExclusiveGroupSpend,
×
782
                })
×
783

×
784
                // Update the input's state as it can no longer be swept.
×
785
                input.state = Excluded
×
786

×
787
                // Remove all unconfirmed transactions from the wallet which
×
788
                // spend the passed outpoint of the same exclusive group.
×
789
                outpoints := map[wire.OutPoint]struct{}{
×
790
                        outpoint: {},
×
791
                }
×
792
                err := s.removeConflictSweepDescendants(outpoints)
×
793
                if err != nil {
×
794
                        log.Warnf("Unable to remove conflicting sweep tx from "+
×
795
                                "wallet for outpoint %v : %v", outpoint, err)
×
796
                }
×
797
        }
798
}
799

800
// signalResult notifies the listeners of the final result of the input sweep.
801
// It also cancels any pending spend notification.
802
func (s *UtxoSweeper) signalResult(pi *SweeperInput, result Result) {
11✔
803
        op := pi.OutPoint()
11✔
804
        listeners := pi.listeners
11✔
805

11✔
806
        if result.Err == nil {
16✔
807
                log.Tracef("Dispatching sweep success for %v to %v listeners",
5✔
808
                        op, len(listeners),
5✔
809
                )
5✔
810
        } else {
11✔
811
                log.Tracef("Dispatching sweep error for %v to %v listeners: %v",
6✔
812
                        op, len(listeners), result.Err,
6✔
813
                )
6✔
814
        }
6✔
815

816
        // Signal all listeners. Channel is buffered. Because we only send once
817
        // on every channel, it should never block.
818
        for _, resultChan := range listeners {
11✔
819
                resultChan <- result
×
820
        }
×
821

822
        // Cancel spend notification with chain notifier. This is not necessary
823
        // in case of a success, except for that a reorg could still happen.
824
        if pi.ntfnRegCancel != nil {
11✔
825
                log.Debugf("Canceling spend ntfn for %v", op)
×
826

×
827
                pi.ntfnRegCancel()
×
828
        }
×
829
}
830

831
// sweep takes a set of preselected inputs, creates a sweep tx and publishes
832
// the tx. The output address is only marked as used if the publish succeeds.
833
func (s *UtxoSweeper) sweep(set InputSet) error {
2✔
834
        // Generate an output script if there isn't an unused script available.
2✔
835
        if s.currentOutputScript.IsNone() {
3✔
836
                addr, err := s.cfg.GenSweepScript().Unpack()
1✔
837
                if err != nil {
1✔
838
                        return fmt.Errorf("gen sweep script: %w", err)
×
839
                }
×
840
                s.currentOutputScript = fn.Some(addr)
1✔
841

1✔
842
                log.Debugf("Created sweep DeliveryAddress %x",
1✔
843
                        addr.DeliveryAddress)
1✔
844
        }
845

846
        sweepAddr, err := s.currentOutputScript.UnwrapOrErr(
2✔
847
                fmt.Errorf("none sweep script"),
2✔
848
        )
2✔
849
        if err != nil {
2✔
850
                return err
×
851
        }
×
852

853
        // Create a fee bump request and ask the publisher to broadcast it. The
854
        // publisher will then take over and start monitoring the tx for
855
        // potential fee bump.
856
        req := &BumpRequest{
2✔
857
                Inputs:          set.Inputs(),
2✔
858
                Budget:          set.Budget(),
2✔
859
                DeadlineHeight:  set.DeadlineHeight(),
2✔
860
                DeliveryAddress: sweepAddr,
2✔
861
                MaxFeeRate:      s.cfg.MaxFeeRate.FeePerKWeight(),
2✔
862
                StartingFeeRate: set.StartingFeeRate(),
2✔
863
                Immediate:       set.Immediate(),
2✔
864
                // TODO(yy): pass the strategy here.
2✔
865
        }
2✔
866

2✔
867
        // Reschedule the inputs that we just tried to sweep. This is done in
2✔
868
        // case the following publish fails, we'd like to update the inputs'
2✔
869
        // publish attempts and rescue them in the next sweep.
2✔
870
        s.markInputsPendingPublish(set)
2✔
871

2✔
872
        // Broadcast will return a read-only chan that we will listen to for
2✔
873
        // this publish result and future RBF attempt.
2✔
874
        resp := s.cfg.Publisher.Broadcast(req)
2✔
875

2✔
876
        // Successfully sent the broadcast attempt, we now handle the result by
2✔
877
        // subscribing to the result chan and listen for future updates about
2✔
878
        // this tx.
2✔
879
        s.wg.Add(1)
2✔
880
        go s.monitorFeeBumpResult(set, resp)
2✔
881

2✔
882
        return nil
2✔
883
}
884

885
// markInputsPendingPublish updates the pending inputs with the given tx
886
// inputs. It also increments the `publishAttempts`.
887
func (s *UtxoSweeper) markInputsPendingPublish(set InputSet) {
3✔
888
        // Reschedule sweep.
3✔
889
        for _, input := range set.Inputs() {
6✔
890
                op := input.OutPoint()
3✔
891
                pi, ok := s.inputs[op]
3✔
892
                if !ok {
3✔
893
                        // It could be that this input is an additional wallet
×
894
                        // input that was attached. In that case there also
×
895
                        // isn't a pending input to update.
×
896
                        log.Tracef("Skipped marking input as pending "+
×
897
                                "published: %v not found in pending inputs", op)
×
898

×
899
                        continue
×
900
                }
901

902
                // If this input has already terminated, there's clearly
903
                // something wrong as it would have been removed. In this case
904
                // we log an error and skip marking this input as pending
905
                // publish.
906
                if pi.terminated() {
4✔
907
                        log.Errorf("Expect input %v to not have terminated "+
1✔
908
                                "state, instead it has %v", op, pi.state)
1✔
909

1✔
910
                        continue
1✔
911
                }
912

913
                // Update the input's state.
914
                pi.state = PendingPublish
2✔
915

2✔
916
                // Record another publish attempt.
2✔
917
                pi.publishAttempts++
2✔
918
        }
919
}
920

921
// markInputsPublished updates the sweeping tx in db and marks the list of
922
// inputs as published.
923
func (s *UtxoSweeper) markInputsPublished(tr *TxRecord, set InputSet) error {
4✔
924
        // Mark this tx in db once successfully published.
4✔
925
        //
4✔
926
        // NOTE: this will behave as an overwrite, which is fine as the record
4✔
927
        // is small.
4✔
928
        tr.Published = true
4✔
929
        err := s.cfg.Store.StoreTx(tr)
4✔
930
        if err != nil {
5✔
931
                return fmt.Errorf("store tx: %w", err)
1✔
932
        }
1✔
933

934
        // Reschedule sweep.
935
        for _, input := range set.Inputs() {
7✔
936
                op := input.OutPoint()
4✔
937
                pi, ok := s.inputs[op]
4✔
938
                if !ok {
4✔
939
                        // It could be that this input is an additional wallet
×
940
                        // input that was attached. In that case there also
×
941
                        // isn't a pending input to update.
×
942
                        log.Tracef("Skipped marking input as published: %v "+
×
943
                                "not found in pending inputs", op)
×
944

×
945
                        continue
×
946
                }
947

948
                // Valdiate that the input is in an expected state.
949
                if pi.state != PendingPublish {
5✔
950
                        // We may get a Published if this is a replacement tx.
1✔
951
                        log.Debugf("Expect input %v to have %v, instead it "+
1✔
952
                                "has %v", op, PendingPublish, pi.state)
1✔
953

1✔
954
                        continue
1✔
955
                }
956

957
                // Update the input's state.
958
                pi.state = Published
3✔
959

3✔
960
                // Update the input's latest fee rate.
3✔
961
                pi.lastFeeRate = chainfee.SatPerKWeight(tr.FeeRate)
3✔
962
        }
963

964
        return nil
3✔
965
}
966

967
// markInputsPublishFailed marks the list of inputs as failed to be published.
968
func (s *UtxoSweeper) markInputsPublishFailed(set InputSet,
969
        feeRate chainfee.SatPerKWeight) {
4✔
970

4✔
971
        // Reschedule sweep.
4✔
972
        for _, inp := range set.Inputs() {
17✔
973
                op := inp.OutPoint()
13✔
974
                pi, ok := s.inputs[op]
13✔
975
                if !ok {
13✔
976
                        // It could be that this input is an additional wallet
×
977
                        // input that was attached. In that case there also
×
978
                        // isn't a pending input to update.
×
979
                        log.Tracef("Skipped marking input as publish failed: "+
×
980
                                "%v not found in pending inputs", op)
×
981

×
982
                        continue
×
983
                }
984

985
                // Valdiate that the input is in an expected state.
986
                if pi.state != PendingPublish && pi.state != Published {
18✔
987
                        log.Debugf("Expect input %v to have %v, instead it "+
5✔
988
                                "has %v", op, PendingPublish, pi.state)
5✔
989

5✔
990
                        continue
5✔
991
                }
992

993
                log.Warnf("Failed to publish input %v", op)
8✔
994

8✔
995
                // Update the input's state.
8✔
996
                pi.state = PublishFailed
8✔
997

8✔
998
                log.Debugf("Input(%v): updating params: starting fee rate "+
8✔
999
                        "[%v -> %v]", op, pi.params.StartingFeeRate,
8✔
1000
                        feeRate)
8✔
1001

8✔
1002
                // Update the input using the fee rate specified from the
8✔
1003
                // BumpResult, which should be the starting fee rate to use for
8✔
1004
                // the next sweeping attempt.
8✔
1005
                pi.params.StartingFeeRate = fn.Some(feeRate)
8✔
1006
        }
1007
}
1008

1009
// monitorSpend registers a spend notification with the chain notifier. It
1010
// returns a cancel function that can be used to cancel the registration.
1011
func (s *UtxoSweeper) monitorSpend(outpoint wire.OutPoint,
1012
        script []byte, heightHint uint32) (func(), error) {
×
1013

×
1014
        log.Tracef("Wait for spend of %v at heightHint=%v",
×
1015
                outpoint, heightHint)
×
1016

×
1017
        spendEvent, err := s.cfg.Notifier.RegisterSpendNtfn(
×
1018
                &outpoint, script, heightHint,
×
1019
        )
×
1020
        if err != nil {
×
1021
                return nil, fmt.Errorf("register spend ntfn: %w", err)
×
1022
        }
×
1023

1024
        s.wg.Add(1)
×
1025
        go func() {
×
1026
                defer s.wg.Done()
×
1027

×
1028
                select {
×
1029
                case spend, ok := <-spendEvent.Spend:
×
1030
                        if !ok {
×
1031
                                log.Debugf("Spend ntfn for %v canceled",
×
1032
                                        outpoint)
×
1033
                                return
×
1034
                        }
×
1035

1036
                        log.Debugf("Delivering spend ntfn for %v", outpoint)
×
1037

×
1038
                        select {
×
1039
                        case s.spendChan <- spend:
×
1040
                                log.Debugf("Delivered spend ntfn for %v",
×
1041
                                        outpoint)
×
1042

1043
                        case <-s.quit:
×
1044
                        }
1045
                case <-s.quit:
×
1046
                }
1047
        }()
1048

1049
        return spendEvent.Cancel, nil
×
1050
}
1051

1052
// PendingInputs returns the set of inputs that the UtxoSweeper is currently
1053
// attempting to sweep.
1054
func (s *UtxoSweeper) PendingInputs() (
1055
        map[wire.OutPoint]*PendingInputResponse, error) {
×
1056

×
1057
        respChan := make(chan map[wire.OutPoint]*PendingInputResponse, 1)
×
1058
        errChan := make(chan error, 1)
×
1059
        select {
×
1060
        case s.pendingSweepsReqs <- &pendingSweepsReq{
1061
                respChan: respChan,
1062
                errChan:  errChan,
1063
        }:
×
1064
        case <-s.quit:
×
1065
                return nil, ErrSweeperShuttingDown
×
1066
        }
1067

1068
        select {
×
1069
        case pendingSweeps := <-respChan:
×
1070
                return pendingSweeps, nil
×
1071
        case err := <-errChan:
×
1072
                return nil, err
×
1073
        case <-s.quit:
×
1074
                return nil, ErrSweeperShuttingDown
×
1075
        }
1076
}
1077

1078
// handlePendingSweepsReq handles a request to retrieve all pending inputs the
1079
// UtxoSweeper is attempting to sweep.
1080
func (s *UtxoSweeper) handlePendingSweepsReq(
1081
        req *pendingSweepsReq) map[wire.OutPoint]*PendingInputResponse {
×
1082

×
1083
        resps := make(map[wire.OutPoint]*PendingInputResponse, len(s.inputs))
×
1084
        for _, inp := range s.inputs {
×
1085
                _, maturityHeight := inp.isMature(uint32(s.currentHeight))
×
1086

×
1087
                // Only the exported fields are set, as we expect the response
×
1088
                // to only be consumed externally.
×
1089
                op := inp.OutPoint()
×
1090
                resps[op] = &PendingInputResponse{
×
1091
                        OutPoint:    op,
×
1092
                        WitnessType: inp.WitnessType(),
×
1093
                        Amount: btcutil.Amount(
×
1094
                                inp.SignDesc().Output.Value,
×
1095
                        ),
×
1096
                        LastFeeRate:       inp.lastFeeRate,
×
1097
                        BroadcastAttempts: inp.publishAttempts,
×
1098
                        Params:            inp.params,
×
1099
                        DeadlineHeight:    uint32(inp.DeadlineHeight),
×
1100
                        MaturityHeight:    maturityHeight,
×
1101
                }
×
1102
        }
×
1103

1104
        select {
×
1105
        case req.respChan <- resps:
×
1106
        case <-s.quit:
×
1107
                log.Debug("Skipped sending pending sweep response due to " +
×
1108
                        "UtxoSweeper shutting down")
×
1109
        }
1110

1111
        return resps
×
1112
}
1113

1114
// UpdateParams allows updating the sweep parameters of a pending input in the
1115
// UtxoSweeper. This function can be used to provide an updated fee preference
1116
// and force flag that will be used for a new sweep transaction of the input
1117
// that will act as a replacement transaction (RBF) of the original sweeping
1118
// transaction, if any. The exclusive group is left unchanged.
1119
//
1120
// NOTE: This currently doesn't do any fee rate validation to ensure that a bump
1121
// is actually successful. The responsibility of doing so should be handled by
1122
// the caller.
1123
func (s *UtxoSweeper) UpdateParams(input wire.OutPoint,
1124
        params Params) (chan Result, error) {
×
1125

×
1126
        responseChan := make(chan *updateResp, 1)
×
1127
        select {
×
1128
        case s.updateReqs <- &updateReq{
1129
                input:        input,
1130
                params:       params,
1131
                responseChan: responseChan,
1132
        }:
×
1133
        case <-s.quit:
×
1134
                return nil, ErrSweeperShuttingDown
×
1135
        }
1136

1137
        select {
×
1138
        case response := <-responseChan:
×
1139
                return response.resultChan, response.err
×
1140
        case <-s.quit:
×
1141
                return nil, ErrSweeperShuttingDown
×
1142
        }
1143
}
1144

1145
// handleUpdateReq handles an update request by simply updating the sweep
1146
// parameters of the pending input. Currently, no validation is done on the new
1147
// fee preference to ensure it will properly create a replacement transaction.
1148
//
1149
// TODO(wilmer):
1150
//   - Validate fee preference to ensure we'll create a valid replacement
1151
//     transaction to allow the new fee rate to propagate throughout the
1152
//     network.
1153
//   - Ensure we don't combine this input with any other unconfirmed inputs that
1154
//     did not exist in the original sweep transaction, resulting in an invalid
1155
//     replacement transaction.
1156
func (s *UtxoSweeper) handleUpdateReq(req *updateReq) (
1157
        chan Result, error) {
×
1158

×
1159
        // If the UtxoSweeper is already trying to sweep this input, then we can
×
1160
        // simply just increase its fee rate. This will allow the input to be
×
1161
        // batched with others which also have a similar fee rate, creating a
×
1162
        // higher fee rate transaction that replaces the original input's
×
1163
        // sweeping transaction.
×
1164
        sweeperInput, ok := s.inputs[req.input]
×
1165
        if !ok {
×
1166
                return nil, lnwallet.ErrNotMine
×
1167
        }
×
1168

1169
        // Create the updated parameters struct. Leave the exclusive group
1170
        // unchanged.
1171
        newParams := Params{
×
1172
                StartingFeeRate: req.params.StartingFeeRate,
×
1173
                Immediate:       req.params.Immediate,
×
1174
                Budget:          req.params.Budget,
×
1175
                DeadlineHeight:  req.params.DeadlineHeight,
×
1176
                ExclusiveGroup:  sweeperInput.params.ExclusiveGroup,
×
1177
        }
×
1178

×
1179
        log.Debugf("Updating parameters for %v(state=%v) from (%v) to (%v)",
×
1180
                req.input, sweeperInput.state, sweeperInput.params, newParams)
×
1181

×
1182
        sweeperInput.params = newParams
×
1183

×
1184
        // We need to reset the state so this input will be attempted again by
×
1185
        // our sweeper.
×
1186
        //
×
1187
        // TODO(yy): a dedicated state?
×
1188
        sweeperInput.state = Init
×
1189

×
1190
        // If the new input specifies a deadline, update the deadline height.
×
1191
        sweeperInput.DeadlineHeight = req.params.DeadlineHeight.UnwrapOr(
×
1192
                sweeperInput.DeadlineHeight,
×
1193
        )
×
1194

×
1195
        resultChan := make(chan Result, 1)
×
1196
        sweeperInput.listeners = append(sweeperInput.listeners, resultChan)
×
1197

×
1198
        return resultChan, nil
×
1199
}
1200

1201
// ListSweeps returns a list of the sweeps recorded by the sweep store.
1202
func (s *UtxoSweeper) ListSweeps() ([]chainhash.Hash, error) {
×
1203
        return s.cfg.Store.ListSweeps()
×
1204
}
×
1205

1206
// mempoolLookup takes an input's outpoint and queries the mempool to see
1207
// whether it's already been spent in a transaction found in the mempool.
1208
// Returns the transaction if found.
1209
func (s *UtxoSweeper) mempoolLookup(op wire.OutPoint) fn.Option[wire.MsgTx] {
7✔
1210
        // For neutrino backend, there's no mempool available, so we exit
7✔
1211
        // early.
7✔
1212
        if s.cfg.Mempool == nil {
8✔
1213
                log.Debugf("Skipping mempool lookup for %v, no mempool ", op)
1✔
1214

1✔
1215
                return fn.None[wire.MsgTx]()
1✔
1216
        }
1✔
1217

1218
        // Query this input in the mempool. If this outpoint is already spent
1219
        // in mempool, we should get a spending event back immediately.
1220
        return s.cfg.Mempool.LookupInputMempoolSpend(op)
6✔
1221
}
1222

1223
// calculateDefaultDeadline calculates the default deadline height for a sweep
1224
// request that has no deadline height specified.
1225
func (s *UtxoSweeper) calculateDefaultDeadline(pi *SweeperInput) int32 {
×
1226
        // Create a default deadline height, which will be used when there's no
×
1227
        // DeadlineHeight specified for a given input.
×
1228
        defaultDeadline := s.currentHeight + int32(s.cfg.NoDeadlineConfTarget)
×
1229

×
1230
        // If the input is immature and has a locktime, we'll use the locktime
×
1231
        // height as the starting height.
×
1232
        matured, locktime := pi.isMature(uint32(s.currentHeight))
×
1233
        if !matured {
×
1234
                defaultDeadline = int32(locktime + s.cfg.NoDeadlineConfTarget)
×
1235
                log.Debugf("Input %v is immature, using locktime=%v instead "+
×
1236
                        "of current height=%d as starting height",
×
1237
                        pi.OutPoint(), locktime, s.currentHeight)
×
1238
        }
×
1239

1240
        return defaultDeadline
×
1241
}
1242

1243
// handleNewInput processes a new input by registering spend notification and
1244
// scheduling sweeping for it.
1245
func (s *UtxoSweeper) handleNewInput(input *sweepInputMessage) error {
×
1246
        outpoint := input.input.OutPoint()
×
1247
        pi, pending := s.inputs[outpoint]
×
1248
        if pending {
×
1249
                log.Infof("Already has pending input %v received, old params: "+
×
1250
                        "%v, new params %v", outpoint, pi.params, input.params)
×
1251

×
1252
                s.handleExistingInput(input, pi)
×
1253

×
1254
                return nil
×
1255
        }
×
1256

1257
        // This is a new input, and we want to query the mempool to see if this
1258
        // input has already been spent. If so, we'll start the input with the
1259
        // RBFInfo.
1260
        rbfInfo := s.decideRBFInfo(input.input.OutPoint())
×
1261

×
1262
        // Create a new pendingInput and initialize the listeners slice with
×
1263
        // the passed in result channel. If this input is offered for sweep
×
1264
        // again, the result channel will be appended to this slice.
×
1265
        pi = &SweeperInput{
×
1266
                state:     Init,
×
1267
                listeners: []chan Result{input.resultChan},
×
1268
                Input:     input.input,
×
1269
                params:    input.params,
×
1270
                rbf:       rbfInfo,
×
1271
        }
×
1272

×
1273
        // Set the starting fee rate if a previous sweeping tx is found.
×
1274
        rbfInfo.WhenSome(func(info RBFInfo) {
×
1275
                pi.params.StartingFeeRate = fn.Some(info.FeeRate)
×
1276
        })
×
1277

1278
        // Set the acutal deadline height.
1279
        pi.DeadlineHeight = input.params.DeadlineHeight.UnwrapOr(
×
1280
                s.calculateDefaultDeadline(pi),
×
1281
        )
×
1282

×
1283
        s.inputs[outpoint] = pi
×
1284
        log.Tracef("input %v, state=%v, added to inputs", outpoint, pi.state)
×
1285

×
1286
        log.Infof("Registered sweep request at block %d: out_point=%v, "+
×
1287
                "witness_type=%v, amount=%v, deadline=%d, state=%v, "+
×
1288
                "params=(%v)", s.currentHeight, pi.OutPoint(), pi.WitnessType(),
×
1289
                btcutil.Amount(pi.SignDesc().Output.Value), pi.DeadlineHeight,
×
1290
                pi.state, pi.params)
×
1291

×
1292
        // Start watching for spend of this input, either by us or the remote
×
1293
        // party.
×
1294
        cancel, err := s.monitorSpend(
×
1295
                outpoint, input.input.SignDesc().Output.PkScript,
×
1296
                input.input.HeightHint(),
×
1297
        )
×
1298
        if err != nil {
×
1299
                err := fmt.Errorf("wait for spend: %w", err)
×
1300
                s.markInputFatal(pi, nil, err)
×
1301

×
1302
                return err
×
1303
        }
×
1304

1305
        pi.ntfnRegCancel = cancel
×
1306

×
1307
        return nil
×
1308
}
1309

1310
// decideRBFInfo queries the mempool to see whether the given input has already
1311
// been spent. When spent, it will query the sweeper store to fetch the fee info
1312
// of the spending transction, and construct an RBFInfo based on it. Suppose an
1313
// error occurs, fn.None is returned.
1314
func (s *UtxoSweeper) decideRBFInfo(
1315
        op wire.OutPoint) fn.Option[RBFInfo] {
4✔
1316

4✔
1317
        // Check if we can find the spending tx of this input in mempool.
4✔
1318
        txOption := s.mempoolLookup(op)
4✔
1319

4✔
1320
        // Extract the spending tx from the option.
4✔
1321
        var tx *wire.MsgTx
4✔
1322
        txOption.WhenSome(func(t wire.MsgTx) {
7✔
1323
                tx = &t
3✔
1324
        })
3✔
1325

1326
        // Exit early if it's not found.
1327
        //
1328
        // NOTE: this is not accurate for backends that don't support mempool
1329
        // lookup:
1330
        // - for neutrino we don't have a mempool.
1331
        // - for btcd below v0.24.1 we don't have `gettxspendingprevout`.
1332
        if tx == nil {
5✔
1333
                return fn.None[RBFInfo]()
1✔
1334
        }
1✔
1335

1336
        // Otherwise the input is already spent in the mempool, so eventually
1337
        // we will return Published.
1338
        //
1339
        // We also need to update the RBF info for this input. If the sweeping
1340
        // transaction is broadcast by us, we can find the fee info in the
1341
        // sweeper store.
1342
        txid := tx.TxHash()
3✔
1343
        tr, err := s.cfg.Store.GetTx(txid)
3✔
1344

3✔
1345
        log.Debugf("Found spending tx %v in mempool for input %v", tx.TxHash(),
3✔
1346
                op)
3✔
1347

3✔
1348
        // If the tx is not found in the store, it means it's not broadcast by
3✔
1349
        // us, hence we can't find the fee info. This is fine as, later on when
3✔
1350
        // this tx is confirmed, we will remove the input from our inputs.
3✔
1351
        if errors.Is(err, ErrTxNotFound) {
4✔
1352
                log.Warnf("Spending tx %v not found in sweeper store", txid)
1✔
1353
                return fn.None[RBFInfo]()
1✔
1354
        }
1✔
1355

1356
        // Exit if we get an db error.
1357
        if err != nil {
3✔
1358
                log.Errorf("Unable to get tx %v from sweeper store: %v",
1✔
1359
                        txid, err)
1✔
1360

1✔
1361
                return fn.None[RBFInfo]()
1✔
1362
        }
1✔
1363

1364
        // Prepare the fee info and return it.
1365
        rbf := fn.Some(RBFInfo{
1✔
1366
                Txid:    txid,
1✔
1367
                Fee:     btcutil.Amount(tr.Fee),
1✔
1368
                FeeRate: chainfee.SatPerKWeight(tr.FeeRate),
1✔
1369
        })
1✔
1370

1✔
1371
        return rbf
1✔
1372
}
1373

1374
// handleExistingInput processes an input that is already known to the sweeper.
1375
// It will overwrite the params of the old input with the new ones.
1376
func (s *UtxoSweeper) handleExistingInput(input *sweepInputMessage,
1377
        oldInput *SweeperInput) {
×
1378

×
1379
        // Before updating the input details, check if a previous exclusive
×
1380
        // group was set. In case the same input is registered again, the
×
1381
        // previous input and its sweep parameters are outdated hence need to be
×
1382
        // replaced. This scenario currently only happens for anchor outputs.
×
1383
        // When a channel is force closed, in the worst case 3 different sweeps
×
1384
        // with the same exclusive group are registered with the sweeper to bump
×
1385
        // the closing transaction (cpfp) when its time critical. Receiving an
×
1386
        // input which was already registered with the sweeper means none of the
×
1387
        // previous inputs were used as CPFP, so we need to make sure we update
×
1388
        // the sweep parameters but also remove all inputs with the same
×
1389
        // exclusive group because they are outdated too.
×
1390
        var prevExclGroup *uint64
×
1391
        if oldInput.params.ExclusiveGroup != nil {
×
1392
                prevExclGroup = new(uint64)
×
1393
                *prevExclGroup = *oldInput.params.ExclusiveGroup
×
1394
        }
×
1395

1396
        // Update input details and sweep parameters. The re-offered input
1397
        // details may contain a change to the unconfirmed parent tx info.
1398
        oldInput.params = input.params
×
1399
        oldInput.Input = input.input
×
1400

×
1401
        // If the new input specifies a deadline, update the deadline height.
×
1402
        oldInput.DeadlineHeight = input.params.DeadlineHeight.UnwrapOr(
×
1403
                oldInput.DeadlineHeight,
×
1404
        )
×
1405

×
1406
        // Add additional result channel to signal spend of this input.
×
1407
        oldInput.listeners = append(oldInput.listeners, input.resultChan)
×
1408

×
1409
        if prevExclGroup != nil {
×
1410
                s.removeExclusiveGroup(*prevExclGroup, input.input.OutPoint())
×
1411
        }
×
1412
}
1413

1414
// handleInputSpent takes a spend event of our input and updates the sweeper's
1415
// internal state to remove the input.
1416
func (s *UtxoSweeper) handleInputSpent(spend *chainntnfs.SpendDetail) {
×
1417
        // Query store to find out if we ever published this tx.
×
1418
        spendHash := *spend.SpenderTxHash
×
1419
        isOurTx := s.cfg.Store.IsOurTx(spendHash)
×
1420

×
1421
        // If this isn't our transaction, it means someone else swept outputs
×
1422
        // that we were attempting to sweep. This can happen for anchor outputs
×
1423
        // as well as justice transactions. In this case, we'll notify the
×
1424
        // wallet to remove any spends that descent from this output.
×
1425
        if !isOurTx {
×
1426
                // Construct a map of the inputs this transaction spends.
×
1427
                spendingTx := spend.SpendingTx
×
1428
                inputsSpent := make(
×
1429
                        map[wire.OutPoint]struct{}, len(spendingTx.TxIn),
×
1430
                )
×
1431
                for _, txIn := range spendingTx.TxIn {
×
1432
                        inputsSpent[txIn.PreviousOutPoint] = struct{}{}
×
1433
                }
×
1434

1435
                log.Debugf("Attempting to remove descendant txns invalidated "+
×
1436
                        "by (txid=%v): %v", spendingTx.TxHash(),
×
1437
                        lnutils.SpewLogClosure(spendingTx))
×
1438

×
1439
                err := s.removeConflictSweepDescendants(inputsSpent)
×
1440
                if err != nil {
×
1441
                        log.Warnf("unable to remove descendant transactions "+
×
1442
                                "due to tx %v: ", spendHash)
×
1443
                }
×
1444

1445
                log.Debugf("Detected third party spend related to in flight "+
×
1446
                        "inputs (is_ours=%v): %v", isOurTx,
×
1447
                        lnutils.SpewLogClosure(spend.SpendingTx))
×
1448
        }
1449

1450
        // We now use the spending tx to update the state of the inputs.
1451
        s.markInputsSwept(spend.SpendingTx, isOurTx)
×
1452
}
1453

1454
// markInputsSwept marks all inputs swept by the spending transaction as swept.
1455
// It will also notify all the subscribers of this input.
1456
func (s *UtxoSweeper) markInputsSwept(tx *wire.MsgTx, isOurTx bool) {
1✔
1457
        for _, txIn := range tx.TxIn {
5✔
1458
                outpoint := txIn.PreviousOutPoint
4✔
1459

4✔
1460
                // Check if this input is known to us. It could probably be
4✔
1461
                // unknown if we canceled the registration, deleted from inputs
4✔
1462
                // map but the ntfn was in-flight already. Or this could be not
4✔
1463
                // one of our inputs.
4✔
1464
                input, ok := s.inputs[outpoint]
4✔
1465
                if !ok {
5✔
1466
                        // It's very likely that a spending tx contains inputs
1✔
1467
                        // that we don't know.
1✔
1468
                        log.Tracef("Skipped marking input as swept: %v not "+
1✔
1469
                                "found in pending inputs", outpoint)
1✔
1470

1✔
1471
                        continue
1✔
1472
                }
1473

1474
                // This input may already been marked as swept by a previous
1475
                // spend notification, which is likely to happen as one sweep
1476
                // transaction usually sweeps multiple inputs.
1477
                if input.terminated() {
4✔
1478
                        log.Debugf("Skipped marking input as swept: %v "+
1✔
1479
                                "state=%v", outpoint, input.state)
1✔
1480

1✔
1481
                        continue
1✔
1482
                }
1483

1484
                input.state = Swept
2✔
1485

2✔
1486
                // Return either a nil or a remote spend result.
2✔
1487
                var err error
2✔
1488
                if !isOurTx {
2✔
1489
                        log.Warnf("Input=%v was spent by remote or third "+
×
1490
                                "party in tx=%v", outpoint, tx.TxHash())
×
1491
                        err = ErrRemoteSpend
×
1492
                }
×
1493

1494
                // Signal result channels.
1495
                s.signalResult(input, Result{
2✔
1496
                        Tx:  tx,
2✔
1497
                        Err: err,
2✔
1498
                })
2✔
1499

2✔
1500
                // Remove all other inputs in this exclusive group.
2✔
1501
                if input.params.ExclusiveGroup != nil {
2✔
1502
                        s.removeExclusiveGroup(
×
1503
                                *input.params.ExclusiveGroup, outpoint,
×
1504
                        )
×
1505
                }
×
1506
        }
1507
}
1508

1509
// markInputFatal marks the given input as fatal and won't be retried. It
1510
// will also notify all the subscribers of this input.
1511
func (s *UtxoSweeper) markInputFatal(pi *SweeperInput, tx *wire.MsgTx,
1512
        err error) {
6✔
1513

6✔
1514
        log.Errorf("Failed to sweep input: %v, error: %v", pi, err)
6✔
1515

6✔
1516
        pi.state = Fatal
6✔
1517

6✔
1518
        s.signalResult(pi, Result{
6✔
1519
                Tx:  tx,
6✔
1520
                Err: err,
6✔
1521
        })
6✔
1522
}
6✔
1523

1524
// updateSweeperInputs updates the sweeper's internal state and returns a map
1525
// of inputs to be swept. It will remove the inputs that are in final states,
1526
// and returns a map of inputs that have either state Init or PublishFailed.
1527
func (s *UtxoSweeper) updateSweeperInputs() InputsMap {
2✔
1528
        // Create a map of inputs to be swept.
2✔
1529
        inputs := make(InputsMap)
2✔
1530

2✔
1531
        // Iterate the pending inputs and update the sweeper's state.
2✔
1532
        //
2✔
1533
        // TODO(yy): sweeper is made to communicate via go channels, so no
2✔
1534
        // locks are needed to access the map. However, it'd be safer if we
2✔
1535
        // turn this inputs map into a SyncMap in case we wanna add concurrent
2✔
1536
        // access to the map in the future.
2✔
1537
        for op, input := range s.inputs {
13✔
1538
                log.Tracef("Checking input: %s, state=%v", input, input.state)
11✔
1539

11✔
1540
                // If the input has reached a final state, that it's either
11✔
1541
                // been swept, or failed, or excluded, we will remove it from
11✔
1542
                // our sweeper.
11✔
1543
                if input.terminated() {
15✔
1544
                        log.Debugf("Removing input(State=%v) %v from sweeper",
4✔
1545
                                input.state, op)
4✔
1546

4✔
1547
                        delete(s.inputs, op)
4✔
1548

4✔
1549
                        continue
4✔
1550
                }
1551

1552
                // If this input has been included in a sweep tx that's not
1553
                // published yet, we'd skip this input and wait for the sweep
1554
                // tx to be published.
1555
                if input.state == PendingPublish {
8✔
1556
                        continue
1✔
1557
                }
1558

1559
                // If this input has already been published, we will need to
1560
                // check the RBF condition before attempting another sweeping.
1561
                if input.state == Published {
7✔
1562
                        continue
1✔
1563
                }
1564

1565
                // If the input has a locktime that's not yet reached, we will
1566
                // skip this input and wait for the locktime to be reached.
1567
                mature, _ := input.isMature(uint32(s.currentHeight))
5✔
1568
                if !mature {
7✔
1569
                        continue
2✔
1570
                }
1571

1572
                // If this input is new or has been failed to be published,
1573
                // we'd retry it. The assumption here is that when an error is
1574
                // returned from `PublishTransaction`, it means the tx has
1575
                // failed to meet the policy, hence it's not in the mempool.
1576
                inputs[op] = input
3✔
1577
        }
1578

1579
        return inputs
2✔
1580
}
1581

1582
// sweepPendingInputs is called when the ticker fires. It will create clusters
1583
// and attempt to create and publish the sweeping transactions.
1584
func (s *UtxoSweeper) sweepPendingInputs(inputs InputsMap) {
2✔
1585
        log.Debugf("Sweeping %v inputs", len(inputs))
2✔
1586

2✔
1587
        // Cluster all of our inputs based on the specific Aggregator.
2✔
1588
        sets := s.cfg.Aggregator.ClusterInputs(inputs)
2✔
1589

2✔
1590
        // sweepWithLock is a helper closure that executes the sweep within a
2✔
1591
        // coin select lock to prevent the coins being selected for other
2✔
1592
        // transactions like funding of a channel.
2✔
1593
        sweepWithLock := func(set InputSet) error {
3✔
1594
                return s.cfg.Wallet.WithCoinSelectLock(func() error {
2✔
1595
                        // Try to add inputs from our wallet.
1✔
1596
                        err := set.AddWalletInputs(s.cfg.Wallet)
1✔
1597
                        if err != nil {
1✔
1598
                                return err
×
1599
                        }
×
1600

1601
                        // Create sweeping transaction for each set.
1602
                        err = s.sweep(set)
1✔
1603
                        if err != nil {
1✔
1604
                                return err
×
1605
                        }
×
1606

1607
                        return nil
1✔
1608
                })
1609
        }
1610

1611
        for _, set := range sets {
4✔
1612
                var err error
2✔
1613
                if set.NeedWalletInput() {
3✔
1614
                        // Sweep the set of inputs that need the wallet inputs.
1✔
1615
                        err = sweepWithLock(set)
1✔
1616
                } else {
2✔
1617
                        // Sweep the set of inputs that don't need the wallet
1✔
1618
                        // inputs.
1✔
1619
                        err = s.sweep(set)
1✔
1620
                }
1✔
1621

1622
                if err != nil {
2✔
1623
                        log.Errorf("Failed to sweep %v: %v", set, err)
×
1624
                }
×
1625
        }
1626
}
1627

1628
// bumpResp wraps the result of a bump attempt returned from the fee bumper and
1629
// the inputs being used.
1630
type bumpResp struct {
1631
        // result is the result of the bump attempt returned from the fee
1632
        // bumper.
1633
        result *BumpResult
1634

1635
        // set is the input set that was used in the bump attempt.
1636
        set InputSet
1637
}
1638

1639
// monitorFeeBumpResult subscribes to the passed result chan to listen for
1640
// future updates about the sweeping tx.
1641
//
1642
// NOTE: must run as a goroutine.
1643
func (s *UtxoSweeper) monitorFeeBumpResult(set InputSet,
1644
        resultChan <-chan *BumpResult) {
6✔
1645

6✔
1646
        defer s.wg.Done()
6✔
1647

6✔
1648
        for {
13✔
1649
                select {
7✔
1650
                case r := <-resultChan:
3✔
1651
                        // Validate the result is valid.
3✔
1652
                        if err := r.Validate(); err != nil {
3✔
1653
                                log.Errorf("Received invalid result: %v", err)
×
1654
                                continue
×
1655
                        }
1656

1657
                        resp := &bumpResp{
3✔
1658
                                result: r,
3✔
1659
                                set:    set,
3✔
1660
                        }
3✔
1661

3✔
1662
                        // Send the result back to the main event loop.
3✔
1663
                        select {
3✔
1664
                        case s.bumpRespChan <- resp:
3✔
1665
                        case <-s.quit:
×
1666
                                log.Debug("Sweeper shutting down, skip " +
×
1667
                                        "sending bump result")
×
1668

×
1669
                                return
×
1670
                        }
1671

1672
                        // The sweeping tx has been confirmed, we can exit the
1673
                        // monitor now.
1674
                        //
1675
                        // TODO(yy): can instead remove the spend subscription
1676
                        // in sweeper and rely solely on this event to mark
1677
                        // inputs as Swept?
1678
                        if r.Event == TxConfirmed || r.Event == TxFailed {
5✔
1679
                                // Exit if the tx is failed to be created.
2✔
1680
                                if r.Tx == nil {
2✔
1681
                                        log.Debugf("Received %v for nil tx, "+
×
1682
                                                "exit monitor", r.Event)
×
1683

×
1684
                                        return
×
1685
                                }
×
1686

1687
                                log.Debugf("Received %v for sweep tx %v, exit "+
2✔
1688
                                        "fee bump monitor", r.Event,
2✔
1689
                                        r.Tx.TxHash())
2✔
1690

2✔
1691
                                // Cancel the rebroadcasting of the failed tx.
2✔
1692
                                s.cfg.Wallet.CancelRebroadcast(r.Tx.TxHash())
2✔
1693

2✔
1694
                                return
2✔
1695
                        }
1696

1697
                case <-s.quit:
2✔
1698
                        log.Debugf("Sweeper shutting down, exit fee " +
2✔
1699
                                "bump handler")
2✔
1700

2✔
1701
                        return
2✔
1702
                }
1703
        }
1704
}
1705

1706
// handleBumpEventTxFailed handles the case where the tx has been failed to
1707
// publish.
1708
func (s *UtxoSweeper) handleBumpEventTxFailed(resp *bumpResp) {
1✔
1709
        r := resp.result
1✔
1710
        tx, err := r.Tx, r.Err
1✔
1711

1✔
1712
        if tx != nil {
2✔
1713
                log.Warnf("Fee bump attempt failed for tx=%v: %v", tx.TxHash(),
1✔
1714
                        err)
1✔
1715
        }
1✔
1716

1717
        // NOTE: When marking the inputs as failed, we are using the input set
1718
        // instead of the inputs found in the tx. This is fine for current
1719
        // version of the sweeper because we always create a tx using ALL of
1720
        // the inputs specified by the set.
1721
        //
1722
        // TODO(yy): should we also remove the failed tx from db?
1723
        s.markInputsPublishFailed(resp.set, resp.result.FeeRate)
1✔
1724
}
1725

1726
// handleBumpEventTxReplaced handles the case where the sweeping tx has been
1727
// replaced by a new one.
1728
func (s *UtxoSweeper) handleBumpEventTxReplaced(resp *bumpResp) error {
3✔
1729
        r := resp.result
3✔
1730
        oldTx := r.ReplacedTx
3✔
1731
        newTx := r.Tx
3✔
1732

3✔
1733
        // Prepare a new record to replace the old one.
3✔
1734
        tr := &TxRecord{
3✔
1735
                Txid:    newTx.TxHash(),
3✔
1736
                FeeRate: uint64(r.FeeRate),
3✔
1737
                Fee:     uint64(r.Fee),
3✔
1738
        }
3✔
1739

3✔
1740
        // Get the old record for logging purpose.
3✔
1741
        oldTxid := oldTx.TxHash()
3✔
1742
        record, err := s.cfg.Store.GetTx(oldTxid)
3✔
1743
        if err != nil {
4✔
1744
                log.Errorf("Fetch tx record for %v: %v", oldTxid, err)
1✔
1745
                return err
1✔
1746
        }
1✔
1747

1748
        // Cancel the rebroadcasting of the replaced tx.
1749
        s.cfg.Wallet.CancelRebroadcast(oldTxid)
2✔
1750

2✔
1751
        log.Infof("RBFed tx=%v(fee=%v sats, feerate=%v sats/kw) with new "+
2✔
1752
                "tx=%v(fee=%v sats, feerate=%v sats/kw)", record.Txid,
2✔
1753
                record.Fee, record.FeeRate, tr.Txid, tr.Fee, tr.FeeRate)
2✔
1754

2✔
1755
        // The old sweeping tx has been replaced by a new one, we will update
2✔
1756
        // the tx record in the sweeper db.
2✔
1757
        //
2✔
1758
        // TODO(yy): we may also need to update the inputs in this tx to a new
2✔
1759
        // state. Suppose a replacing tx only spends a subset of the inputs
2✔
1760
        // here, we'd end up with the rest being marked as `Published` and
2✔
1761
        // won't be aggregated in the next sweep. Atm it's fine as we always
2✔
1762
        // RBF the same input set.
2✔
1763
        if err := s.cfg.Store.DeleteTx(oldTxid); err != nil {
3✔
1764
                log.Errorf("Delete tx record for %v: %v", oldTxid, err)
1✔
1765
                return err
1✔
1766
        }
1✔
1767

1768
        // Mark the inputs as published using the replacing tx.
1769
        return s.markInputsPublished(tr, resp.set)
1✔
1770
}
1771

1772
// handleBumpEventTxPublished handles the case where the sweeping tx has been
1773
// successfully published.
1774
func (s *UtxoSweeper) handleBumpEventTxPublished(resp *bumpResp) error {
1✔
1775
        r := resp.result
1✔
1776
        tx := r.Tx
1✔
1777
        tr := &TxRecord{
1✔
1778
                Txid:    tx.TxHash(),
1✔
1779
                FeeRate: uint64(r.FeeRate),
1✔
1780
                Fee:     uint64(r.Fee),
1✔
1781
        }
1✔
1782

1✔
1783
        // Inputs have been successfully published so we update their
1✔
1784
        // states.
1✔
1785
        err := s.markInputsPublished(tr, resp.set)
1✔
1786
        if err != nil {
1✔
1787
                return err
×
1788
        }
×
1789

1790
        log.Debugf("Published sweep tx %v, num_inputs=%v, height=%v",
1✔
1791
                tx.TxHash(), len(tx.TxIn), s.currentHeight)
1✔
1792

1✔
1793
        // If there's no error, remove the output script. Otherwise keep it so
1✔
1794
        // that it can be reused for the next transaction and causes no address
1✔
1795
        // inflation.
1✔
1796
        s.currentOutputScript = fn.None[lnwallet.AddrWithKey]()
1✔
1797

1✔
1798
        return nil
1✔
1799
}
1800

1801
// handleBumpEventTxFatal handles the case where there's an unexpected error
1802
// when creating or publishing the sweeping tx. In this case, the tx will be
1803
// removed from the sweeper store and the inputs will be marked as `Failed`,
1804
// which means they will not be retried.
1805
func (s *UtxoSweeper) handleBumpEventTxFatal(resp *bumpResp) error {
2✔
1806
        r := resp.result
2✔
1807

2✔
1808
        // Remove the tx from the sweeper store if there is one. Since this is
2✔
1809
        // a broadcast error, it's likely there isn't a tx here.
2✔
1810
        if r.Tx != nil {
4✔
1811
                txid := r.Tx.TxHash()
2✔
1812
                log.Infof("Tx=%v failed with unexpected error: %v", txid, r.Err)
2✔
1813

2✔
1814
                // Remove the tx from the sweeper db if it exists.
2✔
1815
                if err := s.cfg.Store.DeleteTx(txid); err != nil {
3✔
1816
                        return fmt.Errorf("delete tx record for %v: %w", txid,
1✔
1817
                                err)
1✔
1818
                }
1✔
1819
        }
1820

1821
        // Mark the inputs as fatal.
1822
        s.markInputsFatal(resp.set, r.Err)
1✔
1823

1✔
1824
        return nil
1✔
1825
}
1826

1827
// markInputsFatal  marks all inputs in the input set as failed. It will also
1828
// notify all the subscribers of these inputs.
1829
func (s *UtxoSweeper) markInputsFatal(set InputSet, err error) {
2✔
1830
        for _, inp := range set.Inputs() {
9✔
1831
                outpoint := inp.OutPoint()
7✔
1832

7✔
1833
                input, ok := s.inputs[outpoint]
7✔
1834
                if !ok {
7✔
1835
                        // It's very likely that a spending tx contains inputs
×
1836
                        // that we don't know.
×
1837
                        log.Tracef("Skipped marking input as failed: %v not "+
×
1838
                                "found in pending inputs", outpoint)
×
1839

×
1840
                        continue
×
1841
                }
1842

1843
                // If the input is already in a terminal state, we don't want
1844
                // to rewrite it, which also indicates an error as we only get
1845
                // an error event during the initial broadcast.
1846
                if input.terminated() {
10✔
1847
                        log.Errorf("Skipped marking input=%v as failed due to "+
3✔
1848
                                "unexpected state=%v", outpoint, input.state)
3✔
1849

3✔
1850
                        continue
3✔
1851
                }
1852

1853
                s.markInputFatal(input, nil, err)
4✔
1854
        }
1855
}
1856

1857
// handleBumpEvent handles the result sent from the bumper based on its event
1858
// type.
1859
//
1860
// NOTE: TxConfirmed event is not handled, since we already subscribe to the
1861
// input's spending event, we don't need to do anything here.
1862
func (s *UtxoSweeper) handleBumpEvent(r *bumpResp) error {
1✔
1863
        log.Debugf("Received bump result %v", r.result)
1✔
1864

1✔
1865
        switch r.result.Event {
1✔
1866
        // The tx has been published, we update the inputs' state and create a
1867
        // record to be stored in the sweeper db.
1868
        case TxPublished:
×
1869
                return s.handleBumpEventTxPublished(r)
×
1870

1871
        // The tx has failed, we update the inputs' state.
1872
        case TxFailed:
1✔
1873
                s.handleBumpEventTxFailed(r)
1✔
1874
                return nil
1✔
1875

1876
        // The tx has been replaced, we will remove the old tx and replace it
1877
        // with the new one.
1878
        case TxReplaced:
×
1879
                return s.handleBumpEventTxReplaced(r)
×
1880

1881
        // There are inputs being spent in a tx which the fee bumper doesn't
1882
        // understand. We will remove the tx from the sweeper db and mark the
1883
        // inputs as swept.
1884
        case TxUnknownSpend:
×
1885
                s.handleBumpEventTxUnknownSpend(r)
×
1886

1887
        // There's a fatal error in creating the tx, we will remove the tx from
1888
        // the sweeper db and mark the inputs as failed.
1889
        case TxFatal:
×
1890
                return s.handleBumpEventTxFatal(r)
×
1891
        }
1892

1893
        return nil
×
1894
}
1895

1896
// IsSweeperOutpoint determines whether the outpoint was created by the sweeper.
1897
//
1898
// NOTE: It is enough to check the txid because the sweeper will create
1899
// outpoints which solely belong to the internal LND wallet.
1900
func (s *UtxoSweeper) IsSweeperOutpoint(op wire.OutPoint) bool {
×
1901
        return s.cfg.Store.IsOurTx(op.Hash)
×
1902
}
×
1903

1904
// markInputSwept marks the given input as swept by the tx. It will also notify
1905
// all the subscribers of this input.
1906
func (s *UtxoSweeper) markInputSwept(inp *SweeperInput, tx *wire.MsgTx) {
3✔
1907
        log.Debugf("Marking input as swept: %v from state=%v", inp.OutPoint(),
3✔
1908
                inp.state)
3✔
1909

3✔
1910
        inp.state = Swept
3✔
1911

3✔
1912
        // Signal result channels.
3✔
1913
        s.signalResult(inp, Result{
3✔
1914
                Tx: tx,
3✔
1915
        })
3✔
1916

3✔
1917
        // Remove all other inputs in this exclusive group.
3✔
1918
        if inp.params.ExclusiveGroup != nil {
3✔
1919
                s.removeExclusiveGroup(
×
1920
                        *inp.params.ExclusiveGroup, inp.OutPoint(),
×
1921
                )
×
1922
        }
×
1923
}
1924

1925
// handleUnknownSpendTx takes an input and its spending tx. If the spending tx
1926
// cannot be found in the sweeper store, the input will be marked as fatal,
1927
// otherwise it will be marked as swept.
1928
func (s *UtxoSweeper) handleUnknownSpendTx(inp *SweeperInput, tx *wire.MsgTx) {
4✔
1929
        op := inp.OutPoint()
4✔
1930
        txid := tx.TxHash()
4✔
1931

4✔
1932
        isOurTx := s.cfg.Store.IsOurTx(txid)
4✔
1933

4✔
1934
        // If this is our tx, it means it's a previous sweeping tx that got
4✔
1935
        // confirmed, which could happen when a restart happens during the
4✔
1936
        // sweeping process.
4✔
1937
        if isOurTx {
7✔
1938
                log.Debugf("Found our sweeping tx %v, marking input %v as "+
3✔
1939
                        "swept", txid, op)
3✔
1940

3✔
1941
                // We now use the spending tx to update the state of the inputs.
3✔
1942
                s.markInputSwept(inp, tx)
3✔
1943

3✔
1944
                return
3✔
1945
        }
3✔
1946

1947
        // Since the input is spent by others, we now mark it as fatal and won't
1948
        // be retried.
1949
        s.markInputFatal(inp, tx, ErrRemoteSpend)
1✔
1950

1✔
1951
        log.Debugf("Removing descendant txns invalidated by (txid=%v): %v",
1✔
1952
                txid, lnutils.SpewLogClosure(tx))
1✔
1953

1✔
1954
        // Construct a map of the inputs this transaction spends.
1✔
1955
        spentInputs := make(map[wire.OutPoint]struct{}, len(tx.TxIn))
1✔
1956
        for _, txIn := range tx.TxIn {
2✔
1957
                spentInputs[txIn.PreviousOutPoint] = struct{}{}
1✔
1958
        }
1✔
1959

1960
        err := s.removeConflictSweepDescendants(spentInputs)
1✔
1961
        if err != nil {
1✔
1962
                log.Warnf("unable to remove descendant transactions "+
×
1963
                        "due to tx %v: ", txid)
×
1964
        }
×
1965
}
1966

1967
// handleBumpEventTxUnknownSpend handles the case where the confirmed tx is
1968
// unknown to the fee bumper. In the case when the sweeping tx has been replaced
1969
// by another party with their tx being confirmed. It will retry sweeping the
1970
// "good" inputs once the "bad" ones are kicked out.
1971
func (s *UtxoSweeper) handleBumpEventTxUnknownSpend(r *bumpResp) {
2✔
1972
        // Mark the inputs as publish failed, which means they will be retried
2✔
1973
        // later.
2✔
1974
        s.markInputsPublishFailed(r.set, r.result.FeeRate)
2✔
1975

2✔
1976
        // Get all the inputs that are not spent in the current sweeping tx.
2✔
1977
        spentInputs := r.result.SpentInputs
2✔
1978

2✔
1979
        // Create a slice to track inputs to be retried.
2✔
1980
        inputsToRetry := make([]input.Input, 0, len(r.set.Inputs()))
2✔
1981

2✔
1982
        // Iterate all the inputs found in this bump and mark the ones spent by
2✔
1983
        // the third party as failed. The rest of inputs will then be updated
2✔
1984
        // with a new fee rate and be retried immediately.
2✔
1985
        for _, inp := range r.set.Inputs() {
5✔
1986
                op := inp.OutPoint()
3✔
1987
                input, ok := s.inputs[op]
3✔
1988

3✔
1989
                // Wallet inputs are not tracked so we will not find them from
3✔
1990
                // the inputs map.
3✔
1991
                if !ok {
3✔
1992
                        log.Debugf("Skipped marking input: %v not found in "+
×
1993
                                "pending inputs", op)
×
1994

×
1995
                        continue
×
1996
                }
1997

1998
                // Check whether this input has been spent, if so we mark it as
1999
                // fatal or swept based on whether this is one of our previous
2000
                // sweeping txns, then move to the next.
2001
                tx, spent := spentInputs[op]
3✔
2002
                if spent {
5✔
2003
                        s.handleUnknownSpendTx(input, tx)
2✔
2004

2✔
2005
                        continue
2✔
2006
                }
2007

2008
                log.Debugf("Input(%v): updating params: immediate [%v -> true]",
1✔
2009
                        op, r.result.FeeRate, input.params.Immediate)
1✔
2010

1✔
2011
                input.params.Immediate = true
1✔
2012
                inputsToRetry = append(inputsToRetry, input)
1✔
2013
        }
2014

2015
        // Exit early if there are no inputs to be retried.
2016
        if len(inputsToRetry) == 0 {
3✔
2017
                return
1✔
2018
        }
1✔
2019

2020
        log.Debugf("Retry sweeping inputs with updated params: %v",
1✔
2021
                inputTypeSummary(inputsToRetry))
1✔
2022

1✔
2023
        // Get the latest inputs, which should put the PublishFailed inputs back
1✔
2024
        // to the sweeping queue.
1✔
2025
        inputs := s.updateSweeperInputs()
1✔
2026

1✔
2027
        // Immediately sweep the remaining inputs - the previous inputs should
1✔
2028
        // now be swept with the updated StartingFeeRate immediately. We may
1✔
2029
        // also include more inputs in the new sweeping tx if new ones with the
1✔
2030
        // same deadline are offered.
1✔
2031
        s.sweepPendingInputs(inputs)
1✔
2032
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc