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

lightningnetwork / lnd / 10182608679

31 Jul 2024 02:55PM UTC coverage: 58.459% (-0.2%) from 58.625%
10182608679

push

github

web-flow
Merge pull request #8845 from bitbandi/multiple-etcd-host

Allow multiple etcd host

124794 of 213473 relevant lines covered (58.46%)

27889.07 hits per line

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

89.27
/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/chainntnfs"
14
        "github.com/lightningnetwork/lnd/fn"
15
        "github.com/lightningnetwork/lnd/input"
16
        "github.com/lightningnetwork/lnd/lnutils"
17
        "github.com/lightningnetwork/lnd/lnwallet"
18
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
19
)
20

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

121
        // Failed is the state when a pending input has too many failed publish
122
        // atttempts or unknown broadcast error is returned.
123
        Failed
124
)
125

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

132
        case PendingPublish:
3✔
133
                return "PendingPublish"
3✔
134

135
        case Published:
3✔
136
                return "Published"
3✔
137

138
        case PublishFailed:
3✔
139
                return "PublishFailed"
3✔
140

141
        case Swept:
3✔
142
                return "Swept"
3✔
143

144
        case Excluded:
3✔
145
                return "Excluded"
3✔
146

147
        case Failed:
×
148
                return "Failed"
×
149

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

220
        default:
13✔
221
                return false
13✔
222
        }
223
}
224

225
// InputsMap is a type alias for a set of pending inputs.
226
type InputsMap = map[wire.OutPoint]*SweeperInput
227

228
// pendingSweepsReq is an internal message we'll use to represent an external
229
// caller's intent to retrieve all of the pending inputs the UtxoSweeper is
230
// attempting to sweep.
231
type pendingSweepsReq struct {
232
        respChan chan map[wire.OutPoint]*PendingInputResponse
233
        errChan  chan error
234
}
235

236
// PendingInputResponse contains information about an input that is currently
237
// being swept by the UtxoSweeper.
238
type PendingInputResponse struct {
239
        // OutPoint is the identify outpoint of the input being swept.
240
        OutPoint wire.OutPoint
241

242
        // WitnessType is the witness type of the input being swept.
243
        WitnessType input.WitnessType
244

245
        // Amount is the amount of the input being swept.
246
        Amount btcutil.Amount
247

248
        // LastFeeRate is the most recent fee rate used for the input being
249
        // swept within a transaction broadcast to the network.
250
        LastFeeRate chainfee.SatPerKWeight
251

252
        // BroadcastAttempts is the number of attempts we've made to sweept the
253
        // input.
254
        BroadcastAttempts int
255

256
        // Params contains the sweep parameters for this pending request.
257
        Params Params
258

259
        // DeadlineHeight records the deadline height of this input.
260
        DeadlineHeight uint32
261
}
262

263
// updateReq is an internal message we'll use to represent an external caller's
264
// intent to update the sweep parameters of a given input.
265
type updateReq struct {
266
        input        wire.OutPoint
267
        params       Params
268
        responseChan chan *updateResp
269
}
270

271
// updateResp is an internal message we'll use to hand off the response of a
272
// updateReq from the UtxoSweeper's main event loop back to the caller.
273
type updateResp struct {
274
        resultChan chan Result
275
        err        error
276
}
277

278
// UtxoSweeper is responsible for sweeping outputs back into the wallet
279
type UtxoSweeper struct {
280
        started uint32 // To be used atomically.
281
        stopped uint32 // To be used atomically.
282

283
        cfg *UtxoSweeperConfig
284

285
        newInputs chan *sweepInputMessage
286
        spendChan chan *chainntnfs.SpendDetail
287

288
        // pendingSweepsReq is a channel that will be sent requests by external
289
        // callers in order to retrieve the set of pending inputs the
290
        // UtxoSweeper is attempting to sweep.
291
        pendingSweepsReqs chan *pendingSweepsReq
292

293
        // updateReqs is a channel that will be sent requests by external
294
        // callers who wish to bump the fee rate of a given input.
295
        updateReqs chan *updateReq
296

297
        // inputs is the total set of inputs the UtxoSweeper has been requested
298
        // to sweep.
299
        inputs InputsMap
300

301
        currentOutputScript []byte
302

303
        relayFeeRate chainfee.SatPerKWeight
304

305
        quit chan struct{}
306
        wg   sync.WaitGroup
307

308
        // currentHeight is the best known height of the main chain. This is
309
        // updated whenever a new block epoch is received.
310
        currentHeight int32
311

312
        // bumpResultChan is a channel that receives broadcast results from the
313
        // TxPublisher.
314
        bumpResultChan chan *BumpResult
315
}
316

317
// UtxoSweeperConfig contains dependencies of UtxoSweeper.
318
type UtxoSweeperConfig struct {
319
        // GenSweepScript generates a P2WKH script belonging to the wallet where
320
        // funds can be swept.
321
        GenSweepScript func() ([]byte, error)
322

323
        // FeeEstimator is used when crafting sweep transactions to estimate
324
        // the necessary fee relative to the expected size of the sweep
325
        // transaction.
326
        FeeEstimator chainfee.Estimator
327

328
        // Wallet contains the wallet functions that sweeper requires.
329
        Wallet Wallet
330

331
        // Notifier is an instance of a chain notifier we'll use to watch for
332
        // certain on-chain events.
333
        Notifier chainntnfs.ChainNotifier
334

335
        // Mempool is the mempool watcher that will be used to query whether a
336
        // given input is already being spent by a transaction in the mempool.
337
        Mempool chainntnfs.MempoolWatcher
338

339
        // Store stores the published sweeper txes.
340
        Store SweeperStore
341

342
        // Signer is used by the sweeper to generate valid witnesses at the
343
        // time the incubated outputs need to be spent.
344
        Signer input.Signer
345

346
        // MaxInputsPerTx specifies the default maximum number of inputs allowed
347
        // in a single sweep tx. If more need to be swept, multiple txes are
348
        // created and published.
349
        MaxInputsPerTx uint32
350

351
        // MaxFeeRate is the maximum fee rate allowed within the UtxoSweeper.
352
        MaxFeeRate chainfee.SatPerVByte
353

354
        // Aggregator is used to group inputs into clusters based on its
355
        // implemention-specific strategy.
356
        Aggregator UtxoAggregator
357

358
        // Publisher is used to publish the sweep tx crafted here and monitors
359
        // it for potential fee bumps.
360
        Publisher Bumper
361

362
        // NoDeadlineConfTarget is the conf target to use when sweeping
363
        // non-time-sensitive outputs.
364
        NoDeadlineConfTarget uint32
365
}
366

367
// Result is the struct that is pushed through the result channel. Callers can
368
// use this to be informed of the final sweep result. In case of a remote
369
// spend, Err will be ErrRemoteSpend.
370
type Result struct {
371
        // Err is the final result of the sweep. It is nil when the input is
372
        // swept successfully by us. ErrRemoteSpend is returned when another
373
        // party took the input.
374
        Err error
375

376
        // Tx is the transaction that spent the input.
377
        Tx *wire.MsgTx
378
}
379

380
// sweepInputMessage structs are used in the internal channel between the
381
// SweepInput call and the sweeper main loop.
382
type sweepInputMessage struct {
383
        input      input.Input
384
        params     Params
385
        resultChan chan Result
386
}
387

388
// New returns a new Sweeper instance.
389
func New(cfg *UtxoSweeperConfig) *UtxoSweeper {
17✔
390
        return &UtxoSweeper{
17✔
391
                cfg:               cfg,
17✔
392
                newInputs:         make(chan *sweepInputMessage),
17✔
393
                spendChan:         make(chan *chainntnfs.SpendDetail),
17✔
394
                updateReqs:        make(chan *updateReq),
17✔
395
                pendingSweepsReqs: make(chan *pendingSweepsReq),
17✔
396
                quit:              make(chan struct{}),
17✔
397
                inputs:            make(InputsMap),
17✔
398
                bumpResultChan:    make(chan *BumpResult, 100),
17✔
399
        }
17✔
400
}
17✔
401

