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

lightningnetwork / lnd / 11219354629

07 Oct 2024 03:56PM UTC coverage: 58.585% (-0.2%) from 58.814%
11219354629

Pull #9147

github

ziggie1984
fixup! sqlc: migration up script for payments.
Pull Request #9147: [Part 1|3] Introduce SQL Payment schema into LND

130227 of 222287 relevant lines covered (58.59%)

29106.19 hits per line

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

89.34
/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 {
2✔
72
        deadline := "none"
2✔
73
        p.DeadlineHeight.WhenSome(func(d int32) {
4✔
74
                deadline = fmt.Sprintf("%d", d)
2✔
75
        })
2✔
76

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

82
        return fmt.Sprintf("startingFeeRate=%v, immediate=%v, "+
2✔
83
                "exclusive_group=%v, budget=%v, deadline=%v", p.StartingFeeRate,
2✔
84
                p.Immediate, exclusiveGroup, p.Budget, deadline)
2✔
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 {
2✔
128
        switch s {
2✔
129
        case Init:
2✔
130
                return "Init"
2✔
131

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

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

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

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

144
        case Excluded:
2✔
145
                return "Excluded"
2✔
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 {
28✔
207
        return fmt.Sprintf("%v (%v)", p.Input.OutPoint(), p.Input.WitnessType())
28✔
208
}
28✔
209

210
// terminated returns a boolean indicating whether the input has reached a
211
// final state.
212
func (p *SweeperInput) terminated() bool {
17✔
213
        switch p.state {
17✔
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:
7✔
218
                return true
7✔
219

220
        default:
12✔
221
                return false
12✔
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 {
16✔
390
        return &UtxoSweeper{
16✔
391
                cfg:               cfg,
16✔
392
                newInputs:         make(chan *sweepInputMessage),
16✔
393
                spendChan:         make(chan *chainntnfs.SpendDetail),
16✔
394
                updateReqs:        make(chan *updateReq),
16✔
395
                pendingSweepsReqs: make(chan *pendingSweepsReq),
16✔
396
                quit:              make(chan struct{}),
16✔
397
                inputs:            make(InputsMap),
16✔
398
                bumpResultChan:    make(chan *BumpResult, 100),
16✔
399
        }
16✔
400
}
16✔
401

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

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

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

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

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

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

2✔
430
                // The collector exited and won't longer handle incoming
2✔
431
                // requests. This can happen on shutdown, when the block
2✔
432
                // notifier shuts down before the sweeper and its clients. In
2✔
433
                // order to not deadlock the clients waiting for their requests
2✔
434
                // being handled, we handle them here and immediately return an
2✔
435
                // error. When the sweeper finally is shut down we can exit as
2✔
436
                // the clients will be notified.
2✔
437
                for {
4✔
438
                        select {
2✔
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:
2✔
453
                                return
2✔
454
                        }
455
                }
456
        }()
457

458
        return nil
2✔
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 {
2✔
470
        if !atomic.CompareAndSwapUint32(&s.stopped, 0, 1) {
2✔
471
                return nil
×
472
        }
×
473

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

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

2✔
480
        return nil
2✔
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) {
2✔
497

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

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

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

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

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

525
        return sweeperInput.resultChan, nil
2✔
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 {
2✔
544

2✔
545
        // Obtain all the past sweeps that we've done so far. We'll need these
2✔
546
        // to ensure that if the spendingTx spends any of the same inputs, then
2✔
547
        // we remove any transaction that may be spending those inputs from the
2✔
548
        // wallet.
2✔
549
        //
2✔
550
        // TODO(roasbeef): can be last sweep here if we remove anything confirmed
2✔
551
        // from the store?
2✔
552
        pastSweepHashes, err := s.cfg.Store.ListSweeps()
2✔
553
        if err != nil {
2✔
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 {
4✔
565
                sweepTx, err := s.cfg.Wallet.FetchTx(sweepHash)
2✔
566
                if err != nil {
2✔
567
                        return err
×
568
                }
×
569

570
                // Transaction wasn't found in the wallet, may have already
571
                // been replaced/removed.
572
                if sweepTx == nil {
4✔
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
2✔
582
                for _, txIn := range sweepTx.TxIn {
4✔
583
                        if _, ok := outpoints[txIn.PreviousOutPoint]; ok {
4✔
584
                                isConflicting = true
2✔
585
                                break
2✔
586
                        }
587
                }
588

589
                if !isConflicting {
4✔
590
                        continue
2✔
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",
2✔
597
                        sweepTx.TxHash(), spew.Sdump(sweepTx))
2✔
598

2✔
599
                err = s.cfg.Wallet.RemoveDescendants(sweepTx)
2✔
600
                if err != nil {
2✔
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)
2✔
607
        }
608

609
        return nil
2✔
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) {
2✔
615
        // We registered for the block epochs with a nil request. The notifier
2✔
616
        // should send us the current best block immediately. So we need to wait
2✔
617
        // for it here because we need to know the current best height.
2✔
618
        select {
2✔
619
        case bestBlock := <-blockEpochs:
2✔
620
                s.currentHeight = bestBlock.Height
2✔
621

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

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

2✔
633
                select {
2✔
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:
2✔
638
                        err := s.handleNewInput(input)
2✔
639
                        if err != nil {
2✔
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
                        //
649
                        // TODO(ziggie): Make sure when `immediate` is selected
650
                        // as a parameter that we only trigger the sweeping of
651
                        // this specific input rather than triggering the sweeps
652
                        // of all current pending inputs registered with the
653
                        // sweeper.
654
                        if input.params.Immediate {
4✔
655
                                inputs := s.updateSweeperInputs()
2✔
656
                                s.sweepPendingInputs(inputs)
2✔
657
                        }
2✔
658

659
                // A spend of one of our inputs is detected. Signal sweep
660
                // results to the caller(s).
661
                case spend := <-s.spendChan:
2✔
662
                        s.handleInputSpent(spend)
2✔
663

664
                // A new external request has been received to retrieve all of
665
                // the inputs we're currently attempting to sweep.
666
                case req := <-s.pendingSweepsReqs:
2✔
667
                        s.handlePendingSweepsReq(req)
2✔
668

669
                // A new external request has been received to bump the fee rate
670
                // of a given input.
671
                case req := <-s.updateReqs:
2✔
672
                        resultChan, err := s.handleUpdateReq(req)
2✔
673
                        req.responseChan <- &updateResp{
2✔
674
                                resultChan: resultChan,
2✔
675
                                err:        err,
2✔
676
                        }
2✔
677

2✔
678
                        // Perform an sweep immediately if asked.
2✔
679
                        if req.params.Immediate {
4✔
680
                                inputs := s.updateSweeperInputs()
2✔
681
                                s.sweepPendingInputs(inputs)
2✔
682
                        }
2✔
683

684
                case result := <-s.bumpResultChan:
2✔
685
                        // Handle the bump event.
2✔
686
                        err := s.handleBumpEvent(result)
2✔
687
                        if err != nil {
4✔
688
                                log.Errorf("Failed to handle bump event: %v",
2✔
689
                                        err)
2✔
690
                        }
2✔
691

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

×
701
                                return
×
702
                        }
×
703

704
                        // Update the sweeper to the best height.
705
                        s.currentHeight = epoch.Height
2✔
706

2✔
707
                        // Update the inputs with the latest height.
2✔
708
                        inputs := s.updateSweeperInputs()
2✔
709

2✔
710
                        log.Debugf("Received new block: height=%v, attempt "+
2✔
711
                                "sweeping %d inputs", epoch.Height, len(inputs))
2✔
712

2✔
713
                        // Attempt to sweep any pending inputs.
2✔
714
                        s.sweepPendingInputs(inputs)
2✔
715

716
                case <-s.quit:
2✔
717
                        return
2✔
718
                }
719
        }
720
}
721

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

2✔
731
                // Skip inputs that aren't exclusive.
2✔
732
                if input.params.ExclusiveGroup == nil {
4✔
733
                        continue
2✔
734
                }
735

736
                // Skip inputs from other exclusive groups.
737
                if *input.params.ExclusiveGroup != group {
2✔
738
                        continue
×
739
                }
740

741
                // Skip inputs that are already terminated.
742
                if input.terminated() {
4✔
743
                        log.Tracef("Skipped sending error result for "+
2✔
744
                                "input %v, state=%v", outpoint, input.state)
2✔
745

2✔
746
                        continue
2✔
747
                }
748

749
                // Signal result channels.
750
                s.signalResult(input, Result{
2✔
751
                        Err: ErrExclusiveGroupSpend,
2✔
752
                })
2✔
753

2✔
754
                // Update the input's state as it can no longer be swept.
2✔
755
                input.state = Excluded
2✔
756

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

770
// signalResult notifies the listeners of the final result of the input sweep.
771
// It also cancels any pending spend notification.
772
func (s *UtxoSweeper) signalResult(pi *SweeperInput, result Result) {
5✔
773
        op := pi.OutPoint()
5✔
774
        listeners := pi.listeners
5✔
775

5✔
776
        if result.Err == nil {
9✔
777
                log.Tracef("Dispatching sweep success for %v to %v listeners",
4✔
778
                        op, len(listeners),
4✔
779
                )
4✔
780
        } else {
7✔
781
                log.Tracef("Dispatching sweep error for %v to %v listeners: %v",
3✔
782
                        op, len(listeners), result.Err,
3✔
783
                )
3✔
784
        }
3✔
785

786
        // Signal all listeners. Channel is buffered. Because we only send once
787
        // on every channel, it should never block.
788
        for _, resultChan := range listeners {
7✔
789
                resultChan <- result
2✔
790
        }
2✔
791

792
        // Cancel spend notification with chain notifier. This is not necessary
793
        // in case of a success, except for that a reorg could still happen.
794
        if pi.ntfnRegCancel != nil {
7✔
795
                log.Debugf("Canceling spend ntfn for %v", op)
2✔
796

2✔
797
                pi.ntfnRegCancel()
2✔
798
        }
2✔
799
}
800

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

813
        // Create a fee bump request and ask the publisher to broadcast it. The
4✔
814
        // publisher will then take over and start monitoring the tx for
4✔
815
        // potential fee bump.
4✔
816
        req := &BumpRequest{
4✔
817
                Inputs:          set.Inputs(),
×
818
                Budget:          set.Budget(),
×
819
                DeadlineHeight:  set.DeadlineHeight(),
820
                DeliveryAddress: s.currentOutputScript,
821
                MaxFeeRate:      s.cfg.MaxFeeRate.FeePerKWeight(),
822
                StartingFeeRate: set.StartingFeeRate(),
823
                // TODO(yy): pass the strategy here.
4✔
824
        }
4✔
825

4✔
826
        // Reschedule the inputs that we just tried to sweep. This is done in
4✔
827
        // case the following publish fails, we'd like to update the inputs'
4✔
828
        // publish attempts and rescue them in the next sweep.
4✔
829
        s.markInputsPendingPublish(set)
4✔
830

4✔
831
        // Broadcast will return a read-only chan that we will listen to for
4✔
832
        // this publish result and future RBF attempt.
4✔
833
        resp, err := s.cfg.Publisher.Broadcast(req)
4✔
834
        if err != nil {
4✔
835
                outpoints := make([]wire.OutPoint, len(set.Inputs()))
4✔
836
                for i, inp := range set.Inputs() {
4✔
837
                        outpoints[i] = inp.OutPoint()
4✔
838
                }
4✔
839

4✔
840
                log.Errorf("Initial broadcast failed: %v, inputs=\n%v", err,
4✔
841
                        inputTypeSummary(set.Inputs()))
8✔
842

4✔
843
                // TODO(yy): find out which input is causing the failure.
6✔
844
                s.markInputsPublishFailed(outpoints)
2✔
845

2✔
846
                return err
847
        }
4✔
848

4✔
849
        // Successfully sent the broadcast attempt, we now handle the result by
4✔
850
        // subscribing to the result chan and listen for future updates about
4✔
851
        // this tx.
4✔
852
        s.wg.Add(1)
4✔
853
        go s.monitorFeeBumpResult(resp)
4✔
854

855
        return nil
856
}
857

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

9✔
872
                        continue
3✔
873
                }
3✔
874

3✔
875
                // If this input has already terminated, there's clearly
3✔
876
                // something wrong as it would have been removed. In this case
3✔
877
                // we log an error and skip marking this input as pending
3✔
878
                // publish.
3✔
879
                if pi.terminated() {
3✔
880
                        log.Errorf("Expect input %v to not have terminated "+
881
                                "state, instead it has %v",
882
                                input.OutPoint, pi.state)
883

884
                        continue
885
                }
886

6✔
887
                // Update the input's state.
1✔
888
                pi.state = PendingPublish
1✔
889

1✔
890
                // Record another publish attempt.
1✔
891
                pi.publishAttempts++
1✔
892
        }
893
}
894

895
// markInputsPublished updates the sweeping tx in db and marks the list of
4✔
896
// inputs as published.
4✔
897
func (s *UtxoSweeper) markInputsPublished(tr *TxRecord,
4✔
898
        inputs []*wire.TxIn) error {
4✔
899

900
        // Mark this tx in db once successfully published.
901
        //
902
        // NOTE: this will behave as an overwrite, which is fine as the record
903
        // is small.
904
        tr.Published = true
905
        err := s.cfg.Store.StoreTx(tr)
6✔
906
        if err != nil {
6✔
907
                return fmt.Errorf("store tx: %w", err)
6✔
908
        }
6✔
909

6✔
910
        // Reschedule sweep.
6✔
911
        for _, input := range inputs {
6✔
912
                pi, ok := s.inputs[input.PreviousOutPoint]
6✔
913
                if !ok {
7✔
914
                        // It could be that this input is an additional wallet
1✔
915
                        // input that was attached. In that case there also
1✔
916
                        // isn't a pending input to update.
917
                        log.Tracef("Skipped marking input as published: %v "+
918
                                "not found in pending inputs",
12✔
919
                                input.PreviousOutPoint)
7✔
920

10✔
921
                        continue
3✔
922
                }
3✔
923

3✔
924
                // Valdiate that the input is in an expected state.
3✔
925
                if pi.state != PendingPublish {
3✔
926
                        // We may get a Published if this is a replacement tx.
3✔
927
                        log.Debugf("Expect input %v to have %v, instead it "+
3✔
928
                                "has %v", input.PreviousOutPoint,
3✔
929
                                PendingPublish, pi.state)
930

931
                        continue
932
                }
9✔
933

3✔
934
                // Update the input's state.
3✔
935
                pi.state = Published
3✔
936

3✔
937
                // Update the input's latest fee rate.
3✔
938
                pi.lastFeeRate = chainfee.SatPerKWeight(tr.FeeRate)
3✔
939
        }
940

941
        return nil
942
}
5✔
943

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

13✔
956
                        continue
17✔
957
                }
4✔
958

4✔
959
                // Valdiate that the input is in an expected state.
4✔
960
                if pi.state != PendingPublish && pi.state != Published {
4✔
961
                        log.Debugf("Expect input %v to have %v, instead it "+
4✔
962
                                "has %v", op, PendingPublish, pi.state)
4✔
963

4✔
964
                        continue
965
                }
966

967
                log.Warnf("Failed to publish input %v", op)
16✔
968

5✔
969
                // Update the input's state.
5✔
970
                pi.state = PublishFailed
5✔
971
        }
5✔
972
}
973

