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

lightningnetwork / lnd / 14358372723

09 Apr 2025 01:26PM UTC coverage: 56.696% (-12.3%) from 69.037%
14358372723

Pull #9696

github

web-flow
Merge e2837e400 into 867d27d68
Pull Request #9696: Add `development_guidelines.md` for both human and machine

107055 of 188823 relevant lines covered (56.7%)

22721.56 hits per line

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

49.56
/sweep/sweeper.go
1
package sweep
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

83
        return fmt.Sprintf("startingFeeRate=%v, immediate=%v, "+
×
84
                "exclusive_group=%v, budget=%v, deadline=%v", p.StartingFeeRate,
×
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.
131
func (s SweepState) String() string {
×
132
        switch s {
×
133
        case Init:
×
134
                return "Init"
×
135

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

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

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

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

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

151
        case Fatal:
×
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.
262
func inputsMapToString(inputs InputsMap) string {
×
263
        if len(inputs) == 0 {
×
264
                return ""
×
265
        }
×
266

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

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

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

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

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

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

334
        cfg *UtxoSweeperConfig
335

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

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

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

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

352
        currentOutputScript fn.Option[lnwallet.AddrWithKey]
353

354
        relayFeeRate chainfee.SatPerKWeight
355

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

20✔
458
        return s
20✔
459
}
20✔
460

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

467
        log.Info("Sweeper starting")
×
468

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

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

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

×
480
        return nil
×
481
}
482

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

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

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

×
499
        close(s.quit)
×
500
        s.wg.Wait()
×
501

×
502
        return nil
×
503
}
504

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

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

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

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

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

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

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

552
        return sweeperInput.resultChan, nil
×
553
}
554

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

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

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

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

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

616
                if !isConflicting {
×
617
                        continue
×
618
                }
619

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

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

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

636
        return nil
1✔
637
}
638

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

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

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

×
661
                                return
×
662
                        }
×
663

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
762
                        continue
×
763
                }
764

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

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

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

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

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

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

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

×
813
                pi.ntfnRegCancel()
×
814
        }
×
815
}
816

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

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

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

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

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

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

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

2✔
868
        return nil
2✔
869
}
870

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

×
885
                        continue
×
886
                }
887

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

1✔
896
                        continue
1✔
897
                }
898

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

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

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

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

×
931
                        continue
×
932
                }
933

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

1✔
940
                        continue
1✔
941
                }
942

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

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

950
        return nil
3✔
951
}
952

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

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

×
968
                        continue
×
969
                }
970

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

5✔
976
                        continue
5✔
977
                }
978

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

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

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

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

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

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

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

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

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

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

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

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

1035
        return spendEvent.Cancel, nil
×
1036
}
1037

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

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

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

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

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

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

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

1100
        return resps
×
1101
}
1102

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

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

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

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

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

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

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

×
1171
        sweeperInput.params = newParams
×
1172

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

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

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

×
1187
        return resultChan, nil
×
1188
}
1189

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

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

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

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

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

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

1229
        return defaultDeadline
×
1230
}
1231

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

×
1241
                s.handleExistingInput(input, pi)
×
1242

×
1243
                return nil
×
1244
        }
×
1245

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

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

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

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

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

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

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

×
1291
                return err
×
1292
        }
×
1293

1294
        pi.ntfnRegCancel = cancel
×
1295

×
1296
        return nil
×
1297
}
1298

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

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

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

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

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

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

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

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

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

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

1✔
1360
        return rbf
1✔
1361
}
1362

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1✔
1463
                        continue
1✔
1464
                }
1465

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

1✔
1473
                        continue
1✔
1474
                }
1475

1476
                input.state = Swept
2✔
1477

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

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

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

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

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

6✔
1506
        pi.state = Fatal
6✔
1507

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

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

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

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

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

4✔
1539
                        continue
4✔
1540
                }
1541

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

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

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

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

1569
        return inputs
2✔
1570
}
1571

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

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

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

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

1597
                        return nil
1✔
1598
                })
1599
        }
1600

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

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

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

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

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

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

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

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

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

×
1659
                                return
×
1660
                        }
1661

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

×
1674
                                        return
×
1675
                                }
×
1676

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

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

2✔
1684
                                return
2✔
1685
                        }
1686

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1✔
1788
        return nil
1✔
1789
}
1790

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

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

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

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

1✔
1814
        return nil
1✔
1815
}
1816

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

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

×
1830
                        continue
×
1831
                }
1832

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

3✔
1840
                        continue
3✔
1841
                }
1842

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

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

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

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

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

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

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

1883
        return nil
×
1884
}
1885

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

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

3✔
1900
        inp.state = Swept
3✔
1901

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

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

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

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

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

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

3✔
1932
                return
3✔
1933
        }
3✔
1934

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

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

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

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

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

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

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

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

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

×
1983
                        continue
×
1984
                }
1985

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

2✔
1993
                        continue
2✔
1994
                }
1995

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

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

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

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

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

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

© 2025 Coveralls, Inc