402
// Start starts the process of constructing and publish sweep txes.
403
func (s *UtxoSweeper) Start() error {
3✔
404
        if !atomic.CompareAndSwapUint32(&s.started, 0, 1) {
3✔
405
                return nil
×
406
        }
×
407

408
        log.Info("Sweeper starting")
3✔
409

3✔
410
        // Retrieve relay fee for dust limit calculation. Assume that this will
3✔
411
        // not change from here on.
3✔
412
        s.relayFeeRate = s.cfg.FeeEstimator.RelayFeePerKW()
3✔
413

3✔
414
        // We need to register for block epochs and retry sweeping every block.
3✔
415
        // We should get a notification with the current best block immediately
3✔
416
        // if we don't provide any epoch. We'll wait for that in the collector.
3✔
417
        blockEpochs, err := s.cfg.Notifier.RegisterBlockEpochNtfn(nil)
3✔
418
        if err != nil {
3✔
419
                return fmt.Errorf("register block epoch ntfn: %w", err)
×
420
        }
×
421

422
        // Start sweeper main loop.
423
        s.wg.Add(1)
3✔
424
        go func() {
6✔
425
                defer blockEpochs.Cancel()
3✔
426
                defer s.wg.Done()
3✔
427

3✔
428
                s.collector(blockEpochs.Epochs)
3✔
429

3✔
430
                // The collector exited and won't longer handle incoming
3✔
431
                // requests. This can happen on shutdown, when the block
3✔
432
                // notifier shuts down before the sweeper and its clients. In
3✔
433
                // order to not deadlock the clients waiting for their requests
3✔
434
                // being handled, we handle them here and immediately return an
3✔
435
                // error. When the sweeper finally is shut down we can exit as
3✔
436
                // the clients will be notified.
3✔
437
                for {
6✔
438
                        select {
3✔
439
                        case inp := <-s.newInputs:
×
440
                                inp.resultChan <- Result{
×
441
                                        Err: ErrSweeperShuttingDown,
×
442
                                }
×
443

444
                        case req := <-s.pendingSweepsReqs:
×
445
                                req.errChan <- ErrSweeperShuttingDown
×
446

447
                        case req := <-s.updateReqs:
×
448
                                req.responseChan <- &updateResp{
×
449
                                        err: ErrSweeperShuttingDown,
×
450
                                }
×
451

452
                        case <-s.quit:
3✔
453
                                return
3✔
454
                        }
455
                }
456
        }()
457

458
        return nil
3✔
459
}
460

461
// RelayFeePerKW returns the minimum fee rate required for transactions to be
462
// relayed.
463
func (s *UtxoSweeper) RelayFeePerKW() chainfee.SatPerKWeight {
×
464
        return s.relayFeeRate
×
465
}
×
466

467
// Stop stops sweeper from listening to block epochs and constructing sweep
468
// txes.
469
func (s *UtxoSweeper) Stop() error {
3✔
470
        if !atomic.CompareAndSwapUint32(&s.stopped, 0, 1) {
3✔
471
                return nil
×
472
        }
×
473

474
        log.Info("Sweeper shutting down...")
3✔
475
        defer log.Debug("Sweeper shutdown complete")
3✔
476

3✔
477
        close(s.quit)
3✔
478
        s.wg.Wait()
3✔
479

3✔
480
        return nil
3✔
481
}
482

483
// SweepInput sweeps inputs back into the wallet. The inputs will be batched and
484
// swept after the batch time window ends. A custom fee preference can be
485
// provided to determine what fee rate should be used for the input. Note that
486
// the input may not always be swept with this exact value, as its possible for
487
// it to be batched under the same transaction with other similar fee rate
488
// inputs.
489
//
490
// NOTE: Extreme care needs to be taken that input isn't changed externally.
491
// Because it is an interface and we don't know what is exactly behind it, we
492
// cannot make a local copy in sweeper.
493
//
494
// TODO(yy): make sure the caller is using the Result chan.
495
func (s *UtxoSweeper) SweepInput(inp input.Input,
496
        params Params) (chan Result, error) {
3✔
497

3✔
498
        if inp == nil || inp.OutPoint() == input.EmptyOutPoint ||
3✔
499
                inp.SignDesc() == nil {
3✔
500

×
501
                return nil, errors.New("nil input received")
×
502
        }
×
503

504
        absoluteTimeLock, _ := inp.RequiredLockTime()
3✔
505
        log.Infof("Sweep request received: out_point=%v, witness_type=%v, "+
3✔
506
                "relative_time_lock=%v, absolute_time_lock=%v, amount=%v, "+
3✔
507
                "parent=(%v), params=(%v)", inp.OutPoint(), inp.WitnessType(),
3✔
508
                inp.BlocksToMaturity(), absoluteTimeLock,
3✔
509
                btcutil.Amount(inp.SignDesc().Output.Value),
3✔
510
                inp.UnconfParent(), params)
3✔
511

3✔
512
        sweeperInput := &sweepInputMessage{
3✔
513
                input:      inp,
3✔
514
                params:     params,
3✔
515
                resultChan: make(chan Result, 1),
3✔
516
        }
3✔
517

3✔
518
        // Deliver input to the main event loop.
3✔
519
        select {
3✔
520
        case s.newInputs <- sweeperInput:
3✔
521
        case <-s.quit:
×
522
                return nil, ErrSweeperShuttingDown
×
523
        }
524

525
        return sweeperInput.resultChan, nil
3✔
526
}
527

528
// removeConflictSweepDescendants removes any transactions from the wallet that
529
// spend outputs included in the passed outpoint set. This needs to be done in
530
// cases where we're not the only ones that can sweep an output, but there may
531
// exist unconfirmed spends that spend outputs created by a sweep transaction.
532
// The most common case for this is when someone sweeps our anchor outputs
533
// after 16 blocks. Moreover this is also needed for wallets which use neutrino
534
// as a backend when a channel is force closed and anchor cpfp txns are
535
// created to bump the initial commitment transaction. In this case an anchor
536
// cpfp is broadcasted for up to 3 commitment transactions (local,
537
// remote-dangling, remote). Using neutrino all of those transactions will be
538
// accepted (the commitment tx will be different in all of those cases) and have
539
// to be removed as soon as one of them confirmes (they do have the same
540
// ExclusiveGroup). For neutrino backends the corresponding BIP 157 serving full
541
// nodes do not signal invalid transactions anymore.
542
func (s *UtxoSweeper) removeConflictSweepDescendants(
543
        outpoints map[wire.OutPoint]struct{}) error {
3✔
544

3✔
545
        // Obtain all the past sweeps that we've done so far. We'll need these
3✔
546
        // to ensure that if the spendingTx spends any of the same inputs, then
3✔
547
        // we remove any transaction that may be spending those inputs from the
3✔
548
        // wallet.
3✔
549
        //
3✔
550
        // TODO(roasbeef): can be last sweep here if we remove anything confirmed
3✔
551
        // from the store?
3✔
552
        pastSweepHashes, err := s.cfg.Store.ListSweeps()
3✔
553
        if err != nil {
3✔
554
                return err
×
555
        }
×
556

557
        // We'll now go through each past transaction we published during this
558
        // epoch and cross reference the spent inputs. If there're any inputs
559
        // in common with the inputs the spendingTx spent, then we'll remove
560
        // those.
561
        //
562
        // TODO(roasbeef): need to start to remove all transaction hashes after
563
        // every N blocks (assumed point of no return)
564
        for _, sweepHash := range pastSweepHashes {
6✔
565
                sweepTx, err := s.cfg.Wallet.FetchTx(sweepHash)
3✔
566
                if err != nil {
3✔
567
                        return err
×
568
                }
×
569

570
                // Transaction wasn't found in the wallet, may have already
571
                // been replaced/removed.
572
                if sweepTx == nil {
5✔
573
                        // If it was removed, then we'll play it safe and mark
2✔
574
                        // it as no longer need to be rebroadcasted.
2✔
575
                        s.cfg.Wallet.CancelRebroadcast(sweepHash)
2✔
576
                        continue
2✔
577
                }
578

579
                // Check to see if this past sweep transaction spent any of the
580
                // same inputs as spendingTx.
581
                var isConflicting bool
3✔
582
                for _, txIn := range sweepTx.TxIn {
6✔
583
                        if _, ok := outpoints[txIn.PreviousOutPoint]; ok {
6✔
584
                                isConflicting = true
3✔
585
                                break
3✔
586
                        }
587
                }
588

589
                if !isConflicting {
6✔
590
                        continue
3✔
591
                }
592

593
                // If it is conflicting, then we'll signal the wallet to remove
594
                // all the transactions that are descendants of outputs created
595
                // by the sweepTx and the sweepTx itself.
596
                log.Debugf("Removing sweep txid=%v from wallet: %v",
3✔
597
                        sweepTx.TxHash(), spew.Sdump(sweepTx))
3✔
598

3✔
599
                err = s.cfg.Wallet.RemoveDescendants(sweepTx)
3✔
600
                if err != nil {
3✔
601
                        log.Warnf("Unable to remove descendants: %v", err)
×
602
                }
×
603

604
                // If this transaction was conflicting, then we'll stop
605
                // rebroadcasting it in the background.
606
                s.cfg.Wallet.CancelRebroadcast(sweepHash)
3✔
607
        }
608

609
        return nil
3✔
610
}
611