974
// monitorSpend registers a spend notification with the chain notifier. It
6✔
975
// returns a cancel function that can be used to cancel the registration.
6✔
976
func (s *UtxoSweeper) monitorSpend(outpoint wire.OutPoint,
6✔
977
        script []byte, heightHint uint32) (func(), error) {
6✔
978

979
        log.Tracef("Wait for spend of %v at heightHint=%v",
980
                outpoint, heightHint)
981

982
        spendEvent, err := s.cfg.Notifier.RegisterSpendNtfn(
983
                &outpoint, script, heightHint,
984
        )
2✔
985
        if err != nil {
2✔
986
                return nil, fmt.Errorf("register spend ntfn: %w", err)
2✔
987
        }
2✔
988

2✔
989
        s.wg.Add(1)
2✔
990
        go func() {
2✔
991
                defer s.wg.Done()
2✔
992

2✔
993
                select {
×
994
                case spend, ok := <-spendEvent.Spend:
×
995
                        if !ok {
996
                                log.Debugf("Spend ntfn for %v canceled",
2✔
997
                                        outpoint)
4✔
998
                                return
2✔
999
                        }
2✔
1000

2✔
1001
                        log.Debugf("Delivering spend ntfn for %v", outpoint)
2✔
1002

4✔
1003
                        select {
2✔
1004
                        case s.spendChan <- spend:
2✔
1005
                                log.Debugf("Delivered spend ntfn for %v",
2✔
1006
                                        outpoint)
2✔
1007

1008
                        case <-s.quit:
2✔
1009
                        }
2✔
1010
                case <-s.quit:
2✔
1011
                }
2✔
1012
        }()
2✔
1013

2✔
1014
        return spendEvent.Cancel, nil
1015
}
×
1016

