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

lightningnetwork / lnd / 14471480810

15 Apr 2025 02:05PM UTC coverage: 58.611% (-10.5%) from 69.088%
14471480810

Pull #9702

github

web-flow
Merge 811aac3b1 into 014706cc3
Pull Request #9702: multi: make payment address mandatory

2 of 4 new or added lines in 1 file covered. (50.0%)

28451 existing lines in 450 files now uncovered.

97194 of 165828 relevant lines covered (58.61%)

1.82 hits per line

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

87.01
/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

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

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

325
// UtxoSweeper is responsible for sweeping outputs back into the wallet
326
type UtxoSweeper struct {
327
        started uint32 // To be used atomically.
328
        stopped uint32 // To be used atomically.
329

330
        // Embed the blockbeat consumer struct to get access to the method
331
        // `NotifyBlockProcessed` and the `BlockbeatChan`.
332
        chainio.BeatConsumer
333

334
        cfg *UtxoSweeperConfig
335

336
        newInputs chan *sweepInputMessage
337
        spendChan chan *chainntnfs.SpendDetail
338

339
        // pendingSweepsReq is a channel that will be sent requests by external
340
        // callers in order to retrieve the set of pending inputs the
341
        // UtxoSweeper is attempting to sweep.
342
        pendingSweepsReqs chan *pendingSweepsReq
343

344
        // updateReqs is a channel that will be sent requests by external
345
        // callers who wish to bump the fee rate of a given input.
346
        updateReqs chan *updateReq
347

348
        // inputs is the total set of inputs the UtxoSweeper has been requested
349
        // to sweep.
350
        inputs InputsMap
351

352
        currentOutputScript fn.Option[lnwallet.AddrWithKey]
353

354
        relayFeeRate chainfee.SatPerKWeight
355

356
        quit chan struct{}
357
        wg   sync.WaitGroup
358

359
        // currentHeight is the best known height of the main chain. This is
360
        // updated whenever a new block epoch is received.
361
        currentHeight int32
362

363
        // bumpRespChan is a channel that receives broadcast results from the
364
        // TxPublisher.
365
        bumpRespChan chan *bumpResp
366
}
367

368
// Compile-time check for the chainio.Consumer interface.
369
var _ chainio.Consumer = (*UtxoSweeper)(nil)
370

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

377
        // FeeEstimator is used when crafting sweep transactions to estimate
378
        // the necessary fee relative to the expected size of the sweep
379
        // transaction.
380
        FeeEstimator chainfee.Estimator
381

382
        // Wallet contains the wallet functions that sweeper requires.
383
        Wallet Wallet
384

385
        // Notifier is an instance of a chain notifier we'll use to watch for
386
        // certain on-chain events.
387
        Notifier chainntnfs.ChainNotifier
388

389
        // Mempool is the mempool watcher that will be used to query whether a
390
        // given input is already being spent by a transaction in the mempool.
391
        Mempool chainntnfs.MempoolWatcher
392

393
        // Store stores the published sweeper txes.
394
        Store SweeperStore
395

396
        // Signer is used by the sweeper to generate valid witnesses at the
397
        // time the incubated outputs need to be spent.
398
        Signer input.Signer
399

400
        // MaxInputsPerTx specifies the default maximum number of inputs allowed
401
        // in a single sweep tx. If more need to be swept, multiple txes are
402
        // created and published.
403
        MaxInputsPerTx uint32
404

405
        // MaxFeeRate is the maximum fee rate allowed within the UtxoSweeper.
406
        MaxFeeRate chainfee.SatPerVByte
407

408
        // Aggregator is used to group inputs into clusters based on its
409
        // implemention-specific strategy.
410
        Aggregator UtxoAggregator
411

412
        // Publisher is used to publish the sweep tx crafted here and monitors
413
        // it for potential fee bumps.
414
        Publisher Bumper
415

416
        // NoDeadlineConfTarget is the conf target to use when sweeping
417
        // non-time-sensitive outputs.
418
        NoDeadlineConfTarget uint32
419
}
420

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

430
        // Tx is the transaction that spent the input.
431
        Tx *wire.MsgTx
432
}
433

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

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

3✔
455
        // Mount the block consumer.
3✔
456
        s.BeatConsumer = chainio.NewBeatConsumer(s.quit, s.Name())
