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

lightningnetwork / lnd / 15858991938

24 Jun 2025 06:51PM UTC coverage: 55.808% (-2.4%) from 58.173%
15858991938

Pull #9148

github

web-flow
Merge 0e921d6a5 into 29ff13d83
Pull Request #9148: DynComms [2/n]: lnwire: add authenticated wire messages for Dyn*

232 of 267 new or added lines in 5 files covered. (86.89%)

24606 existing lines in 281 files now uncovered.

108380 of 194201 relevant lines covered (55.81%)

22488.12 hits per line

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

49.47
/sweep/sweeper.go
1
package sweep
2

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

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

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

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

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

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

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

46
// Params contains the parameters that control the sweeping process.
47
type Params struct {
48
        // ExclusiveGroup is an identifier that, if set, prevents other inputs
49
        // with the same identifier from being batched together.
50
        ExclusiveGroup *uint64
51

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

254
        return true, locktime
3✔
255
}
256

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

338
        cfg *UtxoSweeperConfig
339

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

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

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

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

356
        currentOutputScript fn.Option[lnwallet.AddrWithKey]
357

358
        relayFeeRate chainfee.SatPerKWeight
359

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
UNCOV
484
        return nil
×
485
}
486

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

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

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

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

×
UNCOV
506
        return nil
×
507
}
508

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

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

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

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

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

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

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

UNCOV
556
        return sweeperInput.resultChan, nil
×
557
}
558

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

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

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

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

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

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

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

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

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

640
        return nil
1✔
641
}
642

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

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

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

×
665
                                return
×
666
                        }
×
667

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
UNCOV
766
                        continue
×
767
                }
768

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

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

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

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

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

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

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

×
UNCOV
817
                pi.ntfnRegCancel()
×
UNCOV
818
        }
×
819
}
820

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

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

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

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

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

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

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

2✔
872
        return nil
2✔
873
}
874

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

×
UNCOV
889
                        continue
×
890
                }
891

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

1✔
900
                        continue
1✔
901
                }
902

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

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

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

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

×
UNCOV
935
                        continue
×
936
                }
937

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

1✔
944
                        continue
1✔
945
                }
946

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

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

954
        return nil
3✔
955
}
956

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

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

×
UNCOV
972
                        continue
×
973
                }
974

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

5✔
980
                        continue
5✔
981
                }
982

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

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

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

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

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

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

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

UNCOV
1014
        s.wg.Add(1)
×
UNCOV
1015
        go func() {
×
UNCOV
1016
                defer s.wg.Done()
×
UNCOV
1017

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

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

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

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

UNCOV
1039
        return spendEvent.Cancel, nil
×
1040
}
1041

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

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

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

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

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

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

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

UNCOV
1101
        return resps
×
1102
}
1103

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

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

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

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

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

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

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

×
UNCOV
1172
        sweeperInput.params = newParams
×
UNCOV
1173

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

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

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

×
UNCOV
1188
        return resultChan, nil
×
1189
}
1190

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

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

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

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

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

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

UNCOV
1230
        return defaultDeadline
×
1231
}
1232

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

×
UNCOV
1242
                s.handleExistingInput(input, pi)
×
UNCOV
1243

×
UNCOV
1244
                return nil
×
UNCOV
1245
        }
×
1246

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

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

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

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

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

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

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

×
1292
                return err
×
1293
        }
×
1294

UNCOV
1295
        pi.ntfnRegCancel = cancel
×
UNCOV
1296

×
UNCOV
1297
        return nil
×
1298
}
1299

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

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

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

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

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

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

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

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

1✔
1351
                return fn.None[RBFInfo]()
1✔
1352
        }
1✔
1353

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

1✔
1361
        return rbf
1✔
1362
}
1363

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

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

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

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

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

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

×
UNCOV
1402
        if prevExclGroup != nil {
×
UNCOV
1403
                s.removeExclusiveGroup(*prevExclGroup)
×
UNCOV
1404
        }
×
1405
}
1406

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

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

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

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

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

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

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

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

1✔
1464
                        continue
1✔
1465
                }
1466

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

1✔
1474
                        continue
1✔
1475
                }
1476

1477
                input.state = Swept
2✔
1478

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

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

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

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

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

6✔
1507
        pi.state = Fatal
6✔
1508

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

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

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

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

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

4✔
1540
                        continue
4✔
1541
                }
1542

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

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

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

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

1570
        return inputs
2✔
1571
}
1572

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

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

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

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

1598
                        return nil
1✔
1599
                })
1600
        }
1601

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

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

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

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

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

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

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

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

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

×
1660
                                return
×
1661
                        }
1662

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

×
UNCOV
1675
                                        return
×
UNCOV
1676
                                }
×
1677

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

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

2✔
1685
                                return
2✔
1686
                        }
1687

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1✔
1789
        return nil
1✔
1790
}
1791

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

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

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

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

1✔
1815
        return nil
1✔
1816
}
1817

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

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

×
UNCOV
1831
                        continue
×
1832
                }
1833

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

3✔
1841
                        continue
3✔
1842
                }
1843

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

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

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

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

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

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

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

UNCOV
1884
        return nil
×
1885
}
1886

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

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

3✔
1901
        inp.state = Swept
3✔
1902

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

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

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

4✔
1921
        isOurTx := s.cfg.Store.IsOurTx(txid)
4✔
1922

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

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

3✔
1933
                return
3✔
1934
        }
3✔
1935

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

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

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

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

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

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

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

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

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

×
UNCOV
1984
                        continue
×
1985
                }
1986

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

2✔
1994
                        continue
2✔
1995
                }
1996

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

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

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

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

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

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

© 2025 Coveralls, Inc