612
// collector is the sweeper main loop. It processes new inputs, spend
613
// notifications and counts down to publication of the sweep tx.
614
func (s *UtxoSweeper) collector(blockEpochs <-chan *chainntnfs.BlockEpoch) {
3✔
615
        // We registered for the block epochs with a nil request. The notifier
3✔
616
        // should send us the current best block immediately. So we need to wait
3✔
617
        // for it here because we need to know the current best height.
3✔
618
        select {
3✔
619
        case bestBlock := <-blockEpochs:
3✔
620
                s.currentHeight = bestBlock.Height
3✔
621

622
        case <-s.quit:
×
623
                return
×
624
        }
625

626
        for {
6✔
627
                // Clean inputs, which will remove inputs that are swept,
3✔
628
                // failed, or excluded from the sweeper and return inputs that
3✔
629
                // are either new or has been published but failed back, which
3✔
630
                // will be retried again here.
3✔
631
                s.updateSweeperInputs()
3✔
632

3✔
633
                select {
3✔
634
                // A new inputs is offered to the sweeper. We check to see if
635
                // we are already trying to sweep this input and if not, set up
636
                // a listener to spend and schedule a sweep.
637
                case input := <-s.newInputs:
3✔
638
                        err := s.handleNewInput(input)
3✔
639
                        if err != nil {
3✔
640
                                log.Criticalf("Unable to handle new input: %v",
×
641
                                        err)
×
642

×
643
                                return
×
644
                        }
×
645

646
                        // If this input is forced, we perform an sweep
647
                        // immediately.
648
                        if input.params.Immediate {
6✔
649
                                inputs := s.updateSweeperInputs()
3✔
650
                                s.sweepPendingInputs(inputs)
3✔
651
                        }
3✔
652

653
                // A spend of one of our inputs is detected. Signal sweep
654
                // results to the caller(s).
655
                case spend := <-s.spendChan:
3✔
656
                        s.handleInputSpent(spend)
3✔
657

658
                // A new external request has been received to retrieve all of
659
                // the inputs we're currently attempting to sweep.
660
                case req := <-s.pendingSweepsReqs:
3✔
661
                        s.handlePendingSweepsReq(req)
3✔
662

663
                // A new external request has been received to bump the fee rate
664
                // of a given input.
665
                case req := <-s.updateReqs:
3✔
666
                        resultChan, err := s.handleUpdateReq(req)
3✔
667
                        req.responseChan <- &updateResp{
3✔
668
                                resultChan: resultChan,
3✔
669
                                err:        err,
3✔
670
                        }
3✔
671

3✔
672
                        // Perform an sweep immediately if asked.
3✔
673
                        if req.params.Immediate {
6✔
674
                                inputs := s.updateSweeperInputs()
3✔
675
                                s.sweepPendingInputs(inputs)
3✔
676
                        }
3✔
677

678
                case result := <-s.bumpResultChan:
3✔
679
                        // Handle the bump event.
3✔
680
                        err := s.handleBumpEvent(result)
3✔
681
                        if err != nil {
6✔
682
                                log.Errorf("Failed to handle bump event: %v",
3✔
683
                                        err)
3✔
684
                        }
3✔
685

686
                // A new block comes in, update the bestHeight, perform a check
687
                // over all pending inputs and publish sweeping txns if needed.
688
                case epoch, ok := <-blockEpochs:
3✔
689
                        if !ok {
3✔
690
                                // We should stop the sweeper before stopping
×
691
                                // the chain service. Otherwise it indicates an
×
692
                                // error.
×
693
                                log.Error("Block epoch channel closed")
×
694

×
695
                                return
×
696
                        }
×
697

698
                        // Update the sweeper to the best height.
699
                        s.currentHeight = epoch.Height
3✔
700

3✔
701
                        // Update the inputs with the latest height.
3✔
702
                        inputs := s.updateSweeperInputs()
3✔
703

3✔
704
                        log.Debugf("Received new block: height=%v, attempt "+
3✔
705
                                "sweeping %d inputs", epoch.Height, len(inputs))
3✔
706

3✔
707
                        // Attempt to sweep any pending inputs.
3✔
708
                        s.sweepPendingInputs(inputs)
3✔
709

710
                case <-s.quit:
3✔
711
                        return
3✔
712
                }
713
        }
714
}
715

716
// removeExclusiveGroup removes all inputs in the given exclusive group. This
717
// function is called when one of the exclusive group inputs has been spent. The
718
// other inputs won't ever be spendable and can be removed. This also prevents
719
// them from being part of future sweep transactions that would fail. In
720
// addition sweep transactions of those inputs will be removed from the wallet.
721
func (s *UtxoSweeper) removeExclusiveGroup(group uint64) {
3✔
722
        for outpoint, input := range s.inputs {
6✔
723
                outpoint := outpoint
3✔
724

3✔
725
                // Skip inputs that aren't exclusive.
3✔
726
                if input.params.ExclusiveGroup == nil {
6✔
727
                        continue
3✔
728
                }
729

730
                // Skip inputs from other exclusive groups.
731
                if *input.params.ExclusiveGroup != group {
3✔
732
                        continue
×
733
                }
734

735
                // Skip inputs that are already terminated.
736
                if input.terminated() {
6✔
737
                        log.Tracef("Skipped sending error result for "+
3✔
738
                                "input %v, state=%v", outpoint, input.state)
3✔
739

3✔
740
                        continue
3✔
741
                }
742

743
                // Signal result channels.
744
                s.signalResult(input, Result{
3✔
745
                        Err: ErrExclusiveGroupSpend,
3✔
746
                })
3✔
747

3✔
748
                // Update the input's state as it can no longer be swept.
3✔
749
                input.state = Excluded
3✔
750

3✔
751
                // Remove all unconfirmed transactions from the wallet which
3✔
752
                // spend the passed outpoint of the same exclusive group.
3✔
753
                outpoints := map[wire.OutPoint]struct{}{
3✔
754
                        outpoint: {},
3✔
755
                }
3✔
756
                err := s.removeConflictSweepDescendants(outpoints)
3✔
757
                if err != nil {
3✔
758
                        log.Warnf("Unable to remove conflicting sweep tx from "+
×
759
                                "wallet for outpoint %v : %v", outpoint, err)
×
760
                }
×
761
        }
762
}
763

764
// signalResult notifies the listeners of the final result of the input sweep.
765
// It also cancels any pending spend notification.
766
func (s *UtxoSweeper) signalResult(pi *SweeperInput, result Result) {
6✔
767
        op := pi.OutPoint()
6✔
768
        listeners := pi.listeners
6✔
769

6✔
770
        if result.Err == nil {
11✔
771
                log.Tracef("Dispatching sweep success for %v to %v listeners",
5✔
772
                        op, len(listeners),
5✔
773
                )
5✔
774
        } else {
9✔
775
                log.Tracef("Dispatching sweep error for %v to %v listeners: %v",
4✔
776
                        op, len(listeners), result.Err,
4✔
777
                )
4✔
778
        }
4✔
779

780
        // Signal all listeners. Channel is buffered. Because we only send once
781
        // on every channel, it should never block.
782
        for _, resultChan := range listeners {
9✔
783
                resultChan <- result
3✔
784
        }
3✔
785

786
        // Cancel spend notification with chain notifier. This is not necessary
787
        // in case of a success, except for that a reorg could still happen.
788
        if pi.ntfnRegCancel != nil {
9✔
789
                log.Debugf("Canceling spend ntfn for %v", op)
3✔
790

3✔
791
                pi.ntfnRegCancel()
3✔
792
        }
3✔
793
}
794

