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

lightningnetwork / lnd / 12392176707

18 Dec 2024 11:37AM UTC coverage: 57.503% (-1.2%) from 58.722%
12392176707

Pull #9368

github

yyforyongyu
itest: fix flake in `testSendDirectPayment`

This bug was hidden because we used standby nodes before, which always
have more-than-necessary wallet utxos.
Pull Request #9368: Fix itest re new behaviors introduced by `blockbeat`

0 of 104 new or added lines in 5 files covered. (0.0%)

19604 existing lines in 259 files now uncovered.

102522 of 178291 relevant lines covered (57.5%)

24689.73 hits per line

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

42.86
/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
        // Failed is the state when a pending input has too many failed publish
123
        // atttempts or unknown broadcast error is returned.
124
        Failed
125
)
126

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

UNCOV
133
        case PendingPublish:
×
UNCOV
134
                return "PendingPublish"
×
135

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

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

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

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

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

151
        default:
×
152
                return "Unknown"
×
153
        }
154
}
155

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

162
        // FeeRate is the fee rate of the sweeping tx.
163
        FeeRate chainfee.SatPerKWeight
164

165
        // Fee is the total fee of the sweeping tx.
166
        Fee btcutil.Amount
167
}
168

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

175
        // state tracks the current state of the input.
176
        state SweepState
177

178
        // listeners is a list of channels over which the final outcome of the
179
        // sweep needs to be broadcasted.
180
        listeners []chan Result
181

182
        // ntfnRegCancel is populated with a function that cancels the chain
183
        // notifier spend registration.
184
        ntfnRegCancel func()
185

186
        // publishAttempts records the number of attempts that have already been
187
        // made to sweep this tx.
188
        publishAttempts int
189

190
        // params contains the parameters that control the sweeping process.
191
        params Params
192

193
        // lastFeeRate is the most recent fee rate used for this input within a
194
        // transaction broadcast to the network.
195
        lastFeeRate chainfee.SatPerKWeight
196

197
        // rbf records the RBF constraints.
198
        rbf fn.Option[RBFInfo]
199

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

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

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

221
        default:
14✔
222
                return false
14✔
223
        }
224
}
225

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

1✔
234
                return false, locktime
1✔
235
        }
1✔
236

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

1✔
248
                return false, locktime
1✔
249
        }
1✔
250

251
        return true, locktime
2✔
252
}
253

254
// InputsMap is a type alias for a set of pending inputs.
255
type InputsMap = map[wire.OutPoint]*SweeperInput
256

257
// inputsMapToString returns a human readable interpretation of the pending
258
// inputs.
UNCOV
259
func inputsMapToString(inputs InputsMap) string {
×
UNCOV
260
        inps := make([]input.Input, 0, len(inputs))
×
UNCOV
261
        for _, in := range inputs {
×
UNCOV
262
                inps = append(inps, in)
×
UNCOV
263
        }
×
264

UNCOV
265
        prefix := "\n"
×
UNCOV
266
        if len(inps) == 0 {
×
UNCOV
267
                prefix = ""
×
UNCOV
268
        }
×
269

UNCOV
270
        return prefix + inputTypeSummary(inps)
×
271
}
272

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

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

287
        // WitnessType is the witness type of the input being swept.
288
        WitnessType input.WitnessType
289

290
        // Amount is the amount of the input being swept.
291
        Amount btcutil.Amount
292

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

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

301
        // Params contains the sweep parameters for this pending request.
302
        Params Params
303

304
        // DeadlineHeight records the deadline height of this input.
305
        DeadlineHeight uint32
306
}
307

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

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

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

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

332
        cfg *UtxoSweeperConfig
333

334
        newInputs chan *sweepInputMessage
335
        spendChan chan *chainntnfs.SpendDetail
336

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

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

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

350
        currentOutputScript fn.Option[lnwallet.AddrWithKey]
351

352
        relayFeeRate chainfee.SatPerKWeight
353

354
        quit chan struct{}
355
        wg   sync.WaitGroup
356

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

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

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

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

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

380
        // Wallet contains the wallet functions that sweeper requires.
381
        Wallet Wallet
382

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

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

391
        // Store stores the published sweeper txes.
392
        Store SweeperStore
393

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

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

403
        // MaxFeeRate is the maximum fee rate allowed within the UtxoSweeper.
404
        MaxFeeRate chainfee.SatPerVByte
405

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

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

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

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

428
        // Tx is the transaction that spent the input.
429
        Tx *wire.MsgTx
430
}
431

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

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

16✔
453
        // Mount the block consumer.
16✔
454
        s.BeatConsumer = chainio.NewBeatConsumer(s.quit, s.Name())
16✔
455

16✔
456
        return s
16✔
457
}
16✔
458

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

UNCOV
465
        log.Info("Sweeper starting")
×
UNCOV
466

×
UNCOV
467
        // Retrieve relay fee for dust limit calculation. Assume that this will
×
UNCOV
468
        // not change from here on.
×
UNCOV
469
        s.relayFeeRate = s.cfg.FeeEstimator.RelayFeePerKW()
×
UNCOV
470

×
UNCOV
471
        // Set the current height.
×
UNCOV
472
        s.currentHeight = beat.Height()
×
UNCOV
473

×
UNCOV
474
        // Start sweeper main loop.
×
UNCOV
475
        s.wg.Add(1)
×
UNCOV
476
        go s.collector()
×
UNCOV
477

×
UNCOV
478
        return nil
×
479
}
480

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

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

UNCOV
494
        log.Info("Sweeper shutting down...")
×
UNCOV
495
        defer log.Debug("Sweeper shutdown complete")
×
UNCOV
496

×
UNCOV
497
        close(s.quit)
×
UNCOV
498
        s.wg.Wait()
×
UNCOV
499

×
UNCOV
500
        return nil
×
501
}
502

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

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

×
UNCOV
523
        if inp == nil || inp.OutPoint() == input.EmptyOutPoint ||
×
UNCOV
524
                inp.SignDesc() == nil {
×
525

×
526
                return nil, errors.New("nil input received")
×
527
        }
×
528

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

×
UNCOV
537
        sweeperInput := &sweepInputMessage{
×
UNCOV
538
                input:      inp,
×
UNCOV
539
                params:     params,
×
UNCOV
540
                resultChan: make(chan Result, 1),
×
UNCOV
541
        }
×
UNCOV
542

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

UNCOV
550
        return sweeperInput.resultChan, nil
×
551
}
552

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

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

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

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

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

UNCOV
614
                if !isConflicting {
×
UNCOV
615
                        continue
×
616
                }
617

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

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

629
                // If this transaction was conflicting, then we'll stop
630
                // rebroadcasting it in the background.
UNCOV
631
                s.cfg.Wallet.CancelRebroadcast(sweepHash)
×
632
        }
633

UNCOV
634
        return nil
×
635
}
636

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

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

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

×
659
                                return
×
660
                        }
×
661

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

675
                // A spend of one of our inputs is detected. Signal sweep
676
                // results to the caller(s).
UNCOV
677
                case spend := <-s.spendChan:
×
UNCOV
678
                        s.handleInputSpent(spend)
×
679

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

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

×
UNCOV
694
                        // Perform an sweep immediately if asked.