1017
// PendingInputs returns the set of inputs that the UtxoSweeper is currently
2✔
1018
// attempting to sweep.
1019
func (s *UtxoSweeper) PendingInputs() (
1020
        map[wire.OutPoint]*PendingInputResponse, error) {
1021

2✔
1022
        respChan := make(chan map[wire.OutPoint]*PendingInputResponse, 1)
1023
        errChan := make(chan error, 1)
1024
        select {
1025
        case s.pendingSweepsReqs <- &pendingSweepsReq{
1026
                respChan: respChan,
1027
                errChan:  errChan,
2✔
1028
        }:
2✔
1029
        case <-s.quit:
2✔
1030
                return nil, ErrSweeperShuttingDown
2✔
1031
        }
2✔
1032

1033
        select {
1034
        case pendingSweeps := <-respChan:
1035
                return pendingSweeps, nil
2✔
1036
        case err := <-errChan:
×
1037
                return nil, err
×
1038
        case <-s.quit:
1039
                return nil, ErrSweeperShuttingDown
1040
        }
2✔
1041
}
2✔
1042

2✔
1043
// handlePendingSweepsReq handles a request to retrieve all pending inputs the
×
1044
// UtxoSweeper is attempting to sweep.
×
1045
func (s *UtxoSweeper) handlePendingSweepsReq(
×
1046
        req *pendingSweepsReq) map[wire.OutPoint]*PendingInputResponse {
×
1047

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

2✔
1066
        select {
2✔
1067
        case req.respChan <- resps:
2✔
1068
        case <-s.quit:
2✔
1069
                log.Debug("Skipped sending pending sweep response due to " +
2✔
1070
                        "UtxoSweeper shutting down")
2✔
1071
        }
2✔
1072

1073
        return resps
2✔
1074
}
2✔
1075

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