795
// sweep takes a set of preselected inputs, creates a sweep tx and publishes
796
// the tx. The output address is only marked as used if the publish succeeds.
797
func (s *UtxoSweeper) sweep(set InputSet) error {
5✔
798
        // Generate an output script if there isn't an unused script available.
5✔
799
        if s.currentOutputScript == nil {
9✔
800
                pkScript, err := s.cfg.GenSweepScript()
4✔
801
                if err != nil {
4✔
802
                        return fmt.Errorf("gen sweep script: %w", err)
×
803
                }
×
804
                s.currentOutputScript = pkScript
4✔
805
        }
806

807
        // Create a fee bump request and ask the publisher to broadcast it. The
808
        // publisher will then take over and start monitoring the tx for
809
        // potential fee bump.
810
        req := &BumpRequest{
5✔
811
                Inputs:          set.Inputs(),
5✔
812
                Budget:          set.Budget(),
5✔
813
                DeadlineHeight:  set.DeadlineHeight(),
5✔
814
                DeliveryAddress: s.currentOutputScript,
5✔
815
                MaxFeeRate:      s.cfg.MaxFeeRate.FeePerKWeight(),
5✔
816
                StartingFeeRate: set.StartingFeeRate(),
5✔
817
                // TODO(yy): pass the strategy here.
5✔
818
        }
5✔
819

5✔
820
        // Reschedule the inputs that we just tried to sweep. This is done in
5✔
821
        // case the following publish fails, we'd like to update the inputs'
5✔
822
        // publish attempts and rescue them in the next sweep.
5✔
823
        s.markInputsPendingPublish(set)
5✔
824

5✔
825
        // Broadcast will return a read-only chan that we will listen to for
5✔
826
        // this publish result and future RBF attempt.
5✔
827
        resp, err := s.cfg.Publisher.Broadcast(req)
5✔
828
        if err != nil {
10✔
829
                outpoints := make([]wire.OutPoint, len(set.Inputs()))
5✔
830
                for i, inp := range set.Inputs() {
8✔
831
                        outpoints[i] = inp.OutPoint()
3✔
832
                }
3✔
833

834
                log.Errorf("Initial broadcast failed: %v, inputs=\n%v", err,
5✔
835
                        inputTypeSummary(set.Inputs()))
5✔
836

5✔
837
                // TODO(yy): find out which input is causing the failure.
5✔
838
                s.markInputsPublishFailed(outpoints)
5✔
839

5✔
840
                return err
5✔
841
        }
842

843
        // Successfully sent the broadcast attempt, we now handle the result by
844
        // subscribing to the result chan and listen for future updates about
845
        // this tx.
846
        s.wg.Add(1)
3✔
847
        go s.monitorFeeBumpResult(resp)
3✔
848

3✔
849
        return nil
3✔
850
}
851

852
// markInputsPendingPublish updates the pending inputs with the given tx
853
// inputs. It also increments the `publishAttempts`.
854
func (s *UtxoSweeper) markInputsPendingPublish(set InputSet) {
6✔
855
        // Reschedule sweep.
6✔
856
        for _, input := range set.Inputs() {
13✔
857
                pi, ok := s.inputs[input.OutPoint()]
7✔
858
                if !ok {
11✔
859
                        // It could be that this input is an additional wallet
4✔
860
                        // input that was attached. In that case there also
4✔
861
                        // isn't a pending input to update.
4✔
862
                        log.Tracef("Skipped marking input as pending "+
4✔
863
                                "published: %v not found in pending inputs",
4✔
864
                                input.OutPoint())
4✔
865

4✔
866
                        continue
4✔
867
                }
868

869
                // If this input has already terminated, there's clearly
870
                // something wrong as it would have been removed. In this case
871
                // we log an error and skip marking this input as pending
872
                // publish.
873
                if pi.terminated() {
7✔
874
                        log.Errorf("Expect input %v to not have terminated "+
1✔
875
                                "state, instead it has %v",
1✔
876
                                input.OutPoint, pi.state)
1✔
877

1✔
878
                        continue
1✔
879
                }
880

881
                // Update the input's state.
882
                pi.state = PendingPublish
5✔
883

5✔
884
                // Record another publish attempt.
5✔
885
                pi.publishAttempts++
5✔
886
        }
887
}
888

889
// markInputsPublished updates the sweeping tx in db and marks the list of
890
// inputs as published.
891
func (s *UtxoSweeper) markInputsPublished(tr *TxRecord,
892
        inputs []*wire.TxIn) error {
7✔
893

7✔
894
        // Mark this tx in db once successfully published.
7✔
895
        //
7✔
896
        // NOTE: this will behave as an overwrite, which is fine as the record
7✔
897
        // is small.
7✔
898
        tr.Published = true
7✔
899
        err := s.cfg.Store.StoreTx(tr)
7✔
900
        if err != nil {
8✔
901
                return fmt.Errorf("store tx: %w", err)
1✔
902
        }
1✔
903

904
        // Reschedule sweep.
905
        for _, input := range inputs {
14✔
906
                pi, ok := s.inputs[input.PreviousOutPoint]
8✔
907
                if !ok {
12✔
908
                        // It could be that this input is an additional wallet
4✔
909
                        // input that was attached. In that case there also
4✔
910
                        // isn't a pending input to update.
4✔
911
                        log.Tracef("Skipped marking input as published: %v "+
4✔
912
                                "not found in pending inputs",
4✔
913
                                input.PreviousOutPoint)
4✔
914

4✔
915
                        continue
4✔
916
                }
917

918
                // Valdiate that the input is in an expected state.
919
                if pi.state != PendingPublish {
11✔
920
                        // We may get a Published if this is a replacement tx.
4✔
921
                        log.Debugf("Expect input %v to have %v, instead it "+
4✔
922
                                "has %v", input.PreviousOutPoint,
4✔
923
                                PendingPublish, pi.state)
4✔
924

4✔
925
                        continue
4✔
926
                }
927

928
                // Update the input's state.
929
                pi.state = Published
6✔
930

6✔
931
                // Update the input's latest fee rate.
6✔
932
                pi.lastFeeRate = chainfee.SatPerKWeight(tr.FeeRate)
6✔
933
        }
934

935
        return nil
6✔
936
}
937

938
// markInputsPublishFailed marks the list of inputs as failed to be published.
939
func (s *UtxoSweeper) markInputsPublishFailed(outpoints []wire.OutPoint) {
7✔
940
        // Reschedule sweep.
7✔
941
        for _, op := range outpoints {
21✔
942
                pi, ok := s.inputs[op]
14✔
943
                if !ok {
19✔
944
                        // It could be that this input is an additional wallet
5✔
945
                        // input that was attached. In that case there also
5✔
946
                        // isn't a pending input to update.
5✔
947
                        log.Tracef("Skipped marking input as publish failed: "+
5✔
948
                                "%v not found in pending inputs", op)
5✔
949

5✔
950
                        continue
5✔
951
                }
952

953
                // Valdiate that the input is in an expected state.
954
                if pi.state != PendingPublish && pi.state != Published {
18✔
955
                        log.Debugf("Expect input %v to have %v, instead it "+
6✔
956
                                "has %v", op, PendingPublish, pi.state)
6✔
957

6✔
958
                        continue
6✔
959
                }
960

961
                log.Warnf("Failed to publish input %v", op)
7✔
962

7✔
963
                // Update the input's state.
7✔
964
                pi.state = PublishFailed
7✔
965
        }
966
}
967

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

3✔
973
        log.Tracef("Wait for spend of %v at heightHint=%v",
3✔
974
                outpoint, heightHint)
3✔
975

3✔
976
        spendEvent, err := s.cfg.Notifier.RegisterSpendNtfn(
3✔
977
                &outpoint, script, heightHint,
3✔
978
        )
3✔
979
        if err != nil {
3✔
980
                return nil, fmt.Errorf("register spend ntfn: %w", err)
×
981
        }
×
982

983
        s.wg.Add(1)
3✔
984
        go func() {
6✔
985
                defer s.wg.Done()
3✔
986

3✔
987
                select {
3✔
988
                case spend, ok := <-spendEvent.Spend:
3✔
989
                        if !ok {
6✔
990
                                log.Debugf("Spend ntfn for %v canceled",
3✔
991
                                        outpoint)
3✔
992
                                return
3✔
993
                        }
3✔
994

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

3✔
997
                        select {
3✔
998
                        case s.spendChan <- spend:
3✔
999
                                log.Debugf("Delivered spend ntfn for %v",
3✔
1000
                                        outpoint)
3✔
1001

1002
                        case <-s.quit:
×
1003
                        }
1004
                case <-s.quit:
3✔
1005
                }
1006
        }()
1007

1008
        return spendEvent.Cancel, nil
3✔
1009
}
1010

1011
// PendingInputs returns the set of inputs that the UtxoSweeper is currently
1012
// attempting to sweep.
1013
func (s *UtxoSweeper) PendingInputs() (
1014
        map[wire.OutPoint]*PendingInputResponse, error) {
3✔
1015

3✔
1016
        respChan := make(chan map[wire.OutPoint]*PendingInputResponse, 1)
3✔
1017
        errChan := make(chan error, 1)
3✔
1018
        select {
3✔
1019
        case s.pendingSweepsReqs <- &pendingSweepsReq{
1020
                respChan: respChan,
1021
                errChan:  errChan,
1022
        }:
3✔
1023
        case <-s.quit:
×
1024
                return nil, ErrSweeperShuttingDown
×
1025
        }
1026

1027
        select {
3✔
1028
        case pendingSweeps := <-respChan:
3✔
1029
                return pendingSweeps, nil
3✔
1030
        case err := <-errChan:
×
1031
                return nil, err
×
1032
        case <-s.quit:
×
1033
                return nil, ErrSweeperShuttingDown
×
1034
        }
1035
}
1036