×
UNCOV
695
                        if req.params.Immediate {
×
UNCOV
696
                                inputs := s.updateSweeperInputs()
×
UNCOV
697
                                s.sweepPendingInputs(inputs)
×
UNCOV
698
                        }
×
699

UNCOV
700
                case resp := <-s.bumpRespChan:
×
UNCOV
701
                        // Handle the bump event.
×
UNCOV
702
                        err := s.handleBumpEvent(resp)
×
UNCOV
703
                        if err != nil {
×
UNCOV
704
                                log.Errorf("Failed to handle bump event: %v",
×
UNCOV
705
                                        err)
×
UNCOV
706
                        }
×
707

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

×
UNCOV
714
                        // Update the inputs with the latest height.
×
UNCOV
715
                        inputs := s.updateSweeperInputs()
×
UNCOV
716

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

724
                        // Attempt to sweep any pending inputs.
UNCOV
725
                        s.sweepPendingInputs(inputs)
×
UNCOV
726

×
UNCOV
727
                        // Notify we've processed the block.
×
UNCOV
728
                        s.NotifyBlockProcessed(beat, nil)
×
729

UNCOV
730
                case <-s.quit:
×
UNCOV
731
                        return
×
732
                }
733
        }
734
}
735

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

×
UNCOV
745
                // Skip inputs that aren't exclusive.
×
UNCOV
746
                if input.params.ExclusiveGroup == nil {
×
UNCOV
747
                        continue
×
748
                }
749

750
                // Skip inputs from other exclusive groups.
UNCOV
751
                if *input.params.ExclusiveGroup != group {
×
752
                        continue
×
753
                }
754

755
                // Skip inputs that are already terminated.
UNCOV
756
                if input.terminated() {
×
UNCOV
757
                        log.Tracef("Skipped sending error result for "+
×
UNCOV
758
                                "input %v, state=%v", outpoint, input.state)
×
UNCOV
759

×
UNCOV
760
                        continue
×
761
                }
762

763
                // Signal result channels.
UNCOV
764
                s.signalResult(input, Result{
×
UNCOV
765
                        Err: ErrExclusiveGroupSpend,
×
UNCOV
766
                })
×
UNCOV
767

×
UNCOV
768
                // Update the input's state as it can no longer be swept.
×
UNCOV
769
                input.state = Excluded
×
UNCOV
770

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

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

7✔
790
        if result.Err == nil {
9✔
791
                log.Tracef("Dispatching sweep success for %v to %v listeners",
2✔
792
                        op, len(listeners),
2✔
793
                )
2✔
794
        } else {
7✔
795
                log.Tracef("Dispatching sweep error for %v to %v listeners: %v",
5✔
796
                        op, len(listeners), result.Err,
5✔
797
                )
5✔
798
        }
5✔
799

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

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

×
UNCOV
811
                pi.ntfnRegCancel()
×
UNCOV
812
        }
×
813
}
814

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

827
        sweepAddr, err := s.currentOutputScript.UnwrapOrErr(
2✔
828
                fmt.Errorf("none sweep script"),
2✔
829
        )
2✔
830
        if err != nil {
2✔
831
                return err
×
832
        }
×
833

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

2✔
848
        // Reschedule the inputs that we just tried to sweep. This is done in
2✔
849
        // case the following publish fails, we'd like to update the inputs'
2✔
850
        // publish attempts and rescue them in the next sweep.
2✔
851
        s.markInputsPendingPublish(set)
2✔
852

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

2✔
857
        // Successfully sent the broadcast attempt, we now handle the result by
2✔
858
        // subscribing to the result chan and listen for future updates about
2✔
859
        // this tx.
2✔
860
        s.wg.Add(1)
2✔
861
        go s.monitorFeeBumpResult(set, resp)
2✔
862

2✔
863
        return nil
2✔
864
}
865

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

×
UNCOV
880
                        continue
×
881
                }
882

883
                // If this input has already terminated, there's clearly
884
                // something wrong as it would have been removed. In this case
885
                // we log an error and skip marking this input as pending
886
                // publish.
887
                if pi.terminated() {
4✔
888
                        log.Errorf("Expect input %v to not have terminated "+
1✔
889
                                "state, instead it has %v", op, pi.state)
1✔
890

1✔
891
                        continue
1✔
892
                }
893

894
                // Update the input's state.
895
                pi.state = PendingPublish
2✔
896

2✔
897
                // Record another publish attempt.
2✔
898
                pi.publishAttempts++
2✔
899
        }
900
}
901

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

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

×
UNCOV
926
                        continue
×
927
                }
928

929
                // Valdiate that the input is in an expected state.
930
                if pi.state != PendingPublish {
5✔
931
                        // We may get a Published if this is a replacement tx.
1✔
932
                        log.Debugf("Expect input %v to have %v, instead it "+
1✔
933
                                "has %v", op, PendingPublish, pi.state)
1✔
934

1✔
935
                        continue
1✔
936
                }
937

938
                // Update the input's state.
939
                pi.state = Published
3✔
940

3✔
941
                // Update the input's latest fee rate.
3✔
942
                pi.lastFeeRate = chainfee.SatPerKWeight(tr.FeeRate)
3✔
943
        }
944

945
        return nil
3✔
946
}
947

948
// markInputsPublishFailed marks the list of inputs as failed to be published.
949
func (s *UtxoSweeper) markInputsPublishFailed(set InputSet) {
2✔
950
        // Reschedule sweep.
2✔
951
        for _, inp := range set.Inputs() {
12✔
952
                op := inp.OutPoint()
10✔
953
                pi, ok := s.inputs[op]
10✔
954
                if !ok {
10✔
UNCOV
955
                        // It could be that this input is an additional wallet
×
UNCOV
956
                        // input that was attached. In that case there also
×
UNCOV
957
                        // isn't a pending input to update.
×
UNCOV
958
                        log.Tracef("Skipped marking input as publish failed: "+
×
UNCOV
959
                                "%v not found in pending inputs", op)
×
UNCOV
960

×
UNCOV
961
                        continue
×
962
                }
963

964
                // Valdiate that the input is in an expected state.
965
                if pi.state != PendingPublish && pi.state != Published {
15✔
966
                        log.Debugf("Expect input %v to have %v, instead it "+
5✔
967
                                "has %v", op, PendingPublish, pi.state)
5✔
968

5✔
969
                        continue
5✔
970
                }
971

972
                log.Warnf("Failed to publish input %v", op)
5✔
973

5✔
974
                // Update the input's state.
5✔
975
                pi.state = PublishFailed
5✔
976
        }
977
}
978

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

×
UNCOV
984
        log.Tracef("Wait for spend of %v at heightHint=%v",
×
UNCOV
985
                outpoint, heightHint)
×
UNCOV
986

×
UNCOV
987
        spendEvent, err := s.cfg.Notifier.RegisterSpendNtfn(
×
UNCOV
988
                &outpoint, script, heightHint,
×
UNCOV
989
        )
×
UNCOV
990
        if err != nil {
×
991
                return nil, fmt.Errorf("register spend ntfn: %w", err)
×
992
        }
×
993

UNCOV
994
        s.wg.Add(1)