1088
        responseChan := make(chan *updateResp, 1)
1089
        select {
1090
        case s.updateReqs <- &updateReq{
1091
                input:        input,
1092
                params:       params,
1093
                responseChan: responseChan,
2✔
1094
        }:
2✔
1095
        case <-s.quit:
2✔
1096
                return nil, ErrSweeperShuttingDown
2✔
1097
        }
1098

1099
        select {
1100
        case response := <-responseChan:
1101
                return response.resultChan, response.err
2✔
1102
        case <-s.quit:
×
1103
                return nil, ErrSweeperShuttingDown
×
1104
        }
1105
}
1106

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

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

2✔
1131
        // Create the updated parameters struct. Leave the exclusive group
2✔
1132
        // unchanged.
2✔
1133
        newParams := Params{
2✔
1134
                StartingFeeRate: req.params.StartingFeeRate,
2✔
1135
                Immediate:       req.params.Immediate,
×
1136
                Budget:          req.params.Budget,
×
1137
                DeadlineHeight:  req.params.DeadlineHeight,
1138
                ExclusiveGroup:  sweeperInput.params.ExclusiveGroup,
1139
        }
1140

2✔
1141
        log.Debugf("Updating parameters for %v(state=%v) from (%v) to (%v)",
2✔
1142
                req.input, sweeperInput.state, sweeperInput.params, newParams)
2✔
1143

2✔
1144
        sweeperInput.params = newParams
2✔
1145

2✔
1146
        // We need to reset the state so this input will be attempted again by