1037
// handlePendingSweepsReq handles a request to retrieve all pending inputs the
1038
// UtxoSweeper is attempting to sweep.
1039
func (s *UtxoSweeper) handlePendingSweepsReq(
1040
        req *pendingSweepsReq) map[wire.OutPoint]*PendingInputResponse {
3✔
1041

3✔
1042
        resps := make(map[wire.OutPoint]*PendingInputResponse, len(s.inputs))
3✔
1043
        for _, inp := range s.inputs {
6✔
1044
                // Only the exported fields are set, as we expect the response
3✔
1045
                // to only be consumed externally.
3✔
1046
                op := inp.OutPoint()
3✔
1047
                resps[op] = &PendingInputResponse{
3✔
1048
                        OutPoint:    op,
3✔
1049
                        WitnessType: inp.WitnessType(),
3✔
1050
                        Amount: btcutil.Amount(
3✔
1051
                                inp.SignDesc().Output.Value,
3✔
1052
                        ),
3✔
1053
                        LastFeeRate:       inp.lastFeeRate,
3✔
1054
                        BroadcastAttempts: inp.publishAttempts,
3✔
1055
                        Params:            inp.params,
3✔
1056
                        DeadlineHeight:    uint32(inp.DeadlineHeight),
3✔
1057
                }
3✔
1058
        }
3✔
1059

1060
        select {
3✔
1061
        case req.respChan <- resps:
3✔
1062
        case <-s.quit:
×
1063
                log.Debug("Skipped sending pending sweep response due to " +
×
1064
                        "UtxoSweeper shutting down")
×
1065
        }
1066

1067
        return resps
3✔
1068
}
1069

1070
// UpdateParams allows updating the sweep parameters of a pending input in the
1071
// UtxoSweeper. This function can be used to provide an updated fee preference
1072
// and force flag that will be used for a new sweep transaction of the input
1073
// that will act as a replacement transaction (RBF) of the original sweeping
1074
// transaction, if any. The exclusive group is left unchanged.
1075
//
1076
// NOTE: This currently doesn't do any fee rate validation to ensure that a bump
1077
// is actually successful. The responsibility of doing so should be handled by
1078
// the caller.
1079
func (s *UtxoSweeper) UpdateParams(input wire.OutPoint,
1080
        params Params) (chan Result, error) {
3✔
1081

3✔
1082
        responseChan := make(chan *updateResp, 1)
3✔
1083
        select {
3✔
1084
        case s.updateReqs <- &updateReq{
1085
                input:        input,
1086
                params:       params,
1087
                responseChan: responseChan,
1088
        }:
3✔
1089
        case <-s.quit:
×
1090
                return nil, ErrSweeperShuttingDown
×
1091
        }
1092

1093
        select {
3✔
1094
        case response := <-responseChan:
3✔
1095
                return response.resultChan, response.err
3✔
1096
        case <-s.quit:
×
1097
                return nil, ErrSweeperShuttingDown
×
1098
        }
1099
}
1100

1101
// handleUpdateReq handles an update request by simply updating the sweep
1102
// parameters of the pending input. Currently, no validation is done on the new
1103
// fee preference to ensure it will properly create a replacement transaction.
1104
//
1105
// TODO(wilmer):
1106
//   - Validate fee preference to ensure we'll create a valid replacement
1107
//     transaction to allow the new fee rate to propagate throughout the
1108
//     network.
1109
//   - Ensure we don't combine this input with any other unconfirmed inputs that
1110
//     did not exist in the original sweep transaction, resulting in an invalid
1111
//     replacement transaction.
1112
func (s *UtxoSweeper) handleUpdateReq(req *updateReq) (
1113
        chan Result, error) {
3✔
1114

3✔
1115
        // If the UtxoSweeper is already trying to sweep this input, then we can
3✔
1116
        // simply just increase its fee rate. This will allow the input to be
3✔
1117
        // batched with others which also have a similar fee rate, creating a
3✔
1118
        // higher fee rate transaction that replaces the original input's
3✔
1119
        // sweeping transaction.
3✔
1120
        sweeperInput, ok := s.inputs[req.input]
3✔
1121
        if !ok {
3✔
1122
                return nil, lnwallet.ErrNotMine
×
1123
        }
×
1124

1125
        // Create the updated parameters struct. Leave the exclusive group
1126
        // unchanged.
1127
        newParams := Params{
3✔
1128
                StartingFeeRate: req.params.StartingFeeRate,
3✔
1129
                Immediate:       req.params.Immediate,
3✔
1130
                Budget:          req.params.Budget,
3✔
1131
                DeadlineHeight:  req.params.DeadlineHeight,
3✔
1132
                ExclusiveGroup:  sweeperInput.params.ExclusiveGroup,
3✔
1133
        }
3✔
1134

3✔
1135
        log.Debugf("Updating parameters for %v(state=%v) from (%v) to (%v)",
3✔
1136
                req.input, sweeperInput.state, sweeperInput.params, newParams)
3✔
1137

3✔
1138
        sweeperInput.params = newParams
3✔
1139

3✔
1140
        // We need to reset the state so this input will be attempted again by
3✔
1141
        // our sweeper.
3✔
1142
        //
3✔
1143
        // TODO(yy): a dedicated state?
3✔
1144
        sweeperInput.state = Init
3✔
1145

3✔
1146
        // If the new input specifies a deadline, update the deadline height.
3✔
1147
        sweeperInput.DeadlineHeight = req.params.DeadlineHeight.UnwrapOr(
3✔
1148
                sweeperInput.DeadlineHeight,
3✔
1149
        )
3✔
1150

3✔
1151
        resultChan := make(chan Result, 1)
3✔
1152
        sweeperInput.listeners = append(sweeperInput.listeners, resultChan)
3✔
1153

3✔
1154
        return resultChan, nil
3✔
1155
}
1156

1157
// ListSweeps returns a list of the sweeps recorded by the sweep store.
1158
func (s *UtxoSweeper) ListSweeps() ([]chainhash.Hash, error) {
3✔
1159
        return s.cfg.Store.ListSweeps()
3✔
1160
}
3✔
1161

1162
// mempoolLookup takes an input's outpoint and queries the mempool to see
1163
// whether it's already been spent in a transaction found in the mempool.
1164
// Returns the transaction if found.
1165
func (s *UtxoSweeper) mempoolLookup(op wire.OutPoint) fn.Option[wire.MsgTx] {
10✔
1166
        // For neutrino backend, there's no mempool available, so we exit
10✔
1167
        // early.
10✔
1168
        if s.cfg.Mempool == nil {
11✔
1169
                log.Debugf("Skipping mempool lookup for %v, no mempool ", op)
1✔
1170

1✔
1171
                return fn.None[wire.MsgTx]()
1✔
1172
        }
1✔
1173

1174
        // Query this input in the mempool. If this outpoint is already spent
1175
        // in mempool, we should get a spending event back immediately.
1176
        return s.cfg.Mempool.LookupInputMempoolSpend(op)
9✔
1177
}
1178

1179
// handleNewInput processes a new input by registering spend notification and
1180
// scheduling sweeping for it.
1181
func (s *UtxoSweeper) handleNewInput(input *sweepInputMessage) error {
3✔
1182
        // Create a default deadline height, which will be used when there's no
3✔
1183
        // DeadlineHeight specified for a given input.
3✔
1184
        defaultDeadline := s.currentHeight + int32(s.cfg.NoDeadlineConfTarget)
3✔
1185

3✔
1186
        outpoint := input.input.OutPoint()
3✔
1187
        pi, pending := s.inputs[outpoint]
3✔
1188
        if pending {
6✔
1189
                log.Debugf("Already has pending input %v received", outpoint)
3✔
1190

3✔
1191
                s.handleExistingInput(input, pi)
3✔
1192

3✔
1193
                return nil
3✔
1194
        }
3✔
1195

1196
        // This is a new input, and we want to query the mempool to see if this
1197
        // input has already been spent. If so, we'll start the input with
1198
        // state Published and attach the RBFInfo.
1199
        state, rbfInfo := s.decideStateAndRBFInfo(input.input.OutPoint())
3✔
1200

3✔
1201
        // Create a new pendingInput and initialize the listeners slice with
3✔
1202
        // the passed in result channel. If this input is offered for sweep
3✔
1203
        // again, the result channel will be appended to this slice.
3✔
1204
        pi = &SweeperInput{
3✔
1205
                state:     state,
3✔
1206
                listeners: []chan Result{input.resultChan},
3✔
1207
                Input:     input.input,
3✔
1208
                params:    input.params,
3✔
1209
                rbf:       rbfInfo,
3✔
1210
                // Set the acutal deadline height.
3✔
1211
                DeadlineHeight: input.params.DeadlineHeight.UnwrapOr(
3✔
1212
                        defaultDeadline,
3✔
1213
                ),
3✔
1214
        }
3✔
1215

3✔
1216
        s.inputs[outpoint] = pi
3✔
1217
        log.Tracef("input %v, state=%v, added to inputs", outpoint, pi.state)
3✔
1218

3✔
1219
        // Start watching for spend of this input, either by us or the remote
3✔
1220
        // party.
3✔
1221
        cancel, err := s.monitorSpend(
3✔
1222
                outpoint, input.input.SignDesc().Output.PkScript,
3✔
1223
                input.input.HeightHint(),
3✔
1224
        )
3✔
1225
        if err != nil {
3✔
1226
                err := fmt.Errorf("wait for spend: %w", err)
×
1227
                s.markInputFailed(pi, err)
×
1228

×
1229
                return err
×
1230
        }
×
1231

1232
        pi.ntfnRegCancel = cancel
3✔
1233

3✔
1234
        return nil
3✔
1235
}
1236