×
UNCOV
995
        go func() {
×
UNCOV
996
                defer s.wg.Done()
×
UNCOV
997

×
UNCOV
998
                select {
×
UNCOV
999
                case spend, ok := <-spendEvent.Spend:
×
UNCOV
1000
                        if !ok {
×
UNCOV
1001
                                log.Debugf("Spend ntfn for %v canceled",
×
UNCOV
1002
                                        outpoint)
×
UNCOV
1003
                                return
×
UNCOV
1004
                        }
×
1005

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

×
UNCOV
1008
                        select {
×
UNCOV
1009
                        case s.spendChan <- spend:
×
UNCOV
1010
                                log.Debugf("Delivered spend ntfn for %v",
×
UNCOV
1011
                                        outpoint)
×
1012

1013
                        case <-s.quit:
×
1014
                        }
UNCOV
1015
                case <-s.quit:
×
1016
                }
1017
        }()
1018

UNCOV
1019
        return spendEvent.Cancel, nil
×
1020
}
1021

1022
// PendingInputs returns the set of inputs that the UtxoSweeper is currently
1023
// attempting to sweep.
1024
func (s *UtxoSweeper) PendingInputs() (
UNCOV
1025
        map[wire.OutPoint]*PendingInputResponse, error) {
×
UNCOV
1026

×
UNCOV
1027
        respChan := make(chan map[wire.OutPoint]*PendingInputResponse, 1)
×
UNCOV
1028
        errChan := make(chan error, 1)
×
UNCOV
1029
        select {
×
1030
        case s.pendingSweepsReqs <- &pendingSweepsReq{
1031
                respChan: respChan,
1032
                errChan:  errChan,
UNCOV
1033
        }:
×
1034
        case <-s.quit:
×
1035
                return nil, ErrSweeperShuttingDown
×
1036
        }
1037

UNCOV
1038
        select {
×
UNCOV
1039
        case pendingSweeps := <-respChan:
×
UNCOV
1040
                return pendingSweeps, nil
×
1041
        case err := <-errChan:
×
1042
                return nil, err
×
1043
        case <-s.quit:
×
1044
                return nil, ErrSweeperShuttingDown
×
1045
        }
1046
}
1047

1048
// handlePendingSweepsReq handles a request to retrieve all pending inputs the
1049
// UtxoSweeper is attempting to sweep.
1050
func (s *UtxoSweeper) handlePendingSweepsReq(
UNCOV
1051
        req *pendingSweepsReq) map[wire.OutPoint]*PendingInputResponse {
×
UNCOV
1052

×
UNCOV
1053
        resps := make(map[wire.OutPoint]*PendingInputResponse, len(s.inputs))
×
UNCOV
1054
        for _, inp := range s.inputs {
×
UNCOV
1055
                // Skip immature inputs for compatibility.
×
UNCOV
1056
                mature, _ := inp.isMature(uint32(s.currentHeight))
×
UNCOV
1057
                if !mature {
×
UNCOV
1058
                        continue
×
1059
                }
1060

1061
                // Only the exported fields are set, as we expect the response
1062
                // to only be consumed externally.
UNCOV
1063
                op := inp.OutPoint()
×
UNCOV
1064
                resps[op] = &PendingInputResponse{
×
UNCOV
1065
                        OutPoint:    op,
×
UNCOV
1066
                        WitnessType: inp.WitnessType(),
×
UNCOV
1067
                        Amount: btcutil.Amount(
×
UNCOV
1068
                                inp.SignDesc().Output.Value,
×
UNCOV
1069
                        ),
×
UNCOV
1070
                        LastFeeRate:       inp.lastFeeRate,
×
UNCOV
1071
                        BroadcastAttempts: inp.publishAttempts,
×
UNCOV
1072
                        Params:            inp.params,
×
UNCOV
1073
                        DeadlineHeight:    uint32(inp.DeadlineHeight),
×
UNCOV
1074
                }
×
1075
        }
1076

UNCOV
1077
        select {
×
UNCOV
1078
        case req.respChan <- resps:
×
1079
        case <-s.quit:
×
1080
                log.Debug("Skipped sending pending sweep response due to " +
×
1081
                        "UtxoSweeper shutting down")
×
1082
        }
1083

UNCOV
1084
        return resps
×
1085
}
1086

1087
// UpdateParams allows updating the sweep parameters of a pending input in the
1088
// UtxoSweeper. This function can be used to provide an updated fee preference
1089
// and force flag that will be used for a new sweep transaction of the input
1090
// that will act as a replacement transaction (RBF) of the original sweeping
1091
// transaction, if any. The exclusive group is left unchanged.
1092
//
1093
// NOTE: This currently doesn't do any fee rate validation to ensure that a bump
1094
// is actually successful. The responsibility of doing so should be handled by
1095
// the caller.
1096
func (s *UtxoSweeper) UpdateParams(input wire.OutPoint,
UNCOV
1097
        params Params) (chan Result, error) {
×
UNCOV
1098

×
UNCOV
1099
        responseChan := make(chan *updateResp, 1)
×
UNCOV
1100
        select {
×
1101
        case s.updateReqs <- &updateReq{
1102
                input:        input,
1103
                params:       params,
1104
                responseChan: responseChan,
UNCOV
1105
        }:
×
1106
        case <-s.quit:
×
1107
                return nil, ErrSweeperShuttingDown
×
1108
        }
1109

UNCOV
1110
        select {
×
UNCOV
1111
        case response := <-responseChan:
×
UNCOV
1112
                return response.resultChan, response.err
×
1113
        case <-s.quit:
×
1114
                return nil, ErrSweeperShuttingDown
×
1115
        }
1116
}
1117

1118
// handleUpdateReq handles an update request by simply updating the sweep
1119
// parameters of the pending input. Currently, no validation is done on the new
1120
// fee preference to ensure it will properly create a replacement transaction.
1121
//
1122
// TODO(wilmer):
1123
//   - Validate fee preference to ensure we'll create a valid replacement
1124
//     transaction to allow the new fee rate to propagate throughout the
1125
//     network.
1126
//   - Ensure we don't combine this input with any other unconfirmed inputs that
1127
//     did not exist in the original sweep transaction, resulting in an invalid
1128
//     replacement transaction.
1129
func (s *UtxoSweeper) handleUpdateReq(req *updateReq) (
UNCOV
1130
        chan Result, error) {
×
UNCOV
1131

×
UNCOV
1132
        // If the UtxoSweeper is already trying to sweep this input, then we can
×
UNCOV
1133
        // simply just increase its fee rate. This will allow the input to be
×
UNCOV
1134
        // batched with others which also have a similar fee rate, creating a
×
UNCOV
1135
        // higher fee rate transaction that replaces the original input's
×
UNCOV
1136
        // sweeping transaction.
×
UNCOV
1137
        sweeperInput, ok := s.inputs[req.input]
×
UNCOV
1138
        if !ok {
×
1139
                return nil, lnwallet.ErrNotMine
×
1140
        }
×
1141

1142
        // Create the updated parameters struct. Leave the exclusive group
1143
        // unchanged.
UNCOV
1144
        newParams := Params{
×
UNCOV
1145
                StartingFeeRate: req.params.StartingFeeRate,
×
UNCOV
1146
                Immediate:       req.params.Immediate,
×
UNCOV
1147
                Budget:          req.params.Budget,
×
UNCOV
1148
                DeadlineHeight:  req.params.DeadlineHeight,
×
UNCOV
1149
                ExclusiveGroup:  sweeperInput.params.ExclusiveGroup,
×
UNCOV
1150
        }
×
UNCOV
1151

×
UNCOV
1152
        log.Debugf("Updating parameters for %v(state=%v) from (%v) to (%v)",
×
UNCOV
1153
                req.input, sweeperInput.state, sweeperInput.params, newParams)
×
UNCOV
1154

×
UNCOV
1155
        sweeperInput.params = newParams
×
UNCOV
1156

×
UNCOV
1157
        // We need to reset the state so this input will be attempted again by
×
UNCOV
1158
        // our sweeper.
×
UNCOV
1159
        //
×
UNCOV
1160
        // TODO(yy): a dedicated state?
×
UNCOV
1161
        sweeperInput.state = Init
×
UNCOV
1162

×
UNCOV
1163
        // If the new input specifies a deadline, update the deadline height.
×
UNCOV
1164
        sweeperInput.DeadlineHeight = req.params.DeadlineHeight.UnwrapOr(
×
UNCOV
1165
                sweeperInput.DeadlineHeight,
×
UNCOV
1166
        )
×
UNCOV
1167

×
UNCOV
1168
        resultChan := make(chan Result, 1)
×
UNCOV
1169
        sweeperInput.listeners = append(sweeperInput.listeners, resultChan)
×
UNCOV
1170

×
UNCOV
1171
        return resultChan, nil
×
1172
}
1173