2✔
1147
        // our sweeper.
2✔
1148
        //
2✔
1149
        // TODO(yy): a dedicated state?
2✔
1150
        sweeperInput.state = Init
2✔
1151

2✔
1152
        // If the new input specifies a deadline, update the deadline height.
2✔
1153
        sweeperInput.DeadlineHeight = req.params.DeadlineHeight.UnwrapOr(
2✔
1154
                sweeperInput.DeadlineHeight,
2✔
1155
        )
2✔
1156

2✔
1157
        resultChan := make(chan Result, 1)
2✔
1158
        sweeperInput.listeners = append(sweeperInput.listeners, resultChan)
2✔
1159

2✔
1160
        return resultChan, nil
2✔
1161
}
2✔
1162

2✔
1163
// ListSweeps returns a list of the sweeps recorded by the sweep store.
2✔
1164
func (s *UtxoSweeper) ListSweeps() ([]chainhash.Hash, error) {
2✔
1165
        return s.cfg.Store.ListSweeps()
2✔
1166
}
2✔
1167

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

1177
                return fn.None[wire.MsgTx]()
1178
        }
9✔
1179

9✔
1180
        // Query this input in the mempool. If this outpoint is already spent
9✔
1181
        // in mempool, we should get a spending event back immediately.
10✔
1182
        return s.cfg.Mempool.LookupInputMempoolSpend(op)
1✔
1183
}
1✔
1184

1✔
1185
// handleNewInput processes a new input by registering spend notification and
1✔
1186
// scheduling sweeping for it.
1187
func (s *UtxoSweeper) handleNewInput(input *sweepInputMessage) error {
1188
        // Create a default deadline height, which will be used when there's no
1189
        // DeadlineHeight specified for a given input.
8✔
1190
        defaultDeadline := s.currentHeight + int32(s.cfg.NoDeadlineConfTarget)
1191

1192
        outpoint := input.input.OutPoint()
1193
        pi, pending := s.inputs[outpoint]
1194
        if pending {
2✔
1195
                log.Debugf("Already has pending input %v received", outpoint)
2✔
1196

2✔
1197
                s.handleExistingInput(input, pi)
2✔
1198

2✔
1199
                return nil
2✔
1200
        }
2✔
1201

4✔
1202
        // This is a new input, and we want to query the mempool to see if this
2✔
1203
        // input has already been spent. If so, we'll start the input with
2✔
1204
        // state Published and attach the RBFInfo.
2✔
1205
        state, rbfInfo := s.decideStateAndRBFInfo(input.input.OutPoint())
2✔
1206

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

2✔
1222
        s.inputs[outpoint] = pi
2✔
1223
        log.Tracef("input %v, state=%v, added to inputs", outpoint, pi.state)
2✔
1224

2✔
1225
        // Start watching for spend of this input, either by us or the remote
2✔
1226
        // party.
2✔
1227
        cancel, err := s.monitorSpend(
2✔
1228
                outpoint, input.input.SignDesc().Output.PkScript,
2✔
1229
                input.input.HeightHint(),
2✔
1230
        )
2✔
1231
        if err != nil {
2✔
1232
                err := fmt.Errorf("wait for spend: %w", err)
2✔
1233
                s.markInputFailed(pi, err)
2✔
1234

2✔
1235
                return err
2✔
1236
        }
2✔
1237

2✔
1238
        pi.ntfnRegCancel = cancel
2✔
1239

×
1240
        return nil
×
1241
}
×
1242

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

1251
        // Check if we can find the spending tx of this input in mempool.
1252
        txOption := s.mempoolLookup(op)
1253

1254
        // Extract the spending tx from the option.
1255
        var tx *wire.MsgTx
1256
        txOption.WhenSome(func(t wire.MsgTx) {
6✔
1257
                tx = &t
6✔
1258
        })
6✔
1259

6✔
1260
        // Exit early if it's not found.
6✔
1261
        //
6✔
1262
        // NOTE: this is not accurate for backends that don't support mempool
6✔
1263
        // lookup:
11✔
1264
        // - for neutrino we don't have a mempool.
5✔
1265
        // - for btcd below v0.24.1 we don't have `gettxspendingprevout`.
5✔
1266
        if tx == nil {
1267
                return Init, fn.None[RBFInfo]()
1268
        }
1269

1270
        // Otherwise the input is already spent in the mempool, so eventually
1271
        // we will return Published.
1272
        //
1273
        // We also need to update the RBF info for this input. If the sweeping
9✔
1274
        // transaction is broadcast by us, we can find the fee info in the
3✔
1275
        // sweeper store.
3✔
1276
        txid := tx.TxHash()
1277
        tr, err := s.cfg.Store.GetTx(txid)
1278

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

5✔
1287
        // Exit if we get an db error.
5✔
1288
        if err != nil {
5✔
1289
                log.Errorf("Unable to get tx %v from sweeper store: %v",
8✔
1290
                        txid, err)
3✔
1291

3✔
1292
                return Published, fn.None[RBFInfo]()
3✔
1293
        }
1294

1295
        // Prepare the fee info and return it.