1237
// decideStateAndRBFInfo queries the mempool to see whether the given input has
1238
// already been spent. If so, the state Published will be returned, otherwise
1239
// state Init. When spent, it will query the sweeper store to fetch the fee
1240
// info of the spending transction, and construct an RBFInfo based on it.
1241
// Suppose an error occurs, fn.None is returned.
1242
func (s *UtxoSweeper) decideStateAndRBFInfo(op wire.OutPoint) (
1243
        SweepState, fn.Option[RBFInfo]) {
7✔
1244

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

7✔
1248
        // Extract the spending tx from the option.
7✔
1249
        var tx *wire.MsgTx
7✔
1250
        txOption.WhenSome(func(t wire.MsgTx) {
13✔
1251
                tx = &t
6✔
1252
        })
6✔
1253

1254
        // Exit early if it's not found.
1255
        //
1256
        // NOTE: this is not accurate for backends that don't support mempool
1257
        // lookup:
1258
        // - for neutrino we don't have a mempool.
1259
        // - for btcd below v0.24.1 we don't have `gettxspendingprevout`.
1260
        if tx == nil {
11✔
1261
                return Init, fn.None[RBFInfo]()
4✔
1262
        }
4✔
1263

1264
        // Otherwise the input is already spent in the mempool, so eventually
1265
        // we will return Published.
1266
        //
1267
        // We also need to update the RBF info for this input. If the sweeping
1268
        // transaction is broadcast by us, we can find the fee info in the
1269
        // sweeper store.
1270
        txid := tx.TxHash()
6✔
1271
        tr, err := s.cfg.Store.GetTx(txid)
6✔
1272

6✔
1273
        // If the tx is not found in the store, it means it's not broadcast by
6✔
1274
        // us, hence we can't find the fee info. This is fine as, later on when
6✔
1275
        // this tx is confirmed, we will remove the input from our inputs.
6✔
1276
        if errors.Is(err, ErrTxNotFound) {
10✔
1277
                log.Warnf("Spending tx %v not found in sweeper store", txid)
4✔
1278
                return Published, fn.None[RBFInfo]()
4✔
1279
        }
4✔
1280

1281
        // Exit if we get an db error.
1282
        if err != nil {
6✔
1283
                log.Errorf("Unable to get tx %v from sweeper store: %v",
1✔
1284
                        txid, err)
1✔
1285

1✔
1286
                return Published, fn.None[RBFInfo]()
1✔
1287
        }
1✔
1288

1289
        // Prepare the fee info and return it.
1290
        rbf := fn.Some(RBFInfo{
4✔
1291
                Txid:    txid,
4✔
1292
                Fee:     btcutil.Amount(tr.Fee),
4✔
1293
                FeeRate: chainfee.SatPerKWeight(tr.FeeRate),
4✔
1294
        })
4✔
1295

4✔
1296
        return Published, rbf
4✔
1297
}
1298

1299
// handleExistingInput processes an input that is already known to the sweeper.
1300
// It will overwrite the params of the old input with the new ones.
1301
func (s *UtxoSweeper) handleExistingInput(input *sweepInputMessage,
1302
        oldInput *SweeperInput) {
3✔
1303

3✔
1304
        // Before updating the input details, check if an exclusive group was
3✔
1305
        // set. In case the same input is registered again without an exclusive
3✔
1306
        // group set, the previous input and its sweep parameters are outdated
3✔
1307
        // hence need to be replaced. This scenario currently only happens for
3✔
1308
        // anchor outputs. When a channel is force closed, in the worst case 3
3✔
1309
        // different sweeps with the same exclusive group are registered with
3✔
1310
        // the sweeper to bump the closing transaction (cpfp) when its time
3✔
1311
        // critical. Receiving an input which was already registered with the
3✔
1312
        // sweeper but now without an exclusive group means non of the previous
3✔
1313
        // inputs were used as CPFP, so we need to make sure we update the
3✔
1314
        // sweep parameters but also remove all inputs with the same exclusive
3✔
1315
        // group because the are outdated too.
3✔
1316
        var prevExclGroup *uint64
3✔
1317
        if oldInput.params.ExclusiveGroup != nil &&
3✔
1318
                input.params.ExclusiveGroup == nil {
6✔
1319

3✔
1320
                prevExclGroup = new(uint64)
3✔
1321
                *prevExclGroup = *oldInput.params.ExclusiveGroup
3✔
1322
        }
3✔
1323

1324
        // Update input details and sweep parameters. The re-offered input
1325
        // details may contain a change to the unconfirmed parent tx info.
1326
        oldInput.params = input.params
3✔
1327
        oldInput.Input = input.input
3✔
1328

3✔
1329
        // If the new input specifies a deadline, update the deadline height.
3✔
1330
        oldInput.DeadlineHeight = input.params.DeadlineHeight.UnwrapOr(
3✔
1331
                oldInput.DeadlineHeight,
3✔
1332
        )
3✔
1333

3✔
1334
        // Add additional result channel to signal spend of this input.
3✔
1335
        oldInput.listeners = append(oldInput.listeners, input.resultChan)
3✔
1336

3✔
1337
        if prevExclGroup != nil {
6✔
1338
                s.removeExclusiveGroup(*prevExclGroup)
3✔
1339
        }
3✔
1340
}
1341

1342
// handleInputSpent takes a spend event of our input and updates the sweeper's
1343
// internal state to remove the input.
1344
func (s *UtxoSweeper) handleInputSpent(spend *chainntnfs.SpendDetail) {
3✔
1345
        // Query store to find out if we ever published this tx.
3✔
1346
        spendHash := *spend.SpenderTxHash
3✔
1347
        isOurTx, err := s.cfg.Store.IsOurTx(spendHash)
3✔
1348
        if err != nil {
3✔
1349
                log.Errorf("cannot determine if tx %v is ours: %v",
×
1350
                        spendHash, err)
×
1351
                return
×
1352
        }
×
1353

1354
        // If this isn't our transaction, it means someone else swept outputs
1355
        // that we were attempting to sweep. This can happen for anchor outputs
1356
        // as well as justice transactions. In this case, we'll notify the
1357
        // wallet to remove any spends that descent from this output.
1358
        if !isOurTx {
6✔
1359
                // Construct a map of the inputs this transaction spends.
3✔
1360
                spendingTx := spend.SpendingTx
3✔
1361
                inputsSpent := make(
3✔
1362
                        map[wire.OutPoint]struct{}, len(spendingTx.TxIn),
3✔
1363
                )
3✔
1364
                for _, txIn := range spendingTx.TxIn {
6✔
1365
                        inputsSpent[txIn.PreviousOutPoint] = struct{}{}
3✔
1366
                }
3✔
1367

1368
                log.Debugf("Attempting to remove descendant txns invalidated "+
3✔
1369
                        "by (txid=%v): %v", spendingTx.TxHash(),
3✔
1370
                        spew.Sdump(spendingTx))
3✔
1371

3✔
1372
                err := s.removeConflictSweepDescendants(inputsSpent)
3✔
1373
                if err != nil {
3✔
1374
                        log.Warnf("unable to remove descendant transactions "+
×
1375
                                "due to tx %v: ", spendHash)
×
1376
                }
×
1377

1378
                log.Debugf("Detected third party spend related to in flight "+
3✔
1379
                        "inputs (is_ours=%v): %v", isOurTx,
3✔
1380
                        lnutils.SpewLogClosure(spend.SpendingTx))
3✔
1381
        }
1382

1383
        // We now use the spending tx to update the state of the inputs.
1384
        s.markInputsSwept(spend.SpendingTx, isOurTx)
3✔
1385
}
1386