1174
// ListSweeps returns a list of the sweeps recorded by the sweep store.
UNCOV
1175
func (s *UtxoSweeper) ListSweeps() ([]chainhash.Hash, error) {
×
UNCOV
1176
        return s.cfg.Store.ListSweeps()
×
UNCOV
1177
}
×
1178

1179
// mempoolLookup takes an input's outpoint and queries the mempool to see
1180
// whether it's already been spent in a transaction found in the mempool.
1181
// Returns the transaction if found.
1182
func (s *UtxoSweeper) mempoolLookup(op wire.OutPoint) fn.Option[wire.MsgTx] {
7✔
1183
        // For neutrino backend, there's no mempool available, so we exit
7✔
1184
        // early.
7✔
1185
        if s.cfg.Mempool == nil {
8✔
1186
                log.Debugf("Skipping mempool lookup for %v, no mempool ", op)
1✔
1187

1✔
1188
                return fn.None[wire.MsgTx]()
1✔
1189
        }
1✔
1190

1191
        // Query this input in the mempool. If this outpoint is already spent
1192
        // in mempool, we should get a spending event back immediately.
1193
        return s.cfg.Mempool.LookupInputMempoolSpend(op)
6✔
1194
}
1195

1196
// calculateDefaultDeadline calculates the default deadline height for a sweep
1197
// request that has no deadline height specified.
UNCOV
1198
func (s *UtxoSweeper) calculateDefaultDeadline(pi *SweeperInput) int32 {
×
UNCOV
1199
        // Create a default deadline height, which will be used when there's no
×
UNCOV
1200
        // DeadlineHeight specified for a given input.
×
UNCOV
1201
        defaultDeadline := s.currentHeight + int32(s.cfg.NoDeadlineConfTarget)
×
UNCOV
1202

×
UNCOV
1203
        // If the input is immature and has a locktime, we'll use the locktime
×
UNCOV
1204
        // height as the starting height.
×
UNCOV
1205
        matured, locktime := pi.isMature(uint32(s.currentHeight))
×
UNCOV
1206
        if !matured {
×
UNCOV
1207
                defaultDeadline = int32(locktime + s.cfg.NoDeadlineConfTarget)
×
UNCOV
1208
                log.Debugf("Input %v is immature, using locktime=%v instead "+
×
UNCOV
1209
                        "of current height=%d as starting height",
×
UNCOV
1210
                        pi.OutPoint(), locktime, s.currentHeight)
×
UNCOV
1211
        }
×
1212

UNCOV
1213
        return defaultDeadline
×
1214
}
1215

1216
// handleNewInput processes a new input by registering spend notification and
1217
// scheduling sweeping for it.
UNCOV
1218
func (s *UtxoSweeper) handleNewInput(input *sweepInputMessage) error {
×
UNCOV
1219
        outpoint := input.input.OutPoint()
×
UNCOV
1220
        pi, pending := s.inputs[outpoint]
×
UNCOV
1221
        if pending {
×
UNCOV
1222
                log.Infof("Already has pending input %v received, old params: "+
×
UNCOV
1223
                        "%v, new params %v", outpoint, pi.params, input.params)
×
UNCOV
1224

×
UNCOV
1225
                s.handleExistingInput(input, pi)
×
UNCOV
1226

×
UNCOV
1227
                return nil
×
UNCOV
1228
        }
×
1229

1230
        // This is a new input, and we want to query the mempool to see if this
1231
        // input has already been spent. If so, we'll start the input with
1232
        // state Published and attach the RBFInfo.
UNCOV
1233
        state, rbfInfo := s.decideStateAndRBFInfo(input.input.OutPoint())
×
UNCOV
1234

×
UNCOV
1235
        // Create a new pendingInput and initialize the listeners slice with
×
UNCOV
1236
        // the passed in result channel. If this input is offered for sweep
×
UNCOV
1237
        // again, the result channel will be appended to this slice.
×
UNCOV
1238
        pi = &SweeperInput{
×
UNCOV
1239
                state:     state,
×
UNCOV
1240
                listeners: []chan Result{input.resultChan},
×
UNCOV
1241
                Input:     input.input,
×
UNCOV
1242
                params:    input.params,
×
UNCOV
1243
                rbf:       rbfInfo,
×
UNCOV
1244
        }
×
UNCOV
1245

×
UNCOV
1246
        // Set the acutal deadline height.
×
UNCOV
1247
        pi.DeadlineHeight = input.params.DeadlineHeight.UnwrapOr(
×
UNCOV
1248
                s.calculateDefaultDeadline(pi),
×
UNCOV
1249
        )
×
UNCOV
1250

×
UNCOV
1251
        s.inputs[outpoint] = pi
×
UNCOV
1252
        log.Tracef("input %v, state=%v, added to inputs", outpoint, pi.state)
×
UNCOV
1253

×
UNCOV
1254
        log.Infof("Registered sweep request at block %d: out_point=%v, "+
×
UNCOV
1255
                "witness_type=%v, amount=%v, deadline=%d, state=%v, "+
×
UNCOV
1256
                "params=(%v)", s.currentHeight, pi.OutPoint(), pi.WitnessType(),
×
UNCOV
1257
                btcutil.Amount(pi.SignDesc().Output.Value), pi.DeadlineHeight,
×
UNCOV
1258
                pi.state, pi.params)
×
UNCOV
1259

×
UNCOV
1260
        // Start watching for spend of this input, either by us or the remote
×
UNCOV
1261
        // party.
×
UNCOV
1262
        cancel, err := s.monitorSpend(
×
UNCOV
1263
                outpoint, input.input.SignDesc().Output.PkScript,
×
UNCOV
1264
                input.input.HeightHint(),
×
UNCOV
1265
        )
×
UNCOV
1266
        if err != nil {
×
1267
                err := fmt.Errorf("wait for spend: %w", err)
×
1268
                s.markInputFailed(pi, err)
×
1269

×
1270
                return err
×
1271
        }
×
1272

UNCOV
1273
        pi.ntfnRegCancel = cancel
×
UNCOV
1274

×
UNCOV
1275
        return nil
×
1276
}
1277