3✔
457

3✔
458
        return s
3✔
459
}
3✔
460

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

467
        log.Info("Sweeper starting")
3✔
468

3✔
469
        // Retrieve relay fee for dust limit calculation. Assume that this will
3✔
470
        // not change from here on.
3✔
471
        s.relayFeeRate = s.cfg.FeeEstimator.RelayFeePerKW()
3✔
472

3✔
473
        // Set the current height.
3✔
474
        s.currentHeight = beat.Height()
3✔
475

3✔
476
        // Start sweeper main loop.
3✔
477
        s.wg.Add(1)
3✔
478
        go s.collector()
3✔
479

3✔
480
        return nil
3✔
481
}
482

483
// RelayFeePerKW returns the minimum fee rate required for transactions to be
484
// relayed.
485
func (s *UtxoSweeper) RelayFeePerKW() chainfee.SatPerKWeight {
×
486
        return s.relayFeeRate
×
487
}
×
488

489
// Stop stops sweeper from listening to block epochs and constructing sweep
490
// txes.
491
func (s *UtxoSweeper) Stop() error {
3✔
492
        if !atomic.CompareAndSwapUint32(&s.stopped, 0, 1) {
3✔
493
                return nil
×
494
        }
×
495

496
        log.Info("Sweeper shutting down...")
3✔
497
        defer log.Debug("Sweeper shutdown complete")
3✔
498

3✔
499
        close(s.quit)
3✔
500
        s.wg.Wait()
3✔
501

3✔
502
        return nil
3✔
503
}
504

505
// NOTE: part of the `chainio.Consumer` interface.
506
func (s *UtxoSweeper) Name() string {
3✔
507
        return "UtxoSweeper"
3✔
508
}
3✔
509

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

3✔
525
        if inp == nil || inp.OutPoint() == input.EmptyOutPoint ||
3✔
526
                inp.SignDesc() == nil {
3✔
527

×
528
                return nil, errors.New("nil input received")
×
529
        }
×
530

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

3✔
539
        sweeperInput := &sweepInputMessage{
3✔
540
                input:      inp,
3✔
541
                params:     params,
3✔
542
                resultChan: make(chan Result, 1),
3✔
543
        }
3✔
544

3✔
545
        // Deliver input to the main event loop.
3✔
546
        select {
3✔
547
        case s.newInputs <- sweeperInput:
3✔
548
        case <-s.quit:
×
549
                return nil, ErrSweeperShuttingDown
×
550
        }
551

552
        return sweeperInput.resultChan, nil
3✔
553
}
554

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

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

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

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

606
                // Check to see if this past sweep transaction spent any of the
607
                // same inputs as spendingTx.
608
                var isConflicting bool
3✔
609
                for _, txIn := range sweepTx.TxIn {
6✔
610
                        if _, ok := outpoints[txIn.PreviousOutPoint]; ok {
6✔
611
                                isConflicting = true
3✔
612
                                break
3✔
613
                        }
614
                }
615

616
                if !isConflicting {
6✔
617
                        continue
3✔
618
                }
619

620
                // If it is conflicting, then we'll signal the wallet to remove
621
                // all the transactions that are descendants of outputs created
622
                // by the sweepTx and the sweepTx itself.
623
                log.Debugf("Removing sweep txid=%v from wallet: %v",
3✔
624
                        sweepTx.TxHash(), spew.Sdump(sweepTx))
3✔
625

3✔
626
                err = s.cfg.Wallet.RemoveDescendants(sweepTx)
3✔
627
                if err != nil {
3✔
628
                        log.Warnf("Unable to remove descendants: %v", err)
×
629
                }
×
630

631
                // If this transaction was conflicting, then we'll stop
632
                // rebroadcasting it in the background.
633
                s.cfg.Wallet.CancelRebroadcast(sweepHash)
3✔
634
        }
635

636
        return nil
3✔
637
}
638

639
// collector is the sweeper main loop. It processes new inputs, spend
640
// notifications and counts down to publication of the sweep tx.
641
func (s *UtxoSweeper) collector() {
3✔
642
        defer s.wg.Done()
3✔
643

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

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

×
661
                                return
×
662
                        }
×
663

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

677
                // A spend of one of our inputs is detected. Signal sweep