5✔
1296
        rbf := fn.Some(RBFInfo{
1✔
1297
                Txid:    txid,
1✔
1298
                Fee:     btcutil.Amount(tr.Fee),
1✔
1299
                FeeRate: chainfee.SatPerKWeight(tr.FeeRate),
1✔
1300
        })
1✔
1301

1302
        return Published, rbf
1303
}
3✔
1304

3✔
1305
// handleExistingInput processes an input that is already known to the sweeper.
3✔
1306
// It will overwrite the params of the old input with the new ones.
3✔
1307
func (s *UtxoSweeper) handleExistingInput(input *sweepInputMessage,
3✔
1308
        oldInput *SweeperInput) {
3✔
1309

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

2✔
1326
                prevExclGroup = new(uint64)
2✔
1327
                *prevExclGroup = *oldInput.params.ExclusiveGroup
2✔
1328
        }
2✔
1329

2✔
1330
        // Update input details and sweep parameters. The re-offered input
2✔
1331
        // details may contain a change to the unconfirmed parent tx info.
4✔
1332
        oldInput.params = input.params
2✔
1333
        oldInput.Input = input.input
2✔
1334

2✔
1335
        // If the new input specifies a deadline, update the deadline height.
2✔
1336
        oldInput.DeadlineHeight = input.params.DeadlineHeight.UnwrapOr(
1337
                oldInput.DeadlineHeight,
1338
        )
1339

2✔
1340
        // Add additional result channel to signal spend of this input.
2✔
1341
        oldInput.listeners = append(oldInput.listeners, input.resultChan)
2✔
1342

2✔
1343
        if prevExclGroup != nil {
2✔
1344
                s.removeExclusiveGroup(*prevExclGroup)
2✔
1345
        }
2✔
1346
}
2✔
1347

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

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

2✔
1374
                log.Debugf("Attempting to remove descendant txns invalidated "+
2✔
1375
                        "by (txid=%v): %v", spendingTx.TxHash(),
2✔
1376
                        spew.Sdump(spendingTx))
2✔
1377

4✔
1378
                err := s.removeConflictSweepDescendants(inputsSpent)
2✔
1379
                if err != nil {
2✔
1380
                        log.Warnf("unable to remove descendant transactions "+
1381
                                "due to tx %v: ", spendHash)
2✔
1382
                }
2✔
1383

2✔
1384
                log.Debugf("Detected third party spend related to in flight "+
2✔
1385
                        "inputs (is_ours=%v): %v", isOurTx,
2✔
1386
                        lnutils.SpewLogClosure(spend.SpendingTx))
2✔
1387
        }
×
1388

×
1389
        // We now use the spending tx to update the state of the inputs.
×
1390
        s.markInputsSwept(spend.SpendingTx, isOurTx)
1391
}
2✔
1392

2✔
1393
// markInputsSwept marks all inputs swept by the spending transaction as swept.
2✔
1394
// It will also notify all the subscribers of this input.
1395
func (s *UtxoSweeper) markInputsSwept(tx *wire.MsgTx, isOurTx bool) {
1396
        for _, txIn := range tx.TxIn {
1397
                outpoint := txIn.PreviousOutPoint
2✔
1398

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

6✔
1410
                        continue
6✔
1411
                }
9✔
1412

3✔
1413
                // This input may already been marked as swept by a previous
3✔
1414
                // spend notification, which is likely to happen as one sweep
3✔
1415
                // transaction usually sweeps multiple inputs.
3✔
1416
                if input.terminated() {
3✔
1417
                        log.Debugf("Skipped marking input as swept: %v "+
3✔
1418
                                "state=%v", outpoint, input.state)
1419

1420
                        continue
1421
                }
1422

1423
                input.state = Swept
6✔
1424

1✔
1425
                // Return either a nil or a remote spend result.
1✔
1426
                var err error
1✔
1427
                if !isOurTx {
1✔
1428
                        log.Warnf("Input=%v was spent by remote or third "+
1429
                                "party in tx=%v", outpoint, tx.TxHash())
1430
                        err = ErrRemoteSpend
4✔
1431
                }
4✔
1432

4✔
1433
                // Signal result channels.
4✔
1434
                s.signalResult(input, Result{
6✔
1435
                        Tx:  tx,
2✔
1436
                        Err: err,
2✔
1437
                })
2✔
1438

2✔
1439
                // Remove all other inputs in this exclusive group.
1440
                if input.params.ExclusiveGroup != nil {
1441
                        s.removeExclusiveGroup(*input.params.ExclusiveGroup)
4✔
1442
                }
4✔
1443
        }
4✔
1444
}
4✔
1445

4✔
1446
// markInputFailed marks the given input as failed and won't be retried. It
4✔
1447
// will also notify all the subscribers of this input.
6✔
1448
func (s *UtxoSweeper) markInputFailed(pi *SweeperInput, err error) {
2✔
1449
        log.Errorf("Failed to sweep input: %v, error: %v", pi, err)
2✔
1450

1451
        pi.state = Failed
1452

1453
        // Remove all other inputs in this exclusive group.
1454
        if pi.params.ExclusiveGroup != nil {
1455
                s.removeExclusiveGroup(*pi.params.ExclusiveGroup)
1✔
1456
        }
1✔
1457

1✔
1458
        s.signalResult(pi, Result{Err: err})
1✔
1459
}
1✔
1460