1278
// decideStateAndRBFInfo queries the mempool to see whether the given input has
1279
// already been spent. If so, the state Published will be returned, otherwise
1280
// state Init. When spent, it will query the sweeper store to fetch the fee
1281
// info of the spending transction, and construct an RBFInfo based on it.
1282
// Suppose an error occurs, fn.None is returned.
1283
func (s *UtxoSweeper) decideStateAndRBFInfo(op wire.OutPoint) (
1284
        SweepState, fn.Option[RBFInfo]) {
4✔
1285

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

4✔
1289
        // Extract the spending tx from the option.
4✔
1290
        var tx *wire.MsgTx
4✔
1291
        txOption.WhenSome(func(t wire.MsgTx) {
7✔
1292
                tx = &t
3✔
1293
        })
3✔
1294

1295
        // Exit early if it's not found.
1296
        //
1297
        // NOTE: this is not accurate for backends that don't support mempool
1298
        // lookup:
1299
        // - for neutrino we don't have a mempool.
1300
        // - for btcd below v0.24.1 we don't have `gettxspendingprevout`.
1301
        if tx == nil {
5✔
1302
                return Init, fn.None[RBFInfo]()
1✔
1303
        }
1✔
1304

1305
        // Otherwise the input is already spent in the mempool, so eventually
1306
        // we will return Published.
1307
        //
1308
        // We also need to update the RBF info for this input. If the sweeping
1309
        // transaction is broadcast by us, we can find the fee info in the
1310
        // sweeper store.
1311
        txid := tx.TxHash()
3✔
1312
        tr, err := s.cfg.Store.GetTx(txid)
3✔
1313

3✔
1314
        // If the tx is not found in the store, it means it's not broadcast by
3✔
1315
        // us, hence we can't find the fee info. This is fine as, later on when
3✔
1316
        // this tx is confirmed, we will remove the input from our inputs.
3✔
1317
        if errors.Is(err, ErrTxNotFound) {
4✔
1318
                log.Warnf("Spending tx %v not found in sweeper store", txid)
1✔
1319
                return Published, fn.None[RBFInfo]()
1✔
1320
        }
1✔
1321

1322
        // Exit if we get an db error.
1323
        if err != nil {
3✔
1324
                log.Errorf("Unable to get tx %v from sweeper store: %v",
1✔
1325
                        txid, err)
1✔
1326

1✔
1327
                return Published, fn.None[RBFInfo]()
1✔
1328
        }
1✔
1329

1330
        // Prepare the fee info and return it.
1331
        rbf := fn.Some(RBFInfo{
1✔
1332
                Txid:    txid,
1✔
1333
                Fee:     btcutil.Amount(tr.Fee),
1✔
1334
                FeeRate: chainfee.SatPerKWeight(tr.FeeRate),
1✔
1335
        })
1✔
1336

1✔
1337
        return Published, rbf
1✔
1338
}
1339

1340
// handleExistingInput processes an input that is already known to the sweeper.
1341
// It will overwrite the params of the old input with the new ones.
1342
func (s *UtxoSweeper) handleExistingInput(input *sweepInputMessage,
UNCOV
1343
        oldInput *SweeperInput) {
×
UNCOV
1344

×
UNCOV
1345
        // Before updating the input details, check if an exclusive group was
×
UNCOV
1346
        // set. In case the same input is registered again without an exclusive
×
UNCOV
1347
        // group set, the previous input and its sweep parameters are outdated
×
UNCOV
1348
        // hence need to be replaced. This scenario currently only happens for
×
UNCOV
1349
        // anchor outputs. When a channel is force closed, in the worst case 3
×
UNCOV
1350
        // different sweeps with the same exclusive group are registered with
×
UNCOV
1351
        // the sweeper to bump the closing transaction (cpfp) when its time
×
UNCOV
1352
        // critical. Receiving an input which was already registered with the
×
UNCOV
1353
        // sweeper but now without an exclusive group means non of the previous
×
UNCOV
1354
        // inputs were used as CPFP, so we need to make sure we update the
×
UNCOV
1355
        // sweep parameters but also remove all inputs with the same exclusive
×
UNCOV
1356
        // group because the are outdated too.
×
UNCOV
1357
        var prevExclGroup *uint64
×
UNCOV
1358
        if oldInput.params.ExclusiveGroup != nil &&
×
UNCOV
1359
                input.params.ExclusiveGroup == nil {
×
UNCOV
1360

×
UNCOV
1361
                prevExclGroup = new(uint64)
×
UNCOV
1362
                *prevExclGroup = *oldInput.params.ExclusiveGroup
×
UNCOV
1363
        }
×
1364

1365
        // Update input details and sweep parameters. The re-offered input
1366
        // details may contain a change to the unconfirmed parent tx info.
UNCOV
1367
        oldInput.params = input.params
×
UNCOV
1368
        oldInput.Input = input.input
×
UNCOV
1369

×
UNCOV
1370
        // If the new input specifies a deadline, update the deadline height.
×
UNCOV
1371
        oldInput.DeadlineHeight = input.params.DeadlineHeight.UnwrapOr(
×
UNCOV
1372
                oldInput.DeadlineHeight,
×
UNCOV
1373
        )
×
UNCOV
1374

×
UNCOV
1375
        // Add additional result channel to signal spend of this input.
×
UNCOV
1376
        oldInput.listeners = append(oldInput.listeners, input.resultChan)
×
UNCOV
1377

×
UNCOV
1378
        if prevExclGroup != nil {
×
UNCOV
1379
                s.removeExclusiveGroup(*prevExclGroup)
×
UNCOV
1380
        }
×
1381
}
1382