678
                // results to the caller(s).
679
                case spend := <-s.spendChan:
3✔
680
                        s.handleInputSpent(spend)
3✔
681

682
                // A new external request has been received to retrieve all of
683
                // the inputs we're currently attempting to sweep.
684
                case req := <-s.pendingSweepsReqs:
3✔
685
                        s.handlePendingSweepsReq(req)
3✔
686

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

3✔
696
                        // Perform an sweep immediately if asked.
3✔
697
                        if req.params.Immediate {
6✔
698
                                inputs := s.updateSweeperInputs()
3✔
699
                                s.sweepPendingInputs(inputs)
3✔
700
                        }
3✔
701

702
                case resp := <-s.bumpRespChan:
3✔
703
                        // Handle the bump event.
3✔
704
                        err := s.handleBumpEvent(resp)
3✔
705
                        if err != nil {
5✔
706
                                log.Errorf("Failed to handle bump event: %v",
2✔
707
                                        err)
2✔
708
                        }
2✔
709

710
                // A new block comes in, update the bestHeight, perform a check
711
                // over all pending inputs and publish sweeping txns if needed.
712
                case beat := <-s.BlockbeatChan:
3✔
713
                        // Update the sweeper to the best height.
3✔
714
                        s.currentHeight = beat.Height()
3✔
715

3✔
716
                        // Update the inputs with the latest height.
3✔
717
                        inputs := s.updateSweeperInputs()
3✔
718

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

726
                        // Attempt to sweep any pending inputs.
727
                        s.sweepPendingInputs(inputs)
3✔
728

3✔
729
                        // Notify we've processed the block.
3✔
730
                        s.NotifyBlockProcessed(beat, nil)
3✔
731

732
                case <-s.quit:
3✔
733
                        return
3✔
734
                }
735
        }
736
}
737

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

3✔
747
                // Skip inputs that aren't exclusive.
3✔
748
                if input.params.ExclusiveGroup == nil {
6✔
749
                        continue
3✔
750
                }
751

752
                // Skip inputs from other exclusive groups.
753
                if *input.params.ExclusiveGroup != group {
3✔
754
                        continue
×
755
                }
756

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

3✔
762
                        continue
3✔
763
                }
764

765
                // Signal result channels.
766
                s.signalResult(input, Result{
3✔
767
                        Err: ErrExclusiveGroupSpend,
3✔
768
                })
3✔
769

3✔
770
                // Update the input's state as it can no longer be swept.
3✔
771
                input.state = Excluded
3✔
772

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

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

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

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

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

3✔
813
                pi.ntfnRegCancel()
3✔
814
        }
3✔
815
}
816

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

3✔
828
                log.Debugf("Created sweep DeliveryAddress %x",
3✔
829
                        addr.DeliveryAddress)
3✔
830
        }
831

832
        sweepAddr, err := s.currentOutputScript.UnwrapOrErr(
3✔
833
                fmt.Errorf("none sweep script"),
3✔
834
        )
3✔
835
        if err != nil {
3✔
836
                return err
×
837
        }
×
838

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

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

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

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

3✔
868
        return nil
3✔
869
}
870

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

3✔
885
                        continue
3✔
886
                }
887

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

×
UNCOV
896
                        continue
×
897
                }
898

899
                // Update the input's state.
900
                pi.state = PendingPublish
3✔
901

3✔
902
                // Record another publish attempt.
3✔
903
                pi.publishAttempts++
3✔
904
        }
905
}
906

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

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

3✔
931
                        continue
3✔
932
                }
933

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

3✔
940
                        continue
3✔
941
                }
942

943
                // Update the input's state.
944
                pi.state = Published
3✔
945

3✔
946
                // Update the input's latest fee rate.
3✔
947
                pi.lastFeeRate = chainfee.SatPerKWeight(tr.FeeRate)
3✔
948
        }
949

950
        return nil
3✔
951
}
952

953
// markInputsPublishFailed marks the list of inputs as failed to be published.
954
func (s *UtxoSweeper) markInputsPublishFailed(set InputSet,
955
        feeRate chainfee.SatPerKWeight) {
3✔
956

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

3✔
968
                        continue
3✔
969
                }
970

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

×
UNCOV
976
                        continue