1387
// markInputsSwept marks all inputs swept by the spending transaction as swept.
1388
// It will also notify all the subscribers of this input.
1389
func (s *UtxoSweeper) markInputsSwept(tx *wire.MsgTx, isOurTx bool) {
4✔
1390
        for _, txIn := range tx.TxIn {
11✔
1391
                outpoint := txIn.PreviousOutPoint
7✔
1392

7✔
1393
                // Check if this input is known to us. It could probably be
7✔
1394
                // unknown if we canceled the registration, deleted from inputs
7✔
1395
                // map but the ntfn was in-flight already. Or this could be not
7✔
1396
                // one of our inputs.
7✔
1397
                input, ok := s.inputs[outpoint]
7✔
1398
                if !ok {
11✔
1399
                        // It's very likely that a spending tx contains inputs
4✔
1400
                        // that we don't know.
4✔
1401
                        log.Tracef("Skipped marking input as swept: %v not "+
4✔
1402
                                "found in pending inputs", outpoint)
4✔
1403

4✔
1404
                        continue
4✔
1405
                }
1406

1407
                // This input may already been marked as swept by a previous
1408
                // spend notification, which is likely to happen as one sweep
1409
                // transaction usually sweeps multiple inputs.
1410
                if input.terminated() {
7✔
1411
                        log.Debugf("Skipped marking input as swept: %v "+
1✔
1412
                                "state=%v", outpoint, input.state)
1✔
1413

1✔
1414
                        continue
1✔
1415
                }
1416

1417
                input.state = Swept
5✔
1418

5✔
1419
                // Return either a nil or a remote spend result.
5✔
1420
                var err error
5✔
1421
                if !isOurTx {
8✔
1422
                        log.Warnf("Input=%v was spent by remote or third "+
3✔
1423
                                "party in tx=%v", outpoint, tx.TxHash())
3✔
1424
                        err = ErrRemoteSpend
3✔
1425
                }
3✔
1426

1427
                // Signal result channels.
1428
                s.signalResult(input, Result{
5✔
1429
                        Tx:  tx,
5✔
1430
                        Err: err,
5✔
1431
                })
5✔
1432

5✔
1433
                // Remove all other inputs in this exclusive group.
5✔
1434
                if input.params.ExclusiveGroup != nil {
8✔
1435
                        s.removeExclusiveGroup(*input.params.ExclusiveGroup)
3✔
1436
                }
3✔
1437
        }
1438
}
1439

1440
// markInputFailed marks the given input as failed and won't be retried. It
1441
// will also notify all the subscribers of this input.
1442
func (s *UtxoSweeper) markInputFailed(pi *SweeperInput, err error) {
1✔
1443
        log.Errorf("Failed to sweep input: %v, error: %v", pi, err)
1✔
1444

1✔
1445
        pi.state = Failed
1✔
1446

1✔
1447
        // Remove all other inputs in this exclusive group.
1✔
1448
        if pi.params.ExclusiveGroup != nil {
1✔
1449
                s.removeExclusiveGroup(*pi.params.ExclusiveGroup)
×
1450
        }
×
1451

1452
        s.signalResult(pi, Result{Err: err})
1✔
1453
}
1454

1455
// updateSweeperInputs updates the sweeper's internal state and returns a map
1456
// of inputs to be swept. It will remove the inputs that are in final states,
1457
// and returns a map of inputs that have either state Init or PublishFailed.
1458
func (s *UtxoSweeper) updateSweeperInputs() InputsMap {
4✔
1459
        // Create a map of inputs to be swept.
4✔
1460
        inputs := make(InputsMap)
4✔
1461

4✔
1462
        // Iterate the pending inputs and update the sweeper's state.
4✔
1463
        //
4✔
1464
        // TODO(yy): sweeper is made to communicate via go channels, so no
4✔
1465
        // locks are needed to access the map. However, it'd be safer if we
4✔
1466
        // turn this inputs map into a SyncMap in case we wanna add concurrent
4✔
1467
        // access to the map in the future.
4✔
1468
        for op, input := range s.inputs {
16✔
1469
                // If the input has reached a final state, that it's either
12✔
1470
                // been swept, or failed, or excluded, we will remove it from
12✔
1471
                // our sweeper.
12✔
1472
                if input.terminated() {
18✔
1473
                        log.Debugf("Removing input(State=%v) %v from sweeper",
6✔
1474
                                input.state, op)
6✔
1475

6✔
1476
                        delete(s.inputs, op)
6✔
1477

6✔
1478
                        continue
6✔
1479
                }
1480

1481
                // If this input has been included in a sweep tx that's not
1482
                // published yet, we'd skip this input and wait for the sweep
1483
                // tx to be published.
1484
                if input.state == PendingPublish {
13✔
1485
                        continue
4✔
1486
                }
1487

1488
                // If this input has already been published, we will need to
1489
                // check the RBF condition before attempting another sweeping.
1490
                if input.state == Published {
12✔
1491
                        continue
4✔
1492
                }
1493

1494
                // If the input has a locktime that's not yet reached, we will
1495
                // skip this input and wait for the locktime to be reached.
1496
                locktime, _ := input.RequiredLockTime()
7✔
1497
                if uint32(s.currentHeight) < locktime {
11✔
1498
                        log.Warnf("Skipping input %v due to locktime=%v not "+
4✔
1499
                                "reached, current height is %v", op, locktime,
4✔
1500
                                s.currentHeight)
4✔
1501

4✔
1502
                        continue
4✔
1503
                }
1504

1505
                // If the input has a CSV that's not yet reached, we will skip
1506
                // this input and wait for the expiry.
1507
                locktime = input.BlocksToMaturity() + input.HeightHint()
6✔
1508
                if s.currentHeight < int32(locktime)-1 {
10✔
1509
                        log.Infof("Skipping input %v due to CSV expiry=%v not "+
4✔
1510
                                "reached, current height is %v", op, locktime,
4✔
1511
                                s.currentHeight)
4✔
1512

4✔
1513
                        continue
4✔
1514
                }
1515

1516
                // If this input is new or has been failed to be published,
1517
                // we'd retry it. The assumption here is that when an error is
1518
                // returned from `PublishTransaction`, it means the tx has
1519
                // failed to meet the policy, hence it's not in the mempool.
1520
                inputs[op] = input
5✔
1521
        }
1522

1523
        return inputs
4✔
1524
}
1525

1526
// sweepPendingInputs is called when the ticker fires. It will create clusters
1527
// and attempt to create and publish the sweeping transactions.
1528
func (s *UtxoSweeper) sweepPendingInputs(inputs InputsMap) {
4✔
1529
        // Cluster all of our inputs based on the specific Aggregator.
4✔
1530
        sets := s.cfg.Aggregator.ClusterInputs(inputs)
4✔
1531

4✔
1532
        // sweepWithLock is a helper closure that executes the sweep within a
4✔
1533
        // coin select lock to prevent the coins being selected for other
4✔
1534
        // transactions like funding of a channel.
4✔
1535
        sweepWithLock := func(set InputSet) error {
8✔
1536
                return s.cfg.Wallet.WithCoinSelectLock(func() error {
8✔
1537
                        // Try to add inputs from our wallet.
4✔
1538
                        err := set.AddWalletInputs(s.cfg.Wallet)
4✔
1539
                        if err != nil {
7✔
1540
                                return err
3✔
1541
                        }
3✔
1542

1543
                        // Create sweeping transaction for each set.
1544
                        err = s.sweep(set)
4✔
1545
                        if err != nil {
8✔
1546
                                return err
4✔
1547
                        }
4✔
1548

1549
                        return nil
3✔
1550
                })
1551
        }
1552

1553
        for _, set := range sets {
9✔
1554
                var err error
5✔
1555
                if set.NeedWalletInput() {
9✔
1556
                        // Sweep the set of inputs that need the wallet inputs.
4✔
1557
                        err = sweepWithLock(set)
4✔
1558
                } else {
8✔
1559
                        // Sweep the set of inputs that don't need the wallet
4✔
1560
                        // inputs.
4✔
1561
                        err = s.sweep(set)
4✔
1562
                }
4✔
1563

1564
                if err != nil {
10✔
1565
                        log.Errorf("Failed to sweep %v: %v", set, err)
5✔
1566
                }
5✔
1567
        }
1568
}
1569