1383
// handleInputSpent takes a spend event of our input and updates the sweeper's
1384
// internal state to remove the input.
UNCOV
1385
func (s *UtxoSweeper) handleInputSpent(spend *chainntnfs.SpendDetail) {
×
UNCOV
1386
        // Query store to find out if we ever published this tx.
×
UNCOV
1387
        spendHash := *spend.SpenderTxHash
×
UNCOV
1388
        isOurTx, err := s.cfg.Store.IsOurTx(spendHash)
×
UNCOV
1389
        if err != nil {
×
1390
                log.Errorf("cannot determine if tx %v is ours: %v",
×
1391
                        spendHash, err)
×
1392
                return
×
1393
        }
×
1394

1395
        // If this isn't our transaction, it means someone else swept outputs
1396
        // that we were attempting to sweep. This can happen for anchor outputs
1397
        // as well as justice transactions. In this case, we'll notify the
1398
        // wallet to remove any spends that descent from this output.
UNCOV
1399
        if !isOurTx {
×
UNCOV
1400
                // Construct a map of the inputs this transaction spends.
×
UNCOV
1401
                spendingTx := spend.SpendingTx
×
UNCOV
1402
                inputsSpent := make(
×
UNCOV
1403
                        map[wire.OutPoint]struct{}, len(spendingTx.TxIn),
×
UNCOV
1404
                )
×
UNCOV
1405
                for _, txIn := range spendingTx.TxIn {
×
UNCOV
1406
                        inputsSpent[txIn.PreviousOutPoint] = struct{}{}
×
UNCOV
1407
                }
×
1408

UNCOV
1409
                log.Debugf("Attempting to remove descendant txns invalidated "+
×
UNCOV
1410
                        "by (txid=%v): %v", spendingTx.TxHash(),
×
UNCOV
1411
                        spew.Sdump(spendingTx))
×
UNCOV
1412

×
UNCOV
1413
                err := s.removeConflictSweepDescendants(inputsSpent)
×
UNCOV
1414
                if err != nil {
×
1415
                        log.Warnf("unable to remove descendant transactions "+
×
1416
                                "due to tx %v: ", spendHash)
×
1417
                }
×
1418

UNCOV
1419
                log.Debugf("Detected third party spend related to in flight "+
×
UNCOV
1420
                        "inputs (is_ours=%v): %v", isOurTx,
×
UNCOV
1421
                        lnutils.SpewLogClosure(spend.SpendingTx))
×
1422
        }
1423

1424
        // We now use the spending tx to update the state of the inputs.
UNCOV
1425
        s.markInputsSwept(spend.SpendingTx, isOurTx)
×
1426
}
1427

1428
// markInputsSwept marks all inputs swept by the spending transaction as swept.
1429
// It will also notify all the subscribers of this input.
1430
func (s *UtxoSweeper) markInputsSwept(tx *wire.MsgTx, isOurTx bool) {
1✔
1431
        for _, txIn := range tx.TxIn {
5✔
1432
                outpoint := txIn.PreviousOutPoint
4✔
1433

4✔
1434
                // Check if this input is known to us. It could probably be
4✔
1435
                // unknown if we canceled the registration, deleted from inputs
4✔
1436
                // map but the ntfn was in-flight already. Or this could be not
4✔
1437
                // one of our inputs.
4✔
1438
                input, ok := s.inputs[outpoint]
4✔
1439
                if !ok {
5✔
1440
                        // It's very likely that a spending tx contains inputs
1✔
1441
                        // that we don't know.
1✔
1442
                        log.Tracef("Skipped marking input as swept: %v not "+
1✔
1443
                                "found in pending inputs", outpoint)
1✔
1444

1✔
1445
                        continue
1✔
1446
                }
1447

1448
                // This input may already been marked as swept by a previous
1449
                // spend notification, which is likely to happen as one sweep
1450
                // transaction usually sweeps multiple inputs.
1451
                if input.terminated() {
4✔
1452
                        log.Debugf("Skipped marking input as swept: %v "+
1✔
1453
                                "state=%v", outpoint, input.state)
1✔
1454

1✔
1455
                        continue
1✔
1456
                }
1457

1458
                input.state = Swept
2✔
1459

2✔
1460
                // Return either a nil or a remote spend result.
2✔
1461
                var err error
2✔
1462
                if !isOurTx {
2✔
UNCOV
1463
                        log.Warnf("Input=%v was spent by remote or third "+
×
UNCOV
1464
                                "party in tx=%v", outpoint, tx.TxHash())
×
UNCOV
1465
                        err = ErrRemoteSpend
×
UNCOV
1466
                }
×
1467

1468
                // Signal result channels.
1469
                s.signalResult(input, Result{
2✔
1470
                        Tx:  tx,
2✔
1471
                        Err: err,
2✔
1472
                })
2✔
1473

2✔
1474
                // Remove all other inputs in this exclusive group.
2✔
1475
                if input.params.ExclusiveGroup != nil {
2✔
UNCOV
1476
                        s.removeExclusiveGroup(*input.params.ExclusiveGroup)
×
UNCOV
1477
                }
×
1478
        }
1479
}
1480

1481
// markInputFailed marks the given input as failed and won't be retried. It
1482
// will also notify all the subscribers of this input.
1483
func (s *UtxoSweeper) markInputFailed(pi *SweeperInput, err error) {
5✔
1484
        log.Errorf("Failed to sweep input: %v, error: %v", pi, err)
5✔
1485

5✔
1486
        pi.state = Failed
5✔
1487

5✔
1488
        s.signalResult(pi, Result{Err: err})
5✔
1489
}
5✔
1490

1491
// updateSweeperInputs updates the sweeper's internal state and returns a map
1492
// of inputs to be swept. It will remove the inputs that are in final states,
1493
// and returns a map of inputs that have either state Init or PublishFailed.
1494
func (s *UtxoSweeper) updateSweeperInputs() InputsMap {
1✔
1495
        // Create a map of inputs to be swept.
1✔
1496
        inputs := make(InputsMap)
1✔
1497

1✔
1498
        // Iterate the pending inputs and update the sweeper's state.
1✔
1499
        //
1✔
1500
        // TODO(yy): sweeper is made to communicate via go channels, so no
1✔
1501
        // locks are needed to access the map. However, it'd be safer if we
1✔
1502
        // turn this inputs map into a SyncMap in case we wanna add concurrent
1✔
1503
        // access to the map in the future.
1✔
1504
        for op, input := range s.inputs {
10✔
1505
                log.Tracef("Checking input: %s, state=%v", input, input.state)
9✔
1506

9✔
1507
                // If the input has reached a final state, that it's either
9✔
1508
                // been swept, or failed, or excluded, we will remove it from
9✔
1509
                // our sweeper.
9✔
1510
                if input.terminated() {
12✔
1511
                        log.Debugf("Removing input(State=%v) %v from sweeper",
3✔
1512
                                input.state, op)
3✔
1513

3✔
1514
                        delete(s.inputs, op)
3✔
1515

3✔
1516
                        continue
3✔
1517
                }
1518

1519
                // If this input has been included in a sweep tx that's not
1520
                // published yet, we'd skip this input and wait for the sweep
1521
                // tx to be published.
1522
                if input.state == PendingPublish {
7✔
1523
                        continue
1✔
1524
                }
1525

1526
                // If this input has already been published, we will need to
1527
                // check the RBF condition before attempting another sweeping.
1528
                if input.state == Published {
6✔
1529
                        continue
1✔
1530
                }
1531

1532
                // If the input has a locktime that's not yet reached, we will
1533
                // skip this input and wait for the locktime to be reached.
1534
                mature, _ := input.isMature(uint32(s.currentHeight))
4✔
1535
                if !mature {
6✔
1536
                        continue
2✔
1537
                }
1538

1539
                // If this input is new or has been failed to be published,
1540
                // we'd retry it. The assumption here is that when an error is
1541
                // returned from `PublishTransaction`, it means the tx has
1542
                // failed to meet the policy, hence it's not in the mempool.
1543
                inputs[op] = input
2✔
1544
        }
1545

1546
        return inputs
1✔
1547
}
1548