×
977
                }
978

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

3✔
981
                // Update the input's state.
3✔
982
                pi.state = PublishFailed
3✔
983

3✔
984
                log.Debugf("Input(%v): updating params: starting fee rate "+
3✔
985
                        "[%v -> %v]", op, pi.params.StartingFeeRate,
3✔
986
                        feeRate)
3✔
987

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

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

3✔
1000
        log.Tracef("Wait for spend of %v at heightHint=%v",
3✔
1001
                outpoint, heightHint)
3✔
1002

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

1010
        s.wg.Add(1)
3✔
1011
        go func() {
6✔
1012
                defer s.wg.Done()
3✔
1013

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

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

3✔
1024
                        select {
3✔
1025
                        case s.spendChan <- spend:
3✔
1026
                                log.Debugf("Delivered spend ntfn for %v",
3✔
1027
                                        outpoint)
3✔
1028

1029
                        case <-s.quit:
×
1030
                        }
1031
                case <-s.quit:
3✔
1032
                }
1033
        }()
1034

1035
        return spendEvent.Cancel, nil
3✔
1036
}
1037

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

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

1054
        select {
3✔
1055
        case pendingSweeps := <-respChan:
3✔
1056
                return pendingSweeps, nil
3✔
1057
        case err := <-errChan:
×
1058
                return nil, err
×
1059
        case <-s.quit:
×
1060
                return nil, ErrSweeperShuttingDown
×
1061
        }
1062
}
1063

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

3✔
1069
        resps := make(map[wire.OutPoint]*PendingInputResponse, len(s.inputs))
3✔
1070
        for _, inp := range s.inputs {
6✔
1071
                // Skip immature inputs for compatibility.
3✔
1072
                mature, _ := inp.isMature(uint32(s.currentHeight))
3✔
1073
                if !mature {
6✔
1074
                        continue
3✔
1075
                }
1076

1077
                // Only the exported fields are set, as we expect the response
1078
                // to only be consumed externally.
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
                }
3✔
1091
        }
1092

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

1100
        return resps
3✔
1101
}
1102

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

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

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

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

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

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

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

3✔
1171
        sweeperInput.params = newParams
3✔
1172

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

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

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

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

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

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

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

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

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

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

1229
        return defaultDeadline
3✔
1230
}
1231

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

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

3✔
1243
                return nil
3✔
1244
        }
3✔
1245

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

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

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

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

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

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

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

×
1291
                return err
×
1292
        }
×
1293

1294
        pi.ntfnRegCancel = cancel
3✔
1295

3✔
1296
        return nil
3✔
1297
}
1298

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

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

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

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

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

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

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

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

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

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

2✔
1360
        return rbf
2✔
1361
}
1362

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
1463
                        continue
3✔
1464
                }
1465

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

×
UNCOV
1473
                        continue
×
1474
                }
1475

1476
                input.state = Swept
3✔
1477

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

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

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

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

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

2✔
1506
        pi.state = Fatal
2✔
1507

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

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

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

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

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

3✔
1539
                        continue
3✔
1540
                }
1541

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

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

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

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

1569
        return inputs
3✔
1570
}
1571

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

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

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

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

1597
                        return nil
3✔
1598
                })
1599
        }
1600

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

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

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

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

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

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

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

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

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

×
1659
                                return
×
1660
                        }
1661

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

3✔
1674
                                        return
3✔
1675
                                }
3✔
1676

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

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

3✔
1684
                                return
3✔
1685
                        }
1686

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
1788
        return nil
3✔
1789
}
1790

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

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

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

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

2✔
1814
        return nil
2✔
1815
}
1816

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

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

2✔
1830
                        continue
2✔
1831
                }
1832

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

×
UNCOV
1840
                        continue
×
1841
                }
1842

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

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

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

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

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

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

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

1883
        return nil
3✔
1884
}
1885

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

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

×
UNCOV
1900
        inp.state = Swept
×
UNCOV
1901

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

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

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

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

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

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

×
UNCOV
1932
                return
×
UNCOV
1933
        }
×
1934

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

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

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

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

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

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

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

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

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

3✔
1983
                        continue
3✔
1984
                }
1985

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

×
UNCOV
1993
                        continue
×
1994
                }
1995

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

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

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

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

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

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