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

lightningnetwork / lnd / 17741595272

15 Sep 2025 05:34PM UTC coverage: 66.653% (+0.008%) from 66.645%
17741595272

Pull #10221

github

web-flow
Merge e7ff1981e into 6b279fb24
Pull Request #10221: Update bbolt + grpc dependencies

136302 of 204494 relevant lines covered (66.65%)

21378.23 hits per line

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

93.21
/sweep/sweeper.go
1
package sweep
2

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

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

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

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

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

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

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

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

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

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

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

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

71
// String returns a human readable interpretation of the sweep parameters.
72
func (p Params) String() string {
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 {
31✔
211
        return fmt.Sprintf("%v (%v)", p.Input.OutPoint(), p.Input.WitnessType())
31✔
212
}
31✔
213

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

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

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

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

254
        return true, locktime
6✔
255
}
256

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

338
        cfg *UtxoSweeperConfig
339

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

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

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

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

356
        currentOutputScript fn.Option[lnwallet.AddrWithKey]
357

358
        relayFeeRate chainfee.SatPerKWeight
359

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

23✔
462
        return s
23✔
463
}
23✔
464

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

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

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

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

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

3✔
484
        return nil
3✔
485
}
486

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

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

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

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

3✔
506
        return nil
3✔
507
}
508

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

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

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

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

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

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

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

556
        return sweeperInput.resultChan, nil
3✔
557
}
558

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

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

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

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

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

620
                if !isConflicting {
6✔
621
                        continue
3✔
622
                }
623

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

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

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

640
        return nil
4✔
641
}
642

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

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

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

×
665
                                return
×
666
                        }
×
667

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
756
                        continue
3✔
757
                }
758

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

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

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

×
774
                        continue
×
775
                }
776

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

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

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

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

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

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

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

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

3✔
827
                pi.ntfnRegCancel()
3✔
828
        }
3✔
829
}
830

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

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

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

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

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

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

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

5✔
882
        return nil
5✔
883
}
884

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

3✔
899
                        continue
3✔
900
                }
901

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

1✔
910
                        continue
1✔
911
                }
912

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

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

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

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

3✔
945
                        continue
3✔
946
                }
947

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

4✔
954
                        continue
4✔
955
                }
956

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

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

964
        return nil
6✔
965
}
966

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

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

3✔
982
                        continue
3✔
983
                }
984

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

5✔
990
                        continue
5✔
991
                }
992

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

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

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

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

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

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

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

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

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

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

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

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

1049
        return spendEvent.Cancel, nil
3✔
1050
}
1051

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

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

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

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

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

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

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

1111
        return resps
3✔
1112
}
1113

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

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

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

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

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

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

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

3✔
1182
        sweeperInput.params = newParams
3✔
1183

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

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

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

3✔
1198
        return resultChan, nil
3✔
1199
}
1200

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

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

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

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

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

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

1240
        return defaultDeadline
3✔
1241
}
1242

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

3✔
1252
                s.handleExistingInput(input, pi)
3✔
1253

3✔
1254
                return nil
3✔
1255
        }
3✔
1256

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

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

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

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

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

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

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

×
1302
                return err
×
1303
        }
×
1304

1305
        pi.ntfnRegCancel = cancel
3✔
1306

3✔
1307
        return nil
3✔
1308
}
1309

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

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

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

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

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

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

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

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

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

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

3✔
1371
        return rbf
3✔
1372
}
1373

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4✔
1471
                        continue
4✔
1472
                }
1473

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

1✔
1481
                        continue
1✔
1482
                }
1483

1484
                input.state = Swept
5✔
1485

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

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

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

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

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

8✔
1516
        pi.state = Fatal
8✔
1517

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

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

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

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

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

7✔
1549
                        continue
7✔
1550
                }
1551

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

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

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

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

1579
        return inputs
5✔
1580
}
1581

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

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

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

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

1607
                        return nil
4✔
1608
                })
1609
        }
1610

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

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

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

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

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

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

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

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

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

×
1669
                                return
×
1670
                        }
1671

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

3✔
1684
                                        return
3✔
1685
                                }
3✔
1686

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

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

5✔
1694
                                return
5✔
1695
                        }
1696

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4✔
1798
        return nil
4✔
1799
}
1800

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

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

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

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

3✔
1824
        return nil
3✔
1825
}
1826

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

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

2✔
1840
                        continue
2✔
1841
                }
1842

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

3✔
1850
                        continue
3✔
1851
                }
1852

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

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

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

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

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

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

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

1893
        return nil
3✔
1894
}
1895

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

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

3✔
1910
        inp.state = Swept
3✔
1911

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

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

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

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

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

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

3✔
1944
                return
3✔
1945
        }
3✔
1946

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

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

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

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

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

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

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

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

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

3✔
1995
                        continue
3✔
1996
                }
1997

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

2✔
2005
                        continue
2✔
2006
                }
2007

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

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

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

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

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

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

© 2025 Coveralls, Inc