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

lightningnetwork / lnd / 15736109134

18 Jun 2025 02:46PM UTC coverage: 58.197% (-10.1%) from 68.248%
15736109134

Pull #9752

github

web-flow
Merge d2634a68c into 31c74f20f
Pull Request #9752: routerrpc: reject payment to invoice that don't have payment secret or blinded paths

6 of 13 new or added lines in 2 files covered. (46.15%)

28331 existing lines in 455 files now uncovered.

97860 of 168153 relevant lines covered (58.2%)

1.81 hits per line

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

87.03
/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/davecgh/go-spew/spew"
13
        "github.com/lightningnetwork/lnd/chainio"
14
        "github.com/lightningnetwork/lnd/chainntnfs"
15
        "github.com/lightningnetwork/lnd/fn/v2"
16
        "github.com/lightningnetwork/lnd/input"
17
        "github.com/lightningnetwork/lnd/lnutils"
18
        "github.com/lightningnetwork/lnd/lnwallet"
19
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
20
)
21

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

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

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

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

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

46
// Params contains the parameters that control the sweeping process.
47
type Params struct {
48
        // ExclusiveGroup is an identifier that, if set, prevents other inputs
49
        // with the same identifier from being batched together.
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 {
3✔
73
        deadline := "none"
3✔
74
        p.DeadlineHeight.WhenSome(func(d int32) {
6✔
75
                deadline = fmt.Sprintf("%d", d)
3✔
76
        })
3✔
77

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

83
        return fmt.Sprintf("startingFeeRate=%v, immediate=%v, "+
3✔
84
                "exclusive_group=%v, budget=%v, deadline=%v", p.StartingFeeRate,
3✔
85
                p.Immediate, exclusiveGroup, p.Budget, deadline)
3✔
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 {
3✔
132
        switch s {
3✔
133
        case Init:
3✔
134
                return "Init"
3✔
135

136
        case PendingPublish:
3✔
137
                return "PendingPublish"
3✔
138

139
        case Published:
3✔
140
                return "Published"
3✔
141

142
        case PublishFailed:
3✔
143
                return "PublishFailed"
3✔
144

145
        case Swept:
3✔
146
                return "Swept"
3✔
147

148
        case Excluded:
3✔
149
                return "Excluded"
3✔
150

151
        case Fatal:
2✔
152
                return "Fatal"
2✔
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 {
3✔
211
        return fmt.Sprintf("%v (%v)", p.Input.OutPoint(), p.Input.WitnessType())
3✔
212
}
3✔
213

214
// terminated returns a boolean indicating whether the input has reached a
215
// final state.
216
func (p *SweeperInput) terminated() bool {
3✔
217
        switch p.state {
3✔
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:
3✔
222
                return true
3✔
223

224
        default:
3✔
225
                return false
3✔
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) {
3✔
232
        locktime, _ := p.RequiredLockTime()
3✔
233
        if currentHeight < locktime {
6✔
234
                log.Debugf("Input %v has locktime=%v, current height is %v",
3✔
235
                        p, locktime, currentHeight)
3✔
236

3✔
237
                return false, locktime
3✔
238
        }
3✔
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()
3✔
247
        if currentHeight+1 < locktime {
6✔
248
                log.Debugf("Input %v has CSV expiry=%v, current height is %v, "+
3✔
249
                        "skipped sweeping", p, locktime, currentHeight)
3✔
250

3✔
251
                return false, locktime
3✔
252
        }
3✔
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 {
3✔
263
        if len(inputs) == 0 {
6✔
264
                return ""
3✔
265
        }
3✔
266

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

272
        return "\n" + inputTypeSummary(inps)
3✔
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 {
3✔
448
        s := &UtxoSweeper{
3✔
449
                cfg:               cfg,
3✔
450
                newInputs:         make(chan *sweepInputMessage),
3✔
451
                spendChan:         make(chan *chainntnfs.SpendDetail),
3✔
452
                updateReqs:        make(chan *updateReq),
3✔
453
                pendingSweepsReqs: make(chan *pendingSweepsReq),
3✔
454
                quit:              make(chan struct{}),
3✔
455
                inputs:            make(InputsMap),
3✔
456
                bumpRespChan:      make(chan *bumpResp, 100),
3✔
457
        }
3✔
458

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

3✔
462
        return s
3✔
463
}
3✔
464

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

471
        log.Info("Sweeper starting")
3✔
472

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

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

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

3✔
484
        return nil
3✔
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 {
3✔
496
        if !atomic.CompareAndSwapUint32(&s.stopped, 0, 1) {
3✔
497
                return nil
×
498
        }
×
499

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

3✔
503
        close(s.quit)
3✔
504
        s.wg.Wait()
3✔
505

3✔
506
        return nil
3✔
507
}
508

509
// NOTE: part of the `chainio.Consumer` interface.
510
func (s *UtxoSweeper) Name() string {
3✔
511
        return "UtxoSweeper"
3✔
512
}
3✔
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) {
3✔
528

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

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

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

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

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

556
        return sweeperInput.resultChan, nil
3✔
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 {
3✔
575

3✔
576
        // Obtain all the past sweeps that we've done so far. We'll need these
3✔
577
        // to ensure that if the spendingTx spends any of the same inputs, then
3✔
578
        // we remove any transaction that may be spending those inputs from the
3✔
579
        // wallet.
3✔
580
        //
3✔
581
        // TODO(roasbeef): can be last sweep here if we remove anything confirmed
3✔
582
        // from the store?
3✔
583
        pastSweepHashes, err := s.cfg.Store.ListSweeps()
3✔
584
        if err != nil {
3✔
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 {
6✔
596
                sweepTx, err := s.cfg.Wallet.FetchTx(sweepHash)
3✔
597
                if err != nil {
6✔
598
                        return err
3✔
599
                }
3✔
600

601
                // Transaction wasn't found in the wallet, may have already
602
                // been replaced/removed.
603
                if sweepTx == nil {
3✔
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
3✔
613
                for _, txIn := range sweepTx.TxIn {
6✔
614
                        if _, ok := outpoints[txIn.PreviousOutPoint]; ok {
6✔
615
                                isConflicting = true
3✔
616
                                break
3✔
617
                        }
618
                }
619

620
                if !isConflicting {
6✔
621
                        continue
3✔
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",
3✔
628
                        sweepTx.TxHash(), spew.Sdump(sweepTx))
3✔
629

3✔
630
                err = s.cfg.Wallet.RemoveDescendants(sweepTx)
3✔
631
                if err != nil {
3✔
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)
3✔
638
        }
639

640
        return nil
3✔
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() {
3✔
646
        defer s.wg.Done()
3✔
647

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

3✔
655
                select {
3✔
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:
3✔
660
                        err := s.handleNewInput(input)
3✔
661
                        if err != nil {
3✔
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 {
6✔
677
                                inputs := s.updateSweeperInputs()
3✔
678
                                s.sweepPendingInputs(inputs)
3✔
679
                        }
3✔
680

681
                // A spend of one of our inputs is detected. Signal sweep
682
                // results to the caller(s).
683
                case spend := <-s.spendChan:
3✔
684
                        s.handleInputSpent(spend)
3✔
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:
3✔
689
                        s.handlePendingSweepsReq(req)
3✔
690

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

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

706
                case resp := <-s.bumpRespChan:
3✔
707
                        // Handle the bump event.
3✔
708
                        err := s.handleBumpEvent(resp)
3✔
709
                        if err != nil {
6✔
710
                                log.Errorf("Failed to handle bump event: %v",
3✔
711
                                        err)
3✔
712
                        }
3✔
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:
3✔
717
                        // Update the sweeper to the best height.
3✔
718
                        s.currentHeight = beat.Height()
3✔
719

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

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

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

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

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

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

3✔
751
                // Skip inputs that aren't exclusive.
3✔
752
                if input.params.ExclusiveGroup == nil {
6✔
753
                        continue
3✔
754
                }
755

756
                // Skip inputs from other exclusive groups.
757
                if *input.params.ExclusiveGroup != group {
3✔
758
                        continue
×
759
                }
760

761
                // Skip inputs that are already terminated.
762
                if input.terminated() {
6✔
763
                        log.Tracef("Skipped sending error result for "+
3✔
764
                                "input %v, state=%v", outpoint, input.state)
3✔
765

3✔
766
                        continue
3✔
767
                }
768

769
                // Signal result channels.
770
                s.signalResult(input, Result{
3✔
771
                        Err: ErrExclusiveGroupSpend,
3✔
772
                })
3✔
773

3✔
774
                // Update the input's state as it can no longer be swept.
3✔
775
                input.state = Excluded
3✔
776

3✔
777
                // Remove all unconfirmed transactions from the wallet which
3✔
778
                // spend the passed outpoint of the same exclusive group.
3✔
779
                outpoints := map[wire.OutPoint]struct{}{
3✔
780
                        outpoint: {},
3✔
781
                }
3✔
782
                err := s.removeConflictSweepDescendants(outpoints)
3✔
783
                if err != nil {
4✔
784
                        log.Warnf("Unable to remove conflicting sweep tx from "+
1✔
785
                                "wallet for outpoint %v : %v", outpoint, err)
1✔
786
                }
1✔
787
        }
788
}
789

790
// signalResult notifies the listeners of the final result of the input sweep.
791
// It also cancels any pending spend notification.
792
func (s *UtxoSweeper) signalResult(pi *SweeperInput, result Result) {
3✔
793
        op := pi.OutPoint()
3✔
794
        listeners := pi.listeners
3✔
795

3✔
796
        if result.Err == nil {
6✔
797
                log.Tracef("Dispatching sweep success for %v to %v listeners",
3✔
798
                        op, len(listeners),
3✔
799
                )
3✔
800
        } else {
6✔
801
                log.Tracef("Dispatching sweep error for %v to %v listeners: %v",
3✔
802
                        op, len(listeners), result.Err,
3✔
803
                )
3✔
804
        }
3✔
805

806
        // Signal all listeners. Channel is buffered. Because we only send once
807
        // on every channel, it should never block.
808
        for _, resultChan := range listeners {
6✔
809
                resultChan <- result
3✔
810
        }
3✔
811

812
        // Cancel spend notification with chain notifier. This is not necessary
813
        // in case of a success, except for that a reorg could still happen.
814
        if pi.ntfnRegCancel != nil {
6✔
815
                log.Debugf("Canceling spend ntfn for %v", op)
3✔
816

3✔
817
                pi.ntfnRegCancel()
3✔
818
        }
3✔
819
}
820

821
// sweep takes a set of preselected inputs, creates a sweep tx and publishes
822
// the tx. The output address is only marked as used if the publish succeeds.
823
func (s *UtxoSweeper) sweep(set InputSet) error {
3✔
824
        // Generate an output script if there isn't an unused script available.
3✔
825
        if s.currentOutputScript.IsNone() {
6✔
826
                addr, err := s.cfg.GenSweepScript().Unpack()
3✔
827
                if err != nil {
3✔
828
                        return fmt.Errorf("gen sweep script: %w", err)
×
829
                }
×
830
                s.currentOutputScript = fn.Some(addr)
3✔
831

3✔
832
                log.Debugf("Created sweep DeliveryAddress %x",
3✔
833
                        addr.DeliveryAddress)
3✔
834
        }
835

836
        sweepAddr, err := s.currentOutputScript.UnwrapOrErr(
3✔
837
                fmt.Errorf("none sweep script"),
3✔
838
        )
3✔
839
        if err != nil {
3✔
840
                return err
×
841
        }
×
842

843
        // Create a fee bump request and ask the publisher to broadcast it. The
844
        // publisher will then take over and start monitoring the tx for
845
        // potential fee bump.
846
        req := &BumpRequest{
3✔
847
                Inputs:          set.Inputs(),
3✔
848
                Budget:          set.Budget(),
3✔
849
                DeadlineHeight:  set.DeadlineHeight(),
3✔
850
                DeliveryAddress: sweepAddr,
3✔
851
                MaxFeeRate:      s.cfg.MaxFeeRate.FeePerKWeight(),
3✔
852
                StartingFeeRate: set.StartingFeeRate(),
3✔
853
                Immediate:       set.Immediate(),
3✔
854
                // TODO(yy): pass the strategy here.
3✔
855
        }
3✔
856

3✔
857
        // Reschedule the inputs that we just tried to sweep. This is done in
3✔
858
        // case the following publish fails, we'd like to update the inputs'
3✔
859
        // publish attempts and rescue them in the next sweep.
3✔
860
        s.markInputsPendingPublish(set)
3✔
861

3✔
862
        // Broadcast will return a read-only chan that we will listen to for
3✔
863
        // this publish result and future RBF attempt.
3✔
864
        resp := s.cfg.Publisher.Broadcast(req)
3✔
865

3✔
866
        // Successfully sent the broadcast attempt, we now handle the result by
3✔
867
        // subscribing to the result chan and listen for future updates about
3✔
868
        // this tx.
3✔
869
        s.wg.Add(1)
3✔
870
        go s.monitorFeeBumpResult(set, resp)
3✔
871

3✔
872
        return nil
3✔
873
}
874

875
// markInputsPendingPublish updates the pending inputs with the given tx
876
// inputs. It also increments the `publishAttempts`.
877
func (s *UtxoSweeper) markInputsPendingPublish(set InputSet) {
3✔
878
        // Reschedule sweep.
3✔
879
        for _, input := range set.Inputs() {
6✔
880
                op := input.OutPoint()
3✔
881
                pi, ok := s.inputs[op]
3✔
882
                if !ok {
6✔
883
                        // It could be that this input is an additional wallet
3✔
884
                        // input that was attached. In that case there also
3✔
885
                        // isn't a pending input to update.
3✔
886
                        log.Tracef("Skipped marking input as pending "+
3✔
887
                                "published: %v not found in pending inputs", op)
3✔
888

3✔
889
                        continue
3✔
890
                }
891

892
                // If this input has already terminated, there's clearly
893
                // something wrong as it would have been removed. In this case
894
                // we log an error and skip marking this input as pending
895
                // publish.
896
                if pi.terminated() {
3✔
UNCOV
897
                        log.Errorf("Expect input %v to not have terminated "+
×
UNCOV
898
                                "state, instead it has %v", op, pi.state)
×
UNCOV
899

×
UNCOV
900
                        continue
×
901
                }
902

903
                // Update the input's state.
904
                pi.state = PendingPublish
3✔
905

3✔
906
                // Record another publish attempt.
3✔
907
                pi.publishAttempts++
3✔
908
        }
909
}
910

911
// markInputsPublished updates the sweeping tx in db and marks the list of
912
// inputs as published.
913
func (s *UtxoSweeper) markInputsPublished(tr *TxRecord, set InputSet) error {
3✔
914
        // Mark this tx in db once successfully published.
3✔
915
        //
3✔
916
        // NOTE: this will behave as an overwrite, which is fine as the record
3✔
917
        // is small.
3✔
918
        tr.Published = true
3✔
919
        err := s.cfg.Store.StoreTx(tr)
3✔
920
        if err != nil {
3✔
UNCOV
921
                return fmt.Errorf("store tx: %w", err)
×
UNCOV
922
        }
×
923

924
        // Reschedule sweep.
925
        for _, input := range set.Inputs() {
6✔
926
                op := input.OutPoint()
3✔
927
                pi, ok := s.inputs[op]
3✔
928
                if !ok {
6✔
929
                        // It could be that this input is an additional wallet
3✔
930
                        // input that was attached. In that case there also
3✔
931
                        // isn't a pending input to update.
3✔
932
                        log.Tracef("Skipped marking input as published: %v "+
3✔
933
                                "not found in pending inputs", op)
3✔
934

3✔
935
                        continue
3✔
936
                }
937

938
                // Valdiate that the input is in an expected state.
939
                if pi.state != PendingPublish {
6✔
940
                        // We may get a Published if this is a replacement tx.
3✔
941
                        log.Debugf("Expect input %v to have %v, instead it "+
3✔
942
                                "has %v", op, PendingPublish, pi.state)
3✔
943

3✔
944
                        continue
3✔
945
                }
946

947
                // Update the input's state.
948
                pi.state = Published
3✔
949

3✔
950
                // Update the input's latest fee rate.
3✔
951
                pi.lastFeeRate = chainfee.SatPerKWeight(tr.FeeRate)
3✔
952
        }
953

954
        return nil
3✔
955
}
956

957
// markInputsPublishFailed marks the list of inputs as failed to be published.
958
func (s *UtxoSweeper) markInputsPublishFailed(set InputSet,
959
        feeRate chainfee.SatPerKWeight) {
3✔
960

3✔
961
        // Reschedule sweep.
3✔
962
        for _, inp := range set.Inputs() {
6✔
963
                op := inp.OutPoint()
3✔
964
                pi, ok := s.inputs[op]
3✔
965
                if !ok {
6✔
966
                        // It could be that this input is an additional wallet
3✔
967
                        // input that was attached. In that case there also
3✔
968
                        // isn't a pending input to update.
3✔
969
                        log.Tracef("Skipped marking input as publish failed: "+
3✔
970
                                "%v not found in pending inputs", op)
3✔
971

3✔
972
                        continue
3✔
973
                }
974

975
                // Valdiate that the input is in an expected state.
976
                if pi.state != PendingPublish && pi.state != Published {
3✔
UNCOV
977
                        log.Debugf("Expect input %v to have %v, instead it "+
×
UNCOV
978
                                "has %v", op, PendingPublish, pi.state)
×
UNCOV
979

×
UNCOV
980
                        continue
×
981
                }
982

983
                log.Warnf("Failed to publish input %v", op)
3✔
984

3✔
985
                // Update the input's state.
3✔
986
                pi.state = PublishFailed
3✔
987

3✔
988
                log.Debugf("Input(%v): updating params: starting fee rate "+
3✔
989
                        "[%v -> %v]", op, pi.params.StartingFeeRate,
3✔
990
                        feeRate)
3✔
991

3✔
992
                // Update the input using the fee rate specified from the
3✔
993
                // BumpResult, which should be the starting fee rate to use for
3✔
994
                // the next sweeping attempt.
3✔
995
                pi.params.StartingFeeRate = fn.Some(feeRate)
3✔
996
        }
997
}
998

999
// monitorSpend registers a spend notification with the chain notifier. It
1000
// returns a cancel function that can be used to cancel the registration.
1001
func (s *UtxoSweeper) monitorSpend(outpoint wire.OutPoint,
1002
        script []byte, heightHint uint32) (func(), error) {
3✔
1003

3✔
1004
        log.Tracef("Wait for spend of %v at heightHint=%v",
3✔
1005
                outpoint, heightHint)
3✔
1006

3✔
1007
        spendEvent, err := s.cfg.Notifier.RegisterSpendNtfn(
3✔
1008
                &outpoint, script, heightHint,
3✔
1009
        )
3✔
1010
        if err != nil {
3✔
1011
                return nil, fmt.Errorf("register spend ntfn: %w", err)
×
1012
        }
×
1013

1014
        s.wg.Add(1)
3✔
1015
        go func() {
6✔
1016
                defer s.wg.Done()
3✔
1017

3✔
1018
                select {
3✔
1019
                case spend, ok := <-spendEvent.Spend:
3✔
1020
                        if !ok {
6✔
1021
                                log.Debugf("Spend ntfn for %v canceled",
3✔
1022
                                        outpoint)
3✔
1023
                                return
3✔
1024
                        }
3✔
1025

1026
                        log.Debugf("Delivering spend ntfn for %v", outpoint)
3✔
1027

3✔
1028
                        select {
3✔
1029
                        case s.spendChan <- spend:
3✔
1030
                                log.Debugf("Delivered spend ntfn for %v",
3✔
1031
                                        outpoint)
3✔
1032

1033
                        case <-s.quit:
×
1034
                        }
1035
                case <-s.quit:
3✔
1036
                }
1037
        }()
1038

1039
        return spendEvent.Cancel, nil
3✔
1040
}
1041

1042
// PendingInputs returns the set of inputs that the UtxoSweeper is currently
1043
// attempting to sweep.
1044
func (s *UtxoSweeper) PendingInputs() (
1045
        map[wire.OutPoint]*PendingInputResponse, error) {
3✔
1046

3✔
1047
        respChan := make(chan map[wire.OutPoint]*PendingInputResponse, 1)
3✔
1048
        errChan := make(chan error, 1)
3✔
1049
        select {
3✔
1050
        case s.pendingSweepsReqs <- &pendingSweepsReq{
1051
                respChan: respChan,
1052
                errChan:  errChan,
1053
        }:
3✔
1054
        case <-s.quit:
×
1055
                return nil, ErrSweeperShuttingDown
×
1056
        }
1057

1058
        select {
3✔
1059
        case pendingSweeps := <-respChan:
3✔
1060
                return pendingSweeps, nil
3✔
1061
        case err := <-errChan:
×
1062
                return nil, err
×
1063
        case <-s.quit:
×
1064
                return nil, ErrSweeperShuttingDown
×
1065
        }
1066
}
1067

1068
// handlePendingSweepsReq handles a request to retrieve all pending inputs the
1069
// UtxoSweeper is attempting to sweep.
1070
func (s *UtxoSweeper) handlePendingSweepsReq(
1071
        req *pendingSweepsReq) map[wire.OutPoint]*PendingInputResponse {
3✔
1072

3✔
1073
        resps := make(map[wire.OutPoint]*PendingInputResponse, len(s.inputs))
3✔
1074
        for _, inp := range s.inputs {
6✔
1075
                _, maturityHeight := inp.isMature(uint32(s.currentHeight))
3✔
1076

3✔
1077
                // Only the exported fields are set, as we expect the response
3✔
1078
                // to only be consumed externally.
3✔
1079
                op := inp.OutPoint()
3✔
1080
                resps[op] = &PendingInputResponse{
3✔
1081
                        OutPoint:    op,
3✔
1082
                        WitnessType: inp.WitnessType(),
3✔
1083
                        Amount: btcutil.Amount(
3✔
1084
                                inp.SignDesc().Output.Value,
3✔
1085
                        ),
3✔
1086
                        LastFeeRate:       inp.lastFeeRate,
3✔
1087
                        BroadcastAttempts: inp.publishAttempts,
3✔
1088
                        Params:            inp.params,
3✔
1089
                        DeadlineHeight:    uint32(inp.DeadlineHeight),
3✔
1090
                        MaturityHeight:    maturityHeight,
3✔
1091
                }
3✔
1092
        }
3✔
1093

1094
        select {
3✔
1095
        case req.respChan <- resps:
3✔
1096
        case <-s.quit:
×
1097
                log.Debug("Skipped sending pending sweep response due to " +
×
1098
                        "UtxoSweeper shutting down")
×
1099
        }
1100

1101
        return resps
3✔
1102
}
1103

1104
// UpdateParams allows updating the sweep parameters of a pending input in the
1105
// UtxoSweeper. This function can be used to provide an updated fee preference
1106
// and force flag that will be used for a new sweep transaction of the input
1107
// that will act as a replacement transaction (RBF) of the original sweeping
1108
// transaction, if any. The exclusive group is left unchanged.
1109
//
1110
// NOTE: This currently doesn't do any fee rate validation to ensure that a bump
1111
// is actually successful. The responsibility of doing so should be handled by
1112
// the caller.
1113
func (s *UtxoSweeper) UpdateParams(input wire.OutPoint,
1114
        params Params) (chan Result, error) {
3✔
1115

3✔
1116
        responseChan := make(chan *updateResp, 1)
3✔
1117
        select {
3✔
1118
        case s.updateReqs <- &updateReq{
1119
                input:        input,
1120
                params:       params,
1121
                responseChan: responseChan,
1122
        }:
3✔
1123
        case <-s.quit:
×
1124
                return nil, ErrSweeperShuttingDown
×
1125
        }
1126

1127
        select {
3✔
1128
        case response := <-responseChan:
3✔
1129
                return response.resultChan, response.err
3✔
1130
        case <-s.quit:
×
1131
                return nil, ErrSweeperShuttingDown
×
1132
        }
1133
}
1134

1135
// handleUpdateReq handles an update request by simply updating the sweep
1136
// parameters of the pending input. Currently, no validation is done on the new
1137
// fee preference to ensure it will properly create a replacement transaction.
1138
//
1139
// TODO(wilmer):
1140
//   - Validate fee preference to ensure we'll create a valid replacement
1141
//     transaction to allow the new fee rate to propagate throughout the
1142
//     network.
1143
//   - Ensure we don't combine this input with any other unconfirmed inputs that
1144
//     did not exist in the original sweep transaction, resulting in an invalid
1145
//     replacement transaction.
1146
func (s *UtxoSweeper) handleUpdateReq(req *updateReq) (
1147
        chan Result, error) {
3✔
1148

3✔
1149
        // If the UtxoSweeper is already trying to sweep this input, then we can
3✔
1150
        // simply just increase its fee rate. This will allow the input to be
3✔
1151
        // batched with others which also have a similar fee rate, creating a
3✔
1152
        // higher fee rate transaction that replaces the original input's
3✔
1153
        // sweeping transaction.
3✔
1154
        sweeperInput, ok := s.inputs[req.input]
3✔
1155
        if !ok {
3✔
1156
                return nil, lnwallet.ErrNotMine
×
1157
        }
×
1158

1159
        // Create the updated parameters struct. Leave the exclusive group
1160
        // unchanged.
1161
        newParams := Params{
3✔
1162
                StartingFeeRate: req.params.StartingFeeRate,
3✔
1163
                Immediate:       req.params.Immediate,
3✔
1164
                Budget:          req.params.Budget,
3✔
1165
                DeadlineHeight:  req.params.DeadlineHeight,
3✔
1166
                ExclusiveGroup:  sweeperInput.params.ExclusiveGroup,
3✔
1167
        }
3✔
1168

3✔
1169
        log.Debugf("Updating parameters for %v(state=%v) from (%v) to (%v)",
3✔
1170
                req.input, sweeperInput.state, sweeperInput.params, newParams)
3✔
1171

3✔
1172
        sweeperInput.params = newParams
3✔
1173

3✔
1174
        // We need to reset the state so this input will be attempted again by
3✔
1175
        // our sweeper.
3✔
1176
        //
3✔
1177
        // TODO(yy): a dedicated state?
3✔
1178
        sweeperInput.state = Init
3✔
1179

3✔
1180
        // If the new input specifies a deadline, update the deadline height.
3✔
1181
        sweeperInput.DeadlineHeight = req.params.DeadlineHeight.UnwrapOr(
3✔
1182
                sweeperInput.DeadlineHeight,
3✔
1183
        )
3✔
1184

3✔
1185
        resultChan := make(chan Result, 1)
3✔
1186
        sweeperInput.listeners = append(sweeperInput.listeners, resultChan)
3✔
1187

3✔
1188
        return resultChan, nil
3✔
1189
}
1190

1191
// ListSweeps returns a list of the sweeps recorded by the sweep store.
1192
func (s *UtxoSweeper) ListSweeps() ([]chainhash.Hash, error) {
3✔
1193
        return s.cfg.Store.ListSweeps()
3✔
1194
}
3✔
1195

1196
// mempoolLookup takes an input's outpoint and queries the mempool to see
1197
// whether it's already been spent in a transaction found in the mempool.
1198
// Returns the transaction if found.
1199
func (s *UtxoSweeper) mempoolLookup(op wire.OutPoint) fn.Option[wire.MsgTx] {
3✔
1200
        // For neutrino backend, there's no mempool available, so we exit
3✔
1201
        // early.
3✔
1202
        if s.cfg.Mempool == nil {
4✔
1203
                log.Debugf("Skipping mempool lookup for %v, no mempool ", op)
1✔
1204

1✔
1205
                return fn.None[wire.MsgTx]()
1✔
1206
        }
1✔
1207

1208
        // Query this input in the mempool. If this outpoint is already spent
1209
        // in mempool, we should get a spending event back immediately.
1210
        return s.cfg.Mempool.LookupInputMempoolSpend(op)
2✔
1211
}
1212

1213
// calculateDefaultDeadline calculates the default deadline height for a sweep
1214
// request that has no deadline height specified.
1215
func (s *UtxoSweeper) calculateDefaultDeadline(pi *SweeperInput) int32 {
3✔
1216
        // Create a default deadline height, which will be used when there's no
3✔
1217
        // DeadlineHeight specified for a given input.
3✔
1218
        defaultDeadline := s.currentHeight + int32(s.cfg.NoDeadlineConfTarget)
3✔
1219

3✔
1220
        // If the input is immature and has a locktime, we'll use the locktime
3✔
1221
        // height as the starting height.
3✔
1222
        matured, locktime := pi.isMature(uint32(s.currentHeight))
3✔
1223
        if !matured {
6✔
1224
                defaultDeadline = int32(locktime + s.cfg.NoDeadlineConfTarget)
3✔
1225
                log.Debugf("Input %v is immature, using locktime=%v instead "+
3✔
1226
                        "of current height=%d as starting height",
3✔
1227
                        pi.OutPoint(), locktime, s.currentHeight)
3✔
1228
        }
3✔
1229

1230
        return defaultDeadline
3✔
1231
}
1232

1233
// handleNewInput processes a new input by registering spend notification and
1234
// scheduling sweeping for it.
1235
func (s *UtxoSweeper) handleNewInput(input *sweepInputMessage) error {
3✔
1236
        outpoint := input.input.OutPoint()
3✔
1237
        pi, pending := s.inputs[outpoint]
3✔
1238
        if pending {
6✔
1239
                log.Infof("Already has pending input %v received, old params: "+
3✔
1240
                        "%v, new params %v", outpoint, pi.params, input.params)
3✔
1241

3✔
1242
                s.handleExistingInput(input, pi)
3✔
1243

3✔
1244
                return nil
3✔
1245
        }
3✔
1246

1247
        // This is a new input, and we want to query the mempool to see if this
1248
        // input has already been spent. If so, we'll start the input with the
1249
        // RBFInfo.
1250
        rbfInfo := s.decideRBFInfo(input.input.OutPoint())
3✔
1251

3✔
1252
        // Create a new pendingInput and initialize the listeners slice with
3✔
1253
        // the passed in result channel. If this input is offered for sweep
3✔
1254
        // again, the result channel will be appended to this slice.
3✔
1255
        pi = &SweeperInput{
3✔
1256
                state:     Init,
3✔
1257
                listeners: []chan Result{input.resultChan},
3✔
1258
                Input:     input.input,
3✔
1259
                params:    input.params,
3✔
1260
                rbf:       rbfInfo,
3✔
1261
        }
3✔
1262

3✔
1263
        // Set the starting fee rate if a previous sweeping tx is found.
3✔
1264
        rbfInfo.WhenSome(func(info RBFInfo) {
5✔
1265
                pi.params.StartingFeeRate = fn.Some(info.FeeRate)
2✔
1266
        })
2✔
1267

1268
        // Set the acutal deadline height.
1269
        pi.DeadlineHeight = input.params.DeadlineHeight.UnwrapOr(
3✔
1270
                s.calculateDefaultDeadline(pi),
3✔
1271
        )
3✔
1272

3✔
1273
        s.inputs[outpoint] = pi
3✔
1274
        log.Tracef("input %v, state=%v, added to inputs", outpoint, pi.state)
3✔
1275

3✔
1276
        log.Infof("Registered sweep request at block %d: out_point=%v, "+
3✔
1277
                "witness_type=%v, amount=%v, deadline=%d, state=%v, "+
3✔
1278
                "params=(%v)", s.currentHeight, pi.OutPoint(), pi.WitnessType(),
3✔
1279
                btcutil.Amount(pi.SignDesc().Output.Value), pi.DeadlineHeight,
3✔
1280
                pi.state, pi.params)
3✔
1281

3✔
1282
        // Start watching for spend of this input, either by us or the remote
3✔
1283
        // party.
3✔
1284
        cancel, err := s.monitorSpend(
3✔
1285
                outpoint, input.input.SignDesc().Output.PkScript,
3✔
1286
                input.input.HeightHint(),
3✔
1287
        )
3✔
1288
        if err != nil {
3✔
1289
                err := fmt.Errorf("wait for spend: %w", err)
×
1290
                s.markInputFatal(pi, nil, err)
×
1291

×
1292
                return err
×
1293
        }
×
1294

1295
        pi.ntfnRegCancel = cancel
3✔
1296

3✔
1297
        return nil
3✔
1298
}
1299

1300
// decideRBFInfo queries the mempool to see whether the given input has already
1301
// been spent. When spent, it will query the sweeper store to fetch the fee info
1302
// of the spending transction, and construct an RBFInfo based on it. Suppose an
1303
// error occurs, fn.None is returned.
1304
func (s *UtxoSweeper) decideRBFInfo(
1305
        op wire.OutPoint) fn.Option[RBFInfo] {
3✔
1306

3✔
1307
        // Check if we can find the spending tx of this input in mempool.
3✔
1308
        txOption := s.mempoolLookup(op)
3✔
1309

3✔
1310
        // Extract the spending tx from the option.
3✔
1311
        var tx *wire.MsgTx
3✔
1312
        txOption.WhenSome(func(t wire.MsgTx) {
5✔
1313
                tx = &t
2✔
1314
        })
2✔
1315

1316
        // Exit early if it's not found.
1317
        //
1318
        // NOTE: this is not accurate for backends that don't support mempool
1319
        // lookup:
1320
        // - for neutrino we don't have a mempool.
1321
        // - for btcd below v0.24.1 we don't have `gettxspendingprevout`.
1322
        if tx == nil {
6✔
1323
                return fn.None[RBFInfo]()
3✔
1324
        }
3✔
1325

1326
        // Otherwise the input is already spent in the mempool, so eventually
1327
        // we will return Published.
1328
        //
1329
        // We also need to update the RBF info for this input. If the sweeping
1330
        // transaction is broadcast by us, we can find the fee info in the
1331
        // sweeper store.
1332
        txid := tx.TxHash()
2✔
1333
        tr, err := s.cfg.Store.GetTx(txid)
2✔
1334

2✔
1335
        log.Debugf("Found spending tx %v in mempool for input %v", tx.TxHash(),
2✔
1336
                op)
2✔
1337

2✔
1338
        // If the tx is not found in the store, it means it's not broadcast by
2✔
1339
        // us, hence we can't find the fee info. This is fine as, later on when
2✔
1340
        // this tx is confirmed, we will remove the input from our inputs.
2✔
1341
        if errors.Is(err, ErrTxNotFound) {
4✔
1342
                log.Warnf("Spending tx %v not found in sweeper store", txid)
2✔
1343
                return fn.None[RBFInfo]()
2✔
1344
        }
2✔
1345

1346
        // Exit if we get an db error.
1347
        if err != nil {
2✔
UNCOV
1348
                log.Errorf("Unable to get tx %v from sweeper store: %v",
×
UNCOV
1349
                        txid, err)
×
UNCOV
1350

×
UNCOV
1351
                return fn.None[RBFInfo]()
×
UNCOV
1352
        }
×
1353

1354
        // Prepare the fee info and return it.
1355
        rbf := fn.Some(RBFInfo{
2✔
1356
                Txid:    txid,
2✔
1357
                Fee:     btcutil.Amount(tr.Fee),
2✔
1358
                FeeRate: chainfee.SatPerKWeight(tr.FeeRate),
2✔
1359
        })
2✔
1360

2✔
1361
        return rbf
2✔
1362
}
1363

1364
// handleExistingInput processes an input that is already known to the sweeper.
1365
// It will overwrite the params of the old input with the new ones.
1366
func (s *UtxoSweeper) handleExistingInput(input *sweepInputMessage,
1367
        oldInput *SweeperInput) {
3✔
1368

3✔
1369
        // Before updating the input details, check if an exclusive group was
3✔
1370
        // set. In case the same input is registered again without an exclusive
3✔
1371
        // group set, the previous input and its sweep parameters are outdated
3✔
1372
        // hence need to be replaced. This scenario currently only happens for
3✔
1373
        // anchor outputs. When a channel is force closed, in the worst case 3
3✔
1374
        // different sweeps with the same exclusive group are registered with
3✔
1375
        // the sweeper to bump the closing transaction (cpfp) when its time
3✔
1376
        // critical. Receiving an input which was already registered with the
3✔
1377
        // sweeper but now without an exclusive group means non of the previous
3✔
1378
        // inputs were used as CPFP, so we need to make sure we update the
3✔
1379
        // sweep parameters but also remove all inputs with the same exclusive
3✔
1380
        // group because the are outdated too.
3✔
1381
        var prevExclGroup *uint64
3✔
1382
        if oldInput.params.ExclusiveGroup != nil &&
3✔
1383
                input.params.ExclusiveGroup == nil {
6✔
1384

3✔
1385
                prevExclGroup = new(uint64)
3✔
1386
                *prevExclGroup = *oldInput.params.ExclusiveGroup
3✔
1387
        }
3✔
1388

1389
        // Update input details and sweep parameters. The re-offered input
1390
        // details may contain a change to the unconfirmed parent tx info.
1391
        oldInput.params = input.params
3✔
1392
        oldInput.Input = input.input
3✔
1393

3✔
1394
        // If the new input specifies a deadline, update the deadline height.
3✔
1395
        oldInput.DeadlineHeight = input.params.DeadlineHeight.UnwrapOr(
3✔
1396
                oldInput.DeadlineHeight,
3✔
1397
        )
3✔
1398

3✔
1399
        // Add additional result channel to signal spend of this input.
3✔
1400
        oldInput.listeners = append(oldInput.listeners, input.resultChan)
3✔
1401

3✔
1402
        if prevExclGroup != nil {
6✔
1403
                s.removeExclusiveGroup(*prevExclGroup)
3✔
1404
        }
3✔
1405
}
1406

1407
// handleInputSpent takes a spend event of our input and updates the sweeper's
1408
// internal state to remove the input.
1409
func (s *UtxoSweeper) handleInputSpent(spend *chainntnfs.SpendDetail) {
3✔
1410
        // Query store to find out if we ever published this tx.
3✔
1411
        spendHash := *spend.SpenderTxHash
3✔
1412
        isOurTx := s.cfg.Store.IsOurTx(spendHash)
3✔
1413

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

1428
                log.Debugf("Attempting to remove descendant txns invalidated "+
3✔
1429
                        "by (txid=%v): %v", spendingTx.TxHash(),
3✔
1430
                        spew.Sdump(spendingTx))
3✔
1431

3✔
1432
                err := s.removeConflictSweepDescendants(inputsSpent)
3✔
1433
                if err != nil {
6✔
1434
                        log.Warnf("unable to remove descendant transactions "+
3✔
1435
                                "due to tx %v: ", spendHash)
3✔
1436
                }
3✔
1437

1438
                log.Debugf("Detected third party spend related to in flight "+
3✔
1439
                        "inputs (is_ours=%v): %v", isOurTx,
3✔
1440
                        lnutils.SpewLogClosure(spend.SpendingTx))
3✔
1441
        }
1442

1443
        // We now use the spending tx to update the state of the inputs.
1444
        s.markInputsSwept(spend.SpendingTx, isOurTx)
3✔
1445
}
1446

1447
// markInputsSwept marks all inputs swept by the spending transaction as swept.
1448
// It will also notify all the subscribers of this input.
1449
func (s *UtxoSweeper) markInputsSwept(tx *wire.MsgTx, isOurTx bool) {
3✔
1450
        for _, txIn := range tx.TxIn {
6✔
1451
                outpoint := txIn.PreviousOutPoint
3✔
1452

3✔
1453
                // Check if this input is known to us. It could probably be
3✔
1454
                // unknown if we canceled the registration, deleted from inputs
3✔
1455
                // map but the ntfn was in-flight already. Or this could be not
3✔
1456
                // one of our inputs.
3✔
1457
                input, ok := s.inputs[outpoint]
3✔
1458
                if !ok {
6✔
1459
                        // It's very likely that a spending tx contains inputs
3✔
1460
                        // that we don't know.
3✔
1461
                        log.Tracef("Skipped marking input as swept: %v not "+
3✔
1462
                                "found in pending inputs", outpoint)
3✔
1463

3✔
1464
                        continue
3✔
1465
                }
1466

1467
                // This input may already been marked as swept by a previous
1468
                // spend notification, which is likely to happen as one sweep
1469
                // transaction usually sweeps multiple inputs.
1470
                if input.terminated() {
3✔
UNCOV
1471
                        log.Debugf("Skipped marking input as swept: %v "+
×
UNCOV
1472
                                "state=%v", outpoint, input.state)
×
UNCOV
1473

×
UNCOV
1474
                        continue
×
1475
                }
1476

1477
                input.state = Swept
3✔
1478

3✔
1479
                // Return either a nil or a remote spend result.
3✔
1480
                var err error
3✔
1481
                if !isOurTx {
6✔
1482
                        log.Warnf("Input=%v was spent by remote or third "+
3✔
1483
                                "party in tx=%v", outpoint, tx.TxHash())
3✔
1484
                        err = ErrRemoteSpend
3✔
1485
                }
3✔
1486

1487
                // Signal result channels.
1488
                s.signalResult(input, Result{
3✔
1489
                        Tx:  tx,
3✔
1490
                        Err: err,
3✔
1491
                })
3✔
1492

3✔
1493
                // Remove all other inputs in this exclusive group.
3✔
1494
                if input.params.ExclusiveGroup != nil {
6✔
1495
                        s.removeExclusiveGroup(*input.params.ExclusiveGroup)
3✔
1496
                }
3✔
1497
        }
1498
}
1499

1500
// markInputFatal marks the given input as fatal and won't be retried. It
1501
// will also notify all the subscribers of this input.
1502
func (s *UtxoSweeper) markInputFatal(pi *SweeperInput, tx *wire.MsgTx,
1503
        err error) {
2✔
1504

2✔
1505
        log.Errorf("Failed to sweep input: %v, error: %v", pi, err)
2✔
1506

2✔
1507
        pi.state = Fatal
2✔
1508

2✔
1509
        s.signalResult(pi, Result{
2✔
1510
                Tx:  tx,
2✔
1511
                Err: err,
2✔
1512
        })
2✔
1513
}
2✔
1514

1515
// updateSweeperInputs updates the sweeper's internal state and returns a map
1516
// of inputs to be swept. It will remove the inputs that are in final states,
1517
// and returns a map of inputs that have either state Init or PublishFailed.
1518
func (s *UtxoSweeper) updateSweeperInputs() InputsMap {
3✔
1519
        // Create a map of inputs to be swept.
3✔
1520
        inputs := make(InputsMap)
3✔
1521

3✔
1522
        // Iterate the pending inputs and update the sweeper's state.
3✔
1523
        //
3✔
1524
        // TODO(yy): sweeper is made to communicate via go channels, so no
3✔
1525
        // locks are needed to access the map. However, it'd be safer if we
3✔
1526
        // turn this inputs map into a SyncMap in case we wanna add concurrent
3✔
1527
        // access to the map in the future.
3✔
1528
        for op, input := range s.inputs {
6✔
1529
                log.Tracef("Checking input: %s, state=%v", input, input.state)
3✔
1530

3✔
1531
                // If the input has reached a final state, that it's either
3✔
1532
                // been swept, or failed, or excluded, we will remove it from
3✔
1533
                // our sweeper.
3✔
1534
                if input.terminated() {
6✔
1535
                        log.Debugf("Removing input(State=%v) %v from sweeper",
3✔
1536
                                input.state, op)
3✔
1537

3✔
1538
                        delete(s.inputs, op)
3✔
1539

3✔
1540
                        continue
3✔
1541
                }
1542

1543
                // If this input has been included in a sweep tx that's not
1544
                // published yet, we'd skip this input and wait for the sweep
1545
                // tx to be published.
1546
                if input.state == PendingPublish {
6✔
1547
                        continue
3✔
1548
                }
1549

1550
                // If this input has already been published, we will need to
1551
                // check the RBF condition before attempting another sweeping.
1552
                if input.state == Published {
6✔
1553
                        continue
3✔
1554
                }
1555

1556
                // If the input has a locktime that's not yet reached, we will
1557
                // skip this input and wait for the locktime to be reached.
1558
                mature, _ := input.isMature(uint32(s.currentHeight))
3✔
1559
                if !mature {
6✔
1560
                        continue
3✔
1561
                }
1562

1563
                // If this input is new or has been failed to be published,
1564
                // we'd retry it. The assumption here is that when an error is
1565
                // returned from `PublishTransaction`, it means the tx has
1566
                // failed to meet the policy, hence it's not in the mempool.
1567
                inputs[op] = input
3✔
1568
        }
1569

1570
        return inputs
3✔
1571
}
1572

1573
// sweepPendingInputs is called when the ticker fires. It will create clusters
1574
// and attempt to create and publish the sweeping transactions.
1575
func (s *UtxoSweeper) sweepPendingInputs(inputs InputsMap) {
3✔
1576
        log.Debugf("Sweeping %v inputs", len(inputs))
3✔
1577

3✔
1578
        // Cluster all of our inputs based on the specific Aggregator.
3✔
1579
        sets := s.cfg.Aggregator.ClusterInputs(inputs)
3✔
1580

3✔
1581
        // sweepWithLock is a helper closure that executes the sweep within a
3✔
1582
        // coin select lock to prevent the coins being selected for other
3✔
1583
        // transactions like funding of a channel.
3✔
1584
        sweepWithLock := func(set InputSet) error {
6✔
1585
                return s.cfg.Wallet.WithCoinSelectLock(func() error {
6✔
1586
                        // Try to add inputs from our wallet.
3✔
1587
                        err := set.AddWalletInputs(s.cfg.Wallet)
3✔
1588
                        if err != nil {
6✔
1589
                                return err
3✔
1590
                        }
3✔
1591

1592
                        // Create sweeping transaction for each set.
1593
                        err = s.sweep(set)
3✔
1594
                        if err != nil {
3✔
1595
                                return err
×
1596
                        }
×
1597

1598
                        return nil
3✔
1599
                })
1600
        }
1601

1602
        for _, set := range sets {
6✔
1603
                var err error
3✔
1604
                if set.NeedWalletInput() {
6✔
1605
                        // Sweep the set of inputs that need the wallet inputs.
3✔
1606
                        err = sweepWithLock(set)
3✔
1607
                } else {
6✔
1608
                        // Sweep the set of inputs that don't need the wallet
3✔
1609
                        // inputs.
3✔
1610
                        err = s.sweep(set)
3✔
1611
                }
3✔
1612

1613
                if err != nil {
6✔
1614
                        log.Errorf("Failed to sweep %v: %v", set, err)
3✔
1615
                }
3✔
1616
        }
1617
}
1618

1619
// bumpResp wraps the result of a bump attempt returned from the fee bumper and
1620
// the inputs being used.
1621
type bumpResp struct {
1622
        // result is the result of the bump attempt returned from the fee
1623
        // bumper.
1624
        result *BumpResult
1625

1626
        // set is the input set that was used in the bump attempt.
1627
        set InputSet
1628
}
1629

1630
// monitorFeeBumpResult subscribes to the passed result chan to listen for
1631
// future updates about the sweeping tx.
1632
//
1633
// NOTE: must run as a goroutine.
1634
func (s *UtxoSweeper) monitorFeeBumpResult(set InputSet,
1635
        resultChan <-chan *BumpResult) {
3✔
1636

3✔
1637
        defer s.wg.Done()
3✔
1638

3✔
1639
        for {
6✔
1640
                select {
3✔
1641
                case r := <-resultChan:
3✔
1642
                        // Validate the result is valid.
3✔
1643
                        if err := r.Validate(); err != nil {
3✔
1644
                                log.Errorf("Received invalid result: %v", err)
×
1645
                                continue
×
1646
                        }
1647

1648
                        resp := &bumpResp{
3✔
1649
                                result: r,
3✔
1650
                                set:    set,
3✔
1651
                        }
3✔
1652

3✔
1653
                        // Send the result back to the main event loop.
3✔
1654
                        select {
3✔
1655
                        case s.bumpRespChan <- resp:
3✔
1656
                        case <-s.quit:
×
1657
                                log.Debug("Sweeper shutting down, skip " +
×
1658
                                        "sending bump result")
×
1659

×
1660
                                return
×
1661
                        }
1662

1663
                        // The sweeping tx has been confirmed, we can exit the
1664
                        // monitor now.
1665
                        //
1666
                        // TODO(yy): can instead remove the spend subscription
1667
                        // in sweeper and rely solely on this event to mark
1668
                        // inputs as Swept?
1669
                        if r.Event == TxConfirmed || r.Event == TxFailed {
6✔
1670
                                // Exit if the tx is failed to be created.
3✔
1671
                                if r.Tx == nil {
6✔
1672
                                        log.Debugf("Received %v for nil tx, "+
3✔
1673
                                                "exit monitor", r.Event)
3✔
1674

3✔
1675
                                        return
3✔
1676
                                }
3✔
1677

1678
                                log.Debugf("Received %v for sweep tx %v, exit "+
3✔
1679
                                        "fee bump monitor", r.Event,
3✔
1680
                                        r.Tx.TxHash())
3✔
1681

3✔
1682
                                // Cancel the rebroadcasting of the failed tx.
3✔
1683
                                s.cfg.Wallet.CancelRebroadcast(r.Tx.TxHash())
3✔
1684

3✔
1685
                                return
3✔
1686
                        }
1687

1688
                case <-s.quit:
3✔
1689
                        log.Debugf("Sweeper shutting down, exit fee " +
3✔
1690
                                "bump handler")
3✔
1691

3✔
1692
                        return
3✔
1693
                }
1694
        }
1695
}
1696

1697
// handleBumpEventTxFailed handles the case where the tx has been failed to
1698
// publish.
1699
func (s *UtxoSweeper) handleBumpEventTxFailed(resp *bumpResp) {
3✔
1700
        r := resp.result
3✔
1701
        tx, err := r.Tx, r.Err
3✔
1702

3✔
1703
        if tx != nil {
6✔
1704
                log.Warnf("Fee bump attempt failed for tx=%v: %v", tx.TxHash(),
3✔
1705
                        err)
3✔
1706
        }
3✔
1707

1708
        // NOTE: When marking the inputs as failed, we are using the input set
1709
        // instead of the inputs found in the tx. This is fine for current
1710
        // version of the sweeper because we always create a tx using ALL of
1711
        // the inputs specified by the set.
1712
        //
1713
        // TODO(yy): should we also remove the failed tx from db?
1714
        s.markInputsPublishFailed(resp.set, resp.result.FeeRate)
3✔
1715
}
1716

1717
// handleBumpEventTxReplaced handles the case where the sweeping tx has been
1718
// replaced by a new one.
1719
func (s *UtxoSweeper) handleBumpEventTxReplaced(resp *bumpResp) error {
3✔
1720
        r := resp.result
3✔
1721
        oldTx := r.ReplacedTx
3✔
1722
        newTx := r.Tx
3✔
1723

3✔
1724
        // Prepare a new record to replace the old one.
3✔
1725
        tr := &TxRecord{
3✔
1726
                Txid:    newTx.TxHash(),
3✔
1727
                FeeRate: uint64(r.FeeRate),
3✔
1728
                Fee:     uint64(r.Fee),
3✔
1729
        }
3✔
1730

3✔
1731
        // Get the old record for logging purpose.
3✔
1732
        oldTxid := oldTx.TxHash()
3✔
1733
        record, err := s.cfg.Store.GetTx(oldTxid)
3✔
1734
        if err != nil {
6✔
1735
                log.Errorf("Fetch tx record for %v: %v", oldTxid, err)
3✔
1736
                return err
3✔
1737
        }
3✔
1738

1739
        // Cancel the rebroadcasting of the replaced tx.
1740
        s.cfg.Wallet.CancelRebroadcast(oldTxid)
3✔
1741

3✔
1742
        log.Infof("RBFed tx=%v(fee=%v sats, feerate=%v sats/kw) with new "+
3✔
1743
                "tx=%v(fee=%v sats, feerate=%v sats/kw)", record.Txid,
3✔
1744
                record.Fee, record.FeeRate, tr.Txid, tr.Fee, tr.FeeRate)
3✔
1745

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

1759
        // Mark the inputs as published using the replacing tx.
1760
        return s.markInputsPublished(tr, resp.set)
3✔
1761
}
1762

1763
// handleBumpEventTxPublished handles the case where the sweeping tx has been
1764
// successfully published.
1765
func (s *UtxoSweeper) handleBumpEventTxPublished(resp *bumpResp) error {
3✔
1766
        r := resp.result
3✔
1767
        tx := r.Tx
3✔
1768
        tr := &TxRecord{
3✔
1769
                Txid:    tx.TxHash(),
3✔
1770
                FeeRate: uint64(r.FeeRate),
3✔
1771
                Fee:     uint64(r.Fee),
3✔
1772
        }
3✔
1773

3✔
1774
        // Inputs have been successfully published so we update their
3✔
1775
        // states.
3✔
1776
        err := s.markInputsPublished(tr, resp.set)
3✔
1777
        if err != nil {
3✔
1778
                return err
×
1779
        }
×
1780

1781
        log.Debugf("Published sweep tx %v, num_inputs=%v, height=%v",
3✔
1782
                tx.TxHash(), len(tx.TxIn), s.currentHeight)
3✔
1783

3✔
1784
        // If there's no error, remove the output script. Otherwise keep it so
3✔
1785
        // that it can be reused for the next transaction and causes no address
3✔
1786
        // inflation.
3✔
1787
        s.currentOutputScript = fn.None[lnwallet.AddrWithKey]()
3✔
1788

3✔
1789
        return nil
3✔
1790
}
1791

1792
// handleBumpEventTxFatal handles the case where there's an unexpected error
1793
// when creating or publishing the sweeping tx. In this case, the tx will be
1794
// removed from the sweeper store and the inputs will be marked as `Failed`,
1795
// which means they will not be retried.
1796
func (s *UtxoSweeper) handleBumpEventTxFatal(resp *bumpResp) error {
2✔
1797
        r := resp.result
2✔
1798

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

2✔
1805
                // Remove the tx from the sweeper db if it exists.
2✔
1806
                if err := s.cfg.Store.DeleteTx(txid); err != nil {
2✔
UNCOV
1807
                        return fmt.Errorf("delete tx record for %v: %w", txid,
×
UNCOV
1808
                                err)
×
UNCOV
1809
                }
×
1810
        }
1811

1812
        // Mark the inputs as fatal.
1813
        s.markInputsFatal(resp.set, r.Err)
2✔
1814

2✔
1815
        return nil
2✔
1816
}
1817

1818
// markInputsFatal  marks all inputs in the input set as failed. It will also
1819
// notify all the subscribers of these inputs.
1820
func (s *UtxoSweeper) markInputsFatal(set InputSet, err error) {
2✔
1821
        for _, inp := range set.Inputs() {
4✔
1822
                outpoint := inp.OutPoint()
2✔
1823

2✔
1824
                input, ok := s.inputs[outpoint]
2✔
1825
                if !ok {
4✔
1826
                        // It's very likely that a spending tx contains inputs
2✔
1827
                        // that we don't know.
2✔
1828
                        log.Tracef("Skipped marking input as failed: %v not "+
2✔
1829
                                "found in pending inputs", outpoint)
2✔
1830

2✔
1831
                        continue
2✔
1832
                }
1833

1834
                // If the input is already in a terminal state, we don't want
1835
                // to rewrite it, which also indicates an error as we only get
1836
                // an error event during the initial broadcast.
1837
                if input.terminated() {
2✔
UNCOV
1838
                        log.Errorf("Skipped marking input=%v as failed due to "+
×
UNCOV
1839
                                "unexpected state=%v", outpoint, input.state)
×
UNCOV
1840

×
UNCOV
1841
                        continue
×
1842
                }
1843

1844
                s.markInputFatal(input, nil, err)
2✔
1845
        }
1846
}
1847

1848
// handleBumpEvent handles the result sent from the bumper based on its event
1849
// type.
1850
//
1851
// NOTE: TxConfirmed event is not handled, since we already subscribe to the
1852
// input's spending event, we don't need to do anything here.
1853
func (s *UtxoSweeper) handleBumpEvent(r *bumpResp) error {
3✔
1854
        log.Debugf("Received bump result %v", r.result)
3✔
1855

3✔
1856
        switch r.result.Event {
3✔
1857
        // The tx has been published, we update the inputs' state and create a
1858
        // record to be stored in the sweeper db.
1859
        case TxPublished:
3✔
1860
                return s.handleBumpEventTxPublished(r)
3✔
1861

1862
        // The tx has failed, we update the inputs' state.
1863
        case TxFailed:
3✔
1864
                s.handleBumpEventTxFailed(r)
3✔
1865
                return nil
3✔
1866

1867
        // The tx has been replaced, we will remove the old tx and replace it
1868
        // with the new one.
1869
        case TxReplaced:
3✔
1870
                return s.handleBumpEventTxReplaced(r)
3✔
1871

1872
        // There are inputs being spent in a tx which the fee bumper doesn't
1873
        // understand. We will remove the tx from the sweeper db and mark the
1874
        // inputs as swept.
1875
        case TxUnknownSpend:
3✔
1876
                s.handleBumpEventTxUnknownSpend(r)
3✔
1877

1878
        // There's a fatal error in creating the tx, we will remove the tx from
1879
        // the sweeper db and mark the inputs as failed.
1880
        case TxFatal:
2✔
1881
                return s.handleBumpEventTxFatal(r)
2✔
1882
        }
1883

1884
        return nil
3✔
1885
}
1886

1887
// IsSweeperOutpoint determines whether the outpoint was created by the sweeper.
1888
//
1889
// NOTE: It is enough to check the txid because the sweeper will create
1890
// outpoints which solely belong to the internal LND wallet.
1891
func (s *UtxoSweeper) IsSweeperOutpoint(op wire.OutPoint) bool {
3✔
1892
        return s.cfg.Store.IsOurTx(op.Hash)
3✔
1893
}
3✔
1894

1895
// markInputSwept marks the given input as swept by the tx. It will also notify
1896
// all the subscribers of this input.
UNCOV
1897
func (s *UtxoSweeper) markInputSwept(inp *SweeperInput, tx *wire.MsgTx) {
×
UNCOV
1898
        log.Debugf("Marking input as swept: %v from state=%v", inp.OutPoint(),
×
UNCOV
1899
                inp.state)
×
UNCOV
1900

×
UNCOV
1901
        inp.state = Swept
×
UNCOV
1902

×
UNCOV
1903
        // Signal result channels.
×
UNCOV
1904
        s.signalResult(inp, Result{
×
UNCOV
1905
                Tx: tx,
×
UNCOV
1906
        })
×
UNCOV
1907

×
UNCOV
1908
        // Remove all other inputs in this exclusive group.
×
UNCOV
1909
        if inp.params.ExclusiveGroup != nil {
×
1910
                s.removeExclusiveGroup(*inp.params.ExclusiveGroup)
×
1911
        }
×
1912
}
1913

1914
// handleUnknownSpendTx takes an input and its spending tx. If the spending tx
1915
// cannot be found in the sweeper store, the input will be marked as fatal,
1916
// otherwise it will be marked as swept.
UNCOV
1917
func (s *UtxoSweeper) handleUnknownSpendTx(inp *SweeperInput, tx *wire.MsgTx) {
×
UNCOV
1918
        op := inp.OutPoint()
×
UNCOV
1919
        txid := tx.TxHash()
×
UNCOV
1920

×
UNCOV
1921
        isOurTx := s.cfg.Store.IsOurTx(txid)
×
UNCOV
1922

×
UNCOV
1923
        // If this is our tx, it means it's a previous sweeping tx that got
×
UNCOV
1924
        // confirmed, which could happen when a restart happens during the
×
UNCOV
1925
        // sweeping process.
×
UNCOV
1926
        if isOurTx {
×
UNCOV
1927
                log.Debugf("Found our sweeping tx %v, marking input %v as "+
×
UNCOV
1928
                        "swept", txid, op)
×
UNCOV
1929

×
UNCOV
1930
                // We now use the spending tx to update the state of the inputs.
×
UNCOV
1931
                s.markInputSwept(inp, tx)
×
UNCOV
1932

×
UNCOV
1933
                return
×
UNCOV
1934
        }
×
1935

1936
        // Since the input is spent by others, we now mark it as fatal and won't
1937
        // be retried.
UNCOV
1938
        s.markInputFatal(inp, tx, ErrRemoteSpend)
×
UNCOV
1939

×
UNCOV
1940
        log.Debugf("Removing descendant txns invalidated by (txid=%v): %v",
×
UNCOV
1941
                txid, lnutils.SpewLogClosure(tx))
×
UNCOV
1942

×
UNCOV
1943
        // Construct a map of the inputs this transaction spends.
×
UNCOV
1944
        spentInputs := make(map[wire.OutPoint]struct{}, len(tx.TxIn))
×
UNCOV
1945
        for _, txIn := range tx.TxIn {
×
UNCOV
1946
                spentInputs[txIn.PreviousOutPoint] = struct{}{}
×
UNCOV
1947
        }
×
1948

UNCOV
1949
        err := s.removeConflictSweepDescendants(spentInputs)
×
UNCOV
1950
        if err != nil {
×
1951
                log.Warnf("unable to remove descendant transactions "+
×
1952
                        "due to tx %v: ", txid)
×
1953
        }
×
1954
}
1955

1956
// handleBumpEventTxUnknownSpend handles the case where the confirmed tx is
1957
// unknown to the fee bumper. In the case when the sweeping tx has been replaced
1958
// by another party with their tx being confirmed. It will retry sweeping the
1959
// "good" inputs once the "bad" ones are kicked out.
1960
func (s *UtxoSweeper) handleBumpEventTxUnknownSpend(r *bumpResp) {
3✔
1961
        // Mark the inputs as publish failed, which means they will be retried
3✔
1962
        // later.
3✔
1963
        s.markInputsPublishFailed(r.set, r.result.FeeRate)
3✔
1964

3✔
1965
        // Get all the inputs that are not spent in the current sweeping tx.
3✔
1966
        spentInputs := r.result.SpentInputs
3✔
1967

3✔
1968
        // Create a slice to track inputs to be retried.
3✔
1969
        inputsToRetry := make([]input.Input, 0, len(r.set.Inputs()))
3✔
1970

3✔
1971
        // Iterate all the inputs found in this bump and mark the ones spent by
3✔
1972
        // the third party as failed. The rest of inputs will then be updated
3✔
1973
        // with a new fee rate and be retried immediately.
3✔
1974
        for _, inp := range r.set.Inputs() {
6✔
1975
                op := inp.OutPoint()
3✔
1976
                input, ok := s.inputs[op]
3✔
1977

3✔
1978
                // Wallet inputs are not tracked so we will not find them from
3✔
1979
                // the inputs map.
3✔
1980
                if !ok {
6✔
1981
                        log.Debugf("Skipped marking input: %v not found in "+
3✔
1982
                                "pending inputs", op)
3✔
1983

3✔
1984
                        continue
3✔
1985
                }
1986

1987
                // Check whether this input has been spent, if so we mark it as
1988
                // fatal or swept based on whether this is one of our previous
1989
                // sweeping txns, then move to the next.
1990
                tx, spent := spentInputs[op]
3✔
1991
                if spent {
3✔
UNCOV
1992
                        s.handleUnknownSpendTx(input, tx)
×
UNCOV
1993

×
UNCOV
1994
                        continue
×
1995
                }
1996

1997
                log.Debugf("Input(%v): updating params: immediate [%v -> true]",
3✔
1998
                        op, r.result.FeeRate, input.params.Immediate)
3✔
1999

3✔
2000
                input.params.Immediate = true
3✔
2001
                inputsToRetry = append(inputsToRetry, input)
3✔
2002
        }
2003

2004
        // Exit early if there are no inputs to be retried.
2005
        if len(inputsToRetry) == 0 {
6✔
2006
                return
3✔
2007
        }
3✔
2008

2009
        log.Debugf("Retry sweeping inputs with updated params: %v",
3✔
2010
                inputTypeSummary(inputsToRetry))
3✔
2011

3✔
2012
        // Get the latest inputs, which should put the PublishFailed inputs back
3✔
2013
        // to the sweeping queue.
3✔
2014
        inputs := s.updateSweeperInputs()
3✔
2015

3✔
2016
        // Immediately sweep the remaining inputs - the previous inputs should
3✔
2017
        // now be swept with the updated StartingFeeRate immediately. We may
3✔
2018
        // also include more inputs in the new sweeping tx if new ones with the
3✔
2019
        // same deadline are offered.
3✔
2020
        s.sweepPendingInputs(inputs)
3✔
2021
}
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