1549
// sweepPendingInputs is called when the ticker fires. It will create clusters
1550
// and attempt to create and publish the sweeping transactions.
1551
func (s *UtxoSweeper) sweepPendingInputs(inputs InputsMap) {
1✔
1552
        log.Debugf("Sweeping %v inputs", len(inputs))
1✔
1553

1✔
1554
        // Cluster all of our inputs based on the specific Aggregator.
1✔
1555
        sets := s.cfg.Aggregator.ClusterInputs(inputs)
1✔
1556

1✔
1557
        // sweepWithLock is a helper closure that executes the sweep within a
1✔
1558
        // coin select lock to prevent the coins being selected for other
1✔
1559
        // transactions like funding of a channel.
1✔
1560
        sweepWithLock := func(set InputSet) error {
2✔
1561
                return s.cfg.Wallet.WithCoinSelectLock(func() error {
2✔
1562
                        // Try to add inputs from our wallet.
1✔
1563
                        err := set.AddWalletInputs(s.cfg.Wallet)
1✔
1564
                        if err != nil {
1✔
UNCOV
1565
                                return err
×
UNCOV
1566
                        }
×
1567

1568
                        // Create sweeping transaction for each set.
1569
                        err = s.sweep(set)
1✔
1570
                        if err != nil {
1✔
1571
                                return err
×
1572
                        }
×
1573

1574
                        return nil
1✔
1575
                })
1576
        }
1577

1578
        for _, set := range sets {
3✔
1579
                var err error
2✔
1580
                if set.NeedWalletInput() {
3✔
1581
                        // Sweep the set of inputs that need the wallet inputs.
1✔
1582
                        err = sweepWithLock(set)
1✔
1583
                } else {
2✔
1584
                        // Sweep the set of inputs that don't need the wallet
1✔
1585
                        // inputs.
1✔
1586
                        err = s.sweep(set)
1✔
1587
                }
1✔
1588

1589
                if err != nil {
2✔
UNCOV
1590
                        log.Errorf("Failed to sweep %v: %v", set, err)
×
UNCOV
1591
                }
×
1592
        }
1593
}
1594

1595
// bumpResp wraps the result of a bump attempt returned from the fee bumper and
1596
// the inputs being used.
1597
type bumpResp struct {
1598
        // result is the result of the bump attempt returned from the fee
1599
        // bumper.
1600
        result *BumpResult
1601

1602
        // set is the input set that was used in the bump attempt.
1603
        set InputSet
1604
}
1605

1606
// monitorFeeBumpResult subscribes to the passed result chan to listen for
1607
// future updates about the sweeping tx.
1608
//
1609
// NOTE: must run as a goroutine.
1610
func (s *UtxoSweeper) monitorFeeBumpResult(set InputSet,
1611
        resultChan <-chan *BumpResult) {
6✔
1612

6✔
1613
        defer s.wg.Done()
6✔
1614

6✔
1615
        for {
13✔
1616
                select {
7✔
1617
                case r := <-resultChan:
3✔
1618
                        // Validate the result is valid.
3✔
1619
                        if err := r.Validate(); err != nil {
3✔
1620
                                log.Errorf("Received invalid result: %v", err)
×
1621
                                continue
×
1622
                        }
1623

1624
                        resp := &bumpResp{
3✔
1625
                                result: r,
3✔
1626
                                set:    set,
3✔
1627
                        }
3✔
1628

3✔
1629
                        // Send the result back to the main event loop.
3✔
1630
                        select {
3✔
1631
                        case s.bumpRespChan <- resp:
3✔
1632
                        case <-s.quit:
×
1633
                                log.Debug("Sweeper shutting down, skip " +
×
1634
                                        "sending bump result")
×
1635

×
1636
                                return
×
1637
                        }
1638

1639
                        // The sweeping tx has been confirmed, we can exit the
1640
                        // monitor now.
1641
                        //
1642
                        // TODO(yy): can instead remove the spend subscription
1643
                        // in sweeper and rely solely on this event to mark
1644
                        // inputs as Swept?
1645
                        if r.Event == TxConfirmed || r.Event == TxFailed {
5✔
1646
                                // Exit if the tx is failed to be created.
2✔
1647
                                if r.Tx == nil {
2✔
UNCOV
1648
                                        log.Debugf("Received %v for nil tx, "+
×
UNCOV
1649
                                                "exit monitor", r.Event)
×
UNCOV
1650

×
UNCOV
1651
                                        return
×
UNCOV
1652
                                }
×
1653

1654
                                log.Debugf("Received %v for sweep tx %v, exit "+
2✔
1655
                                        "fee bump monitor", r.Event,
2✔
1656
                                        r.Tx.TxHash())
2✔
1657

2✔
1658
                                // Cancel the rebroadcasting of the failed tx.
2✔
1659
                                s.cfg.Wallet.CancelRebroadcast(r.Tx.TxHash())
2✔
1660

2✔
1661
                                return
2✔
1662
                        }
1663

1664
                case <-s.quit:
2✔
1665
                        log.Debugf("Sweeper shutting down, exit fee " +
2✔
1666
                                "bump handler")
2✔
1667

2✔
1668
                        return
2✔
1669
                }
1670
        }
1671
}
1672

1673
// handleBumpEventTxFailed handles the case where the tx has been failed to
1674
// publish.
1675
func (s *UtxoSweeper) handleBumpEventTxFailed(resp *bumpResp) {
1✔
1676
        r := resp.result
1✔
1677
        tx, err := r.Tx, r.Err
1✔
1678

1✔
1679
        if tx != nil {
2✔
1680
                log.Warnf("Fee bump attempt failed for tx=%v: %v", tx.TxHash(),
1✔
1681
                        err)
1✔
1682
        }
1✔
1683

1684
        // NOTE: When marking the inputs as failed, we are using the input set
1685
        // instead of the inputs found in the tx. This is fine for current
1686
        // version of the sweeper because we always create a tx using ALL of
1687
        // the inputs specified by the set.
1688
        //
1689
        // TODO(yy): should we also remove the failed tx from db?
1690
        s.markInputsPublishFailed(resp.set)
1✔
1691
}
1692

1693
// handleBumpEventTxReplaced handles the case where the sweeping tx has been
1694
// replaced by a new one.
1695
func (s *UtxoSweeper) handleBumpEventTxReplaced(resp *bumpResp) error {
3✔
1696
        r := resp.result
3✔
1697
        oldTx := r.ReplacedTx
3✔
1698
        newTx := r.Tx
3✔
1699

3✔
1700
        // Prepare a new record to replace the old one.
3✔
1701
        tr := &TxRecord{
3✔
1702
                Txid:    newTx.TxHash(),
3✔
1703
                FeeRate: uint64(r.FeeRate),
3✔
1704
                Fee:     uint64(r.Fee),
3✔
1705
        }
3✔
1706

3✔
1707
        // Get the old record for logging purpose.
3✔
1708
        oldTxid := oldTx.TxHash()
3✔
1709
        record, err := s.cfg.Store.GetTx(oldTxid)
3✔
1710
        if err != nil {
4✔
1711
                log.Errorf("Fetch tx record for %v: %v", oldTxid, err)
1✔
1712
                return err
1✔
1713
        }
1✔
1714

1715
        // Cancel the rebroadcasting of the replaced tx.
1716
        s.cfg.Wallet.CancelRebroadcast(oldTxid)
2✔
1717

2✔
1718
        log.Infof("RBFed tx=%v(fee=%v sats, feerate=%v sats/kw) with new "+
2✔
1719
                "tx=%v(fee=%v, "+"feerate=%v)", record.Txid, record.Fee,
2✔
1720
                record.FeeRate, tr.Txid, tr.Fee, tr.FeeRate)
2✔
1721

2✔
1722
        // The old sweeping tx has been replaced by a new one, we will update
2✔
1723
        // the tx record in the sweeper db.
2✔
1724
        //
2✔
1725
        // TODO(yy): we may also need to update the inputs in this tx to a new
2✔
1726
        // state. Suppose a replacing tx only spends a subset of the inputs
2✔
1727
        // here, we'd end up with the rest being marked as `Published` and
2✔
1728
        // won't be aggregated in the next sweep. Atm it's fine as we always
2✔
1729
        // RBF the same input set.
2✔
1730
        if err := s.cfg.Store.DeleteTx(oldTxid); err != nil {
3✔
1731
                log.Errorf("Delete tx record for %v: %v", oldTxid, err)
1✔
1732
                return err
1✔
1733
        }
1✔
1734

1735
        // Mark the inputs as published using the replacing tx.
1736
        return s.markInputsPublished(tr, resp.set)
1✔
1737
}
1738