1570
// monitorFeeBumpResult subscribes to the passed result chan to listen for
1571
// future updates about the sweeping tx.
1572
//
1573
// NOTE: must run as a goroutine.
1574
func (s *UtxoSweeper) monitorFeeBumpResult(resultChan <-chan *BumpResult) {
7✔
1575
        defer s.wg.Done()
7✔
1576

7✔
1577
        for {
15✔
1578
                select {
8✔
1579
                case r := <-resultChan:
6✔
1580
                        // Validate the result is valid.
6✔
1581
                        if err := r.Validate(); err != nil {
6✔
1582
                                log.Errorf("Received invalid result: %v", err)
×
1583
                                continue
×
1584
                        }
1585

1586
                        // Send the result back to the main event loop.
1587
                        select {
6✔
1588
                        case s.bumpResultChan <- r:
6✔
1589
                        case <-s.quit:
×
1590
                                log.Debug("Sweeper shutting down, skip " +
×
1591
                                        "sending bump result")
×
1592

×
1593
                                return
×
1594
                        }
1595

1596
                        // The sweeping tx has been confirmed, we can exit the
1597
                        // monitor now.
1598
                        //
1599
                        // TODO(yy): can instead remove the spend subscription
1600
                        // in sweeper and rely solely on this event to mark
1601
                        // inputs as Swept?
1602
                        if r.Event == TxConfirmed || r.Event == TxFailed {
11✔
1603
                                log.Debugf("Received %v for sweep tx %v, exit "+
5✔
1604
                                        "fee bump monitor", r.Event,
5✔
1605
                                        r.Tx.TxHash())
5✔
1606

5✔
1607
                                // Cancel the rebroadcasting of the failed tx.
5✔
1608
                                s.cfg.Wallet.CancelRebroadcast(r.Tx.TxHash())
5✔
1609

5✔
1610
                                return
5✔
1611
                        }
5✔
1612

1613
                case <-s.quit:
5✔
1614
                        log.Debugf("Sweeper shutting down, exit fee " +
5✔
1615
                                "bump handler")
5✔
1616

5✔
1617
                        return
5✔
1618
                }
1619
        }
1620
}
1621

1622
// handleBumpEventTxFailed handles the case where the tx has been failed to
1623
// publish.
1624
func (s *UtxoSweeper) handleBumpEventTxFailed(r *BumpResult) error {
4✔
1625
        tx, err := r.Tx, r.Err
4✔
1626

4✔
1627
        log.Errorf("Fee bump attempt failed for tx=%v: %v", tx.TxHash(), err)
4✔
1628

4✔
1629
        outpoints := make([]wire.OutPoint, 0, len(tx.TxIn))
4✔
1630
        for _, inp := range tx.TxIn {
10✔
1631
                outpoints = append(outpoints, inp.PreviousOutPoint)
6✔
1632
        }
6✔
1633

1634
        // TODO(yy): should we also remove the failed tx from db?
1635
        s.markInputsPublishFailed(outpoints)
4✔
1636

4✔
1637
        return err
4✔
1638
}
1639

1640
// handleBumpEventTxReplaced handles the case where the sweeping tx has been
1641
// replaced by a new one.
1642
func (s *UtxoSweeper) handleBumpEventTxReplaced(r *BumpResult) error {
6✔
1643
        oldTx := r.ReplacedTx
6✔
1644
        newTx := r.Tx
6✔
1645

6✔
1646
        // Prepare a new record to replace the old one.
6✔
1647
        tr := &TxRecord{
6✔
1648
                Txid:    newTx.TxHash(),
6✔
1649
                FeeRate: uint64(r.FeeRate),
6✔
1650
                Fee:     uint64(r.Fee),
6✔
1651
        }
6✔
1652

6✔
1653
        // Get the old record for logging purpose.
6✔
1654
        oldTxid := oldTx.TxHash()
6✔
1655
        record, err := s.cfg.Store.GetTx(oldTxid)
6✔
1656
        if err != nil {
7✔
1657
                log.Errorf("Fetch tx record for %v: %v", oldTxid, err)
1✔
1658
                return err
1✔
1659
        }
1✔
1660

1661
        // Cancel the rebroadcasting of the replaced tx.
1662
        s.cfg.Wallet.CancelRebroadcast(oldTxid)
5✔
1663

5✔
1664
        log.Infof("RBFed tx=%v(fee=%v sats, feerate=%v sats/kw) with new "+
5✔
1665
                "tx=%v(fee=%v, "+"feerate=%v)", record.Txid, record.Fee,
5✔
1666
                record.FeeRate, tr.Txid, tr.Fee, tr.FeeRate)
5✔
1667

5✔
1668
        // The old sweeping tx has been replaced by a new one, we will update
5✔
1669
        // the tx record in the sweeper db.
5✔
1670
        //
5✔
1671
        // TODO(yy): we may also need to update the inputs in this tx to a new
5✔
1672
        // state. Suppose a replacing tx only spends a subset of the inputs
5✔
1673
        // here, we'd end up with the rest being marked as `Published` and
5✔
1674
        // won't be aggregated in the next sweep. Atm it's fine as we always
5✔
1675
        // RBF the same input set.
5✔
1676
        if err := s.cfg.Store.DeleteTx(oldTxid); err != nil {
6✔
1677
                log.Errorf("Delete tx record for %v: %v", oldTxid, err)
1✔
1678
                return err
1✔
1679
        }
1✔
1680

1681
        // Mark the inputs as published using the replacing tx.
1682
        return s.markInputsPublished(tr, r.Tx.TxIn)
4✔
1683
}
1684

1685
// handleBumpEventTxPublished handles the case where the sweeping tx has been
1686
// successfully published.
1687
func (s *UtxoSweeper) handleBumpEventTxPublished(r *BumpResult) error {
4✔
1688
        tx := r.Tx
4✔
1689
        tr := &TxRecord{
4✔
1690
                Txid:    tx.TxHash(),
4✔
1691
                FeeRate: uint64(r.FeeRate),
4✔
1692
                Fee:     uint64(r.Fee),
4✔
1693
        }
4✔
1694

4✔
1695
        // Inputs have been successfully published so we update their
4✔
1696
        // states.
4✔
1697
        err := s.markInputsPublished(tr, tx.TxIn)
4✔
1698
        if err != nil {
4✔
1699
                return err
×
1700
        }
×
1701

1702
        log.Debugf("Published sweep tx %v, num_inputs=%v, height=%v",
4✔
1703
                tx.TxHash(), len(tx.TxIn), s.currentHeight)
4✔
1704

4✔
1705
        // If there's no error, remove the output script. Otherwise
4✔
1706
        // keep it so that it can be reused for the next transaction
4✔
1707
        // and causes no address inflation.
4✔
1708
        s.currentOutputScript = nil
4✔
1709

4✔
1710
        return nil
4✔
1711
}
1712

1713
// handleBumpEvent handles the result sent from the bumper based on its event
1714
// type.
1715
//
1716
// NOTE: TxConfirmed event is not handled, since we already subscribe to the
1717
// input's spending event, we don't need to do anything here.
1718
func (s *UtxoSweeper) handleBumpEvent(r *BumpResult) error {
4✔
1719
        log.Debugf("Received bump event [%v] for tx %v", r.Event, r.Tx.TxHash())
4✔
1720

4✔
1721
        switch r.Event {
4✔
1722
        // The tx has been published, we update the inputs' state and create a
1723
        // record to be stored in the sweeper db.
1724
        case TxPublished:
3✔
1725
                return s.handleBumpEventTxPublished(r)
3✔
1726

1727
        // The tx has failed, we update the inputs' state.
1728
        case TxFailed:
4✔
1729
                return s.handleBumpEventTxFailed(r)
4✔
1730

1731
        // The tx has been replaced, we will remove the old tx and replace it
1732
        // with the new one.
1733
        case TxReplaced:
3✔
1734
                return s.handleBumpEventTxReplaced(r)
3✔
1735
        }
1736

1737
        return nil
3✔
1738
}
1739

1740
// IsSweeperOutpoint determines whether the outpoint was created by the sweeper.
1741
//
1742
// NOTE: It is enough to check the txid because the sweeper will create
1743
// outpoints which solely belong to the internal LND wallet.
1744
func (s *UtxoSweeper) IsSweeperOutpoint(op wire.OutPoint) bool {
3✔
1745
        found, err := s.cfg.Store.IsOurTx(op.Hash)
3✔
1746
        // In case there is an error fetching the transaction details from the
3✔
1747
        // sweeper store we assume the outpoint is still used by the sweeper
3✔
1748
        // (worst case scenario).
3✔
1749
        //
3✔
1750
        // TODO(ziggie): Ensure that confirmed outpoints are deleted from the
3✔
1751
        // bucket.
3✔
1752
        if err != nil && !errors.Is(err, errNoTxHashesBucket) {
3✔
1753
                log.Errorf("failed to fetch info for outpoint(%v:%d) "+
×
1754
                        "with: %v, we assume it is still in use by the sweeper",
×
1755
                        op.Hash, op.Index, err)
×
1756

×
1757
                return true
×
1758
        }
×
1759

1760
        return found
3✔
1761
}
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