1✔
1461
// updateSweeperInputs updates the sweeper's internal state and returns a map
1✔
1462
// of inputs to be swept. It will remove the inputs that are in final states,
×
1463
// and returns a map of inputs that have either state Init or PublishFailed.
×
1464
func (s *UtxoSweeper) updateSweeperInputs() InputsMap {
1465
        // Create a map of inputs to be swept.
1✔
1466
        inputs := make(InputsMap)
1467

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

14✔
1482
                        delete(s.inputs, op)
11✔
1483

11✔
1484
                        continue
11✔
1485
                }
16✔
1486

5✔
1487
                // If this input has been included in a sweep tx that's not
5✔
1488
                // published yet, we'd skip this input and wait for the sweep
5✔
1489
                // tx to be published.
5✔
1490
                if input.state == PendingPublish {
5✔
1491
                        continue
5✔
1492
                }
1493

1494
                // If this input has already been published, we will need to
1495
                // check the RBF condition before attempting another sweeping.
1496
                if input.state == Published {
1497
                        continue
11✔
1498
                }
3✔
1499

1500
                // If the input has a locktime that's not yet reached, we will
1501
                // skip this input and wait for the locktime to be reached.
1502
                locktime, _ := input.RequiredLockTime()
1503
                if uint32(s.currentHeight) < locktime {
10✔
1504
                        log.Warnf("Skipping input %v due to locktime=%v not "+
3✔
1505
                                "reached, current height is %v", op, locktime,
1506
                                s.currentHeight)
1507

1508
                        continue
1509
                }
6✔
1510

9✔
1511
                // If the input has a CSV that's not yet reached, we will skip
3✔
1512
                // this input and wait for the expiry.
3✔
1513
                locktime = input.BlocksToMaturity() + input.HeightHint()
3✔
1514
                if s.currentHeight < int32(locktime)-1 {
3✔
1515
                        log.Infof("Skipping input %v due to CSV expiry=%v not "+
3✔
1516
                                "reached, current height is %v", op, locktime,
1517
                                s.currentHeight)
1518

1519
                        continue
1520
                }
5✔
1521

8✔
1522
                // If this input is new or has been failed to be published,
3✔
1523
                // we'd retry it. The assumption here is that when an error is
3✔
1524
                // returned from `PublishTransaction`, it means the tx has
3✔
1525
                // failed to meet the policy, hence it's not in the mempool.
3✔
1526
                inputs[op] = input
3✔
1527
        }
1528

1529
        return inputs
1530
}
1531

1532
// sweepPendingInputs is called when the ticker fires. It will create clusters
1533
// and attempt to create and publish the sweeping transactions.
4✔
1534
func (s *UtxoSweeper) sweepPendingInputs(inputs InputsMap) {
1535
        // Cluster all of our inputs based on the specific Aggregator.
1536
        sets := s.cfg.Aggregator.ClusterInputs(inputs)
3✔
1537

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

6✔
1549
                        // Create sweeping transaction for each set.
6✔
1550
                        err = s.sweep(set)
3✔
1551
                        if err != nil {
3✔
1552
                                return err
5✔
1553
                        }
2✔
1554

2✔
1555
                        return nil
1556
                })
1557
        }
3✔
1558

6✔
1559
        for _, set := range sets {
3✔
1560
                var err error
3✔
1561
                if set.NeedWalletInput() {
1562
                        // Sweep the set of inputs that need the wallet inputs.
2✔
1563
                        err = sweepWithLock(set)
1564
                } else {
1565
                        // Sweep the set of inputs that don't need the wallet
1566
                        // inputs.
7✔
1567
                        err = s.sweep(set)
4✔
1568
                }
7✔
1569

3✔
1570
                if err != nil {
3✔
1571
                        log.Errorf("Failed to sweep %v: %v", set, err)
6✔
1572
                }
3✔
1573
        }
3✔
1574
}
3✔
1575

3✔
1576
// monitorFeeBumpResult subscribes to the passed result chan to listen for
1577
// future updates about the sweeping tx.
8✔
1578
//
4✔
1579
// NOTE: must run as a goroutine.
4✔
1580
func (s *UtxoSweeper) monitorFeeBumpResult(resultChan <-chan *BumpResult) {
1581
        defer s.wg.Done()
1582

1583
        for {
1584
                select {
1585
                case r := <-resultChan:
1586
                        // Validate the result is valid.
1587
                        if err := r.Validate(); err != nil {
6✔
1588
                                log.Errorf("Received invalid result: %v", err)
6✔
1589
                                continue
6✔
1590
                        }
13✔
1591

7✔
1592
                        // Send the result back to the main event loop.
5✔
1593
                        select {
5✔
1594
                        case s.bumpResultChan <- r:
5✔
1595
                        case <-s.quit:
×
1596
                                log.Debug("Sweeper shutting down, skip " +
×
1597
                                        "sending bump result")
1598

1599
                                return
1600
                        }
5✔
1601

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

1613
                                // Cancel the rebroadcasting of the failed tx.
1614
                                s.cfg.Wallet.CancelRebroadcast(r.Tx.TxHash())
1615

9✔
1616
                                return
4✔
1617
                        }
4✔
1618

4✔
1619
                case <-s.quit:
4✔
1620
                        log.Debugf("Sweeper shutting down, exit fee " +
4✔
1621
                                "bump handler")
4✔
1622

4✔
1623
                        return
4✔
1624
                }
4✔
1625
        }