1739
// handleBumpEventTxPublished handles the case where the sweeping tx has been
1740
// successfully published.
1741
func (s *UtxoSweeper) handleBumpEventTxPublished(resp *bumpResp) error {
1✔
1742
        r := resp.result
1✔
1743
        tx := r.Tx
1✔
1744
        tr := &TxRecord{
1✔
1745
                Txid:    tx.TxHash(),
1✔
1746
                FeeRate: uint64(r.FeeRate),
1✔
1747
                Fee:     uint64(r.Fee),
1✔
1748
        }
1✔
1749

1✔
1750
        // Inputs have been successfully published so we update their
1✔
1751
        // states.
1✔
1752
        err := s.markInputsPublished(tr, resp.set)
1✔
1753
        if err != nil {
1✔
1754
                return err
×
1755
        }
×
1756

1757
        log.Debugf("Published sweep tx %v, num_inputs=%v, height=%v",
1✔
1758
                tx.TxHash(), len(tx.TxIn), s.currentHeight)
1✔
1759

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

1✔
1765
        return nil
1✔
1766
}
1767

1768
// handleBumpEventTxFatal handles the case where there's an unexpected error
1769
// when creating or publishing the sweeping tx. In this case, the tx will be
1770
// removed from the sweeper store and the inputs will be marked as `Failed`,
1771
// which means they will not be retried.
1772
func (s *UtxoSweeper) handleBumpEventTxFatal(resp *bumpResp) error {
2✔
1773
        r := resp.result
2✔
1774

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

2✔
1781
                // Remove the tx from the sweeper db if it exists.
2✔
1782
                if err := s.cfg.Store.DeleteTx(txid); err != nil {
3✔
1783
                        return fmt.Errorf("delete tx record for %v: %w", txid,
1✔
1784
                                err)
1✔
1785
                }
1✔
1786
        }
1787

1788
        // Mark the inputs as failed.
1789
        s.markInputsFailed(resp.set, r.Err)
1✔
1790

1✔
1791
        return nil
1✔
1792
}
1793

1794
// markInputsFailed marks all inputs found in the tx as failed. It will also
1795
// notify all the subscribers of these inputs.
1796
func (s *UtxoSweeper) markInputsFailed(set InputSet, err error) {
2✔
1797
        for _, inp := range set.Inputs() {
9✔
1798
                outpoint := inp.OutPoint()
7✔
1799

7✔
1800
                input, ok := s.inputs[outpoint]
7✔
1801
                if !ok {
7✔
UNCOV
1802
                        // It's very likely that a spending tx contains inputs
×
UNCOV
1803
                        // that we don't know.
×
UNCOV
1804
                        log.Tracef("Skipped marking input as failed: %v not "+
×
UNCOV
1805
                                "found in pending inputs", outpoint)
×
UNCOV
1806

×
UNCOV
1807
                        continue
×
1808
                }
1809

1810
                // If the input is already in a terminal state, we don't want
1811
                // to rewrite it, which also indicates an error as we only get
1812
                // an error event during the initial broadcast.
1813
                if input.terminated() {
10✔
1814
                        log.Errorf("Skipped marking input=%v as failed due to "+
3✔
1815
                                "unexpected state=%v", outpoint, input.state)
3✔
1816

3✔
1817
                        continue
3✔
1818
                }
1819

1820
                s.markInputFailed(input, err)
4✔
1821
        }
1822
}
1823

1824
// handleBumpEvent handles the result sent from the bumper based on its event
1825
// type.
1826
//
1827
// NOTE: TxConfirmed event is not handled, since we already subscribe to the
1828
// input's spending event, we don't need to do anything here.
1829
func (s *UtxoSweeper) handleBumpEvent(r *bumpResp) error {
1✔
1830
        log.Debugf("Received bump result %v", r.result)
1✔
1831

1✔
1832
        switch r.result.Event {
1✔
1833
        // The tx has been published, we update the inputs' state and create a
1834
        // record to be stored in the sweeper db.
UNCOV
1835
        case TxPublished:
×
UNCOV
1836
                return s.handleBumpEventTxPublished(r)
×
1837

1838
        // The tx has failed, we update the inputs' state.
1839
        case TxFailed:
1✔
1840
                s.handleBumpEventTxFailed(r)
1✔
1841
                return nil
1✔
1842

1843
        // The tx has been replaced, we will remove the old tx and replace it
1844
        // with the new one.
UNCOV
1845
        case TxReplaced:
×
UNCOV
1846
                return s.handleBumpEventTxReplaced(r)
×
1847

1848
        // There's a fatal error in creating the tx, we will remove the tx from
1849
        // the sweeper db and mark the inputs as failed.
UNCOV
1850
        case TxFatal:
×
UNCOV
1851
                return s.handleBumpEventTxFatal(r)
×
1852
        }
1853

UNCOV
1854
        return nil
×
1855
}
1856

1857
// IsSweeperOutpoint determines whether the outpoint was created by the sweeper.
1858
//
1859
// NOTE: It is enough to check the txid because the sweeper will create
1860
// outpoints which solely belong to the internal LND wallet.
UNCOV
1861
func (s *UtxoSweeper) IsSweeperOutpoint(op wire.OutPoint) bool {
×
UNCOV
1862
        found, err := s.cfg.Store.IsOurTx(op.Hash)
×
UNCOV
1863
        // In case there is an error fetching the transaction details from the
×
UNCOV
1864
        // sweeper store we assume the outpoint is still used by the sweeper
×
UNCOV
1865
        // (worst case scenario).
×
UNCOV
1866
        //
×
UNCOV
1867
        // TODO(ziggie): Ensure that confirmed outpoints are deleted from the
×
UNCOV
1868
        // bucket.
×
UNCOV
1869
        if err != nil && !errors.Is(err, errNoTxHashesBucket) {
×
1870
                log.Errorf("failed to fetch info for outpoint(%v:%d) "+
×
1871
                        "with: %v, we assume it is still in use by the sweeper",
×
1872
                        op.Hash, op.Index, err)
×
1873

×
1874
                return true
×
1875
        }
×
1876

UNCOV
1877
        return found
×
1878
}
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