1626
}
4✔
1627

4✔
1628
// handleBumpEventTxFailed handles the case where the tx has been failed to
4✔
1629
// publish.
4✔
1630
func (s *UtxoSweeper) handleBumpEventTxFailed(r *BumpResult) error {
4✔
1631
        tx, err := r.Tx, r.Err
1632

1633
        log.Errorf("Fee bump attempt failed for tx=%v: %v", tx.TxHash(), err)
1634

1635
        outpoints := make([]wire.OutPoint, 0, len(tx.TxIn))
1636
        for _, inp := range tx.TxIn {
1637
                outpoints = append(outpoints, inp.PreviousOutPoint)
3✔
1638
        }
3✔
1639

3✔
1640
        // TODO(yy): should we also remove the failed tx from db?
3✔
1641
        s.markInputsPublishFailed(outpoints)
3✔
1642

3✔
1643
        return err
8✔
1644
}
5✔
1645

5✔
1646
// handleBumpEventTxReplaced handles the case where the sweeping tx has been
1647
// replaced by a new one.
1648
func (s *UtxoSweeper) handleBumpEventTxReplaced(r *BumpResult) error {
3✔
1649
        oldTx := r.ReplacedTx
3✔
1650
        newTx := r.Tx
3✔
1651

1652
        // Prepare a new record to replace the old one.
1653
        tr := &TxRecord{
1654
                Txid:    newTx.TxHash(),
1655
                FeeRate: uint64(r.FeeRate),
5✔
1656
                Fee:     uint64(r.Fee),
5✔
1657
        }
5✔
1658

5✔
1659
        // Get the old record for logging purpose.
5✔
1660
        oldTxid := oldTx.TxHash()
5✔
1661
        record, err := s.cfg.Store.GetTx(oldTxid)
5✔
1662
        if err != nil {
5✔
1663
                log.Errorf("Fetch tx record for %v: %v", oldTxid, err)
5✔
1664
                return err
5✔
1665
        }
5✔
1666

5✔
1667
        // Cancel the rebroadcasting of the replaced tx.
5✔
1668
        s.cfg.Wallet.CancelRebroadcast(oldTxid)
5✔
1669

6✔
1670
        log.Infof("RBFed tx=%v(fee=%v sats, feerate=%v sats/kw) with new "+
1✔
1671
                "tx=%v(fee=%v, "+"feerate=%v)", record.Txid, record.Fee,
1✔
1672
                record.FeeRate, tr.Txid, tr.Fee, tr.FeeRate)
1✔
1673

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

4✔
1687
        // Mark the inputs as published using the replacing tx.
4✔
1688
        return s.markInputsPublished(tr, r.Tx.TxIn)
4✔
1689
}
5✔
1690

1✔
1691
// handleBumpEventTxPublished handles the case where the sweeping tx has been
1✔
1692
// successfully published.
1✔
1693
func (s *UtxoSweeper) handleBumpEventTxPublished(r *BumpResult) error {
1694
        tx := r.Tx
1695
        tr := &TxRecord{
3✔
1696
                Txid:    tx.TxHash(),
1697
                FeeRate: uint64(r.FeeRate),
1698
                Fee:     uint64(r.Fee),
1699
        }
1700

3✔
1701
        // Inputs have been successfully published so we update their
3✔
1702
        // states.
3✔
1703
        err := s.markInputsPublished(tr, tx.TxIn)
3✔
1704
        if err != nil {
3✔
1705
                return err
3✔
1706
        }
3✔
1707

3✔
1708
        log.Debugf("Published sweep tx %v, num_inputs=%v, height=%v",
3✔
1709
                tx.TxHash(), len(tx.TxIn), s.currentHeight)
3✔
1710

3✔
1711
        // If there's no error, remove the output script. Otherwise
3✔
1712
        // keep it so that it can be reused for the next transaction
×
1713
        // and causes no address inflation.
×
1714
        s.currentOutputScript = nil
1715

3✔
1716
        return nil
3✔
1717
}
3✔
1718

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

1727
        switch r.Event {
1728
        // The tx has been published, we update the inputs' state and create a
1729
        // record to be stored in the sweeper db.
1730
        case TxPublished:
1731
                return s.handleBumpEventTxPublished(r)
3✔
1732

3✔
1733
        // The tx has failed, we update the inputs' state.
3✔
1734
        case TxFailed:
3✔
1735
                return s.handleBumpEventTxFailed(r)
1736

1737
        // The tx has been replaced, we will remove the old tx and replace it
2✔
1738
        // with the new one.
2✔
1739
        case TxReplaced:
1740
                return s.handleBumpEventTxReplaced(r)
1741
        }
3✔
1742

3✔
1743
        return nil
1744
}
1745

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

2✔
1763
                return true
2✔
1764
        }
2✔
1765

2✔
1766
        return found
×
1767
}
×
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