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

lightningnetwork / lnd / 11170835610

03 Oct 2024 10:41PM UTC coverage: 49.188% (-9.6%) from 58.738%
11170835610

push

github

web-flow
Merge pull request #9154 from ziggie1984/master

multi: bump btcd version.

3 of 6 new or added lines in 6 files covered. (50.0%)

26110 existing lines in 428 files now uncovered.

97359 of 197934 relevant lines covered (49.19%)

1.04 hits per line

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

77.9
/sweep/fee_bumper.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/rpcclient"
12
        "github.com/btcsuite/btcd/txscript"
13
        "github.com/btcsuite/btcd/wire"
14
        "github.com/btcsuite/btcwallet/chain"
15
        "github.com/lightningnetwork/lnd/chainntnfs"
16
        "github.com/lightningnetwork/lnd/fn"
17
        "github.com/lightningnetwork/lnd/input"
18
        "github.com/lightningnetwork/lnd/labels"
19
        "github.com/lightningnetwork/lnd/lntypes"
20
        "github.com/lightningnetwork/lnd/lnutils"
21
        "github.com/lightningnetwork/lnd/lnwallet"
22
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
23
        "github.com/lightningnetwork/lnd/tlv"
24
)
25

26
var (
27
        // ErrInvalidBumpResult is returned when the bump result is invalid.
28
        ErrInvalidBumpResult = errors.New("invalid bump result")
29

30
        // ErrNotEnoughBudget is returned when the fee bumper decides the
31
        // current budget cannot cover the fee.
32
        ErrNotEnoughBudget = errors.New("not enough budget")
33

34
        // ErrLocktimeImmature is returned when sweeping an input whose
35
        // locktime is not reached.
36
        ErrLocktimeImmature = errors.New("immature input")
37

38
        // ErrTxNoOutput is returned when an output cannot be created during tx
39
        // preparation, usually due to the output being dust.
40
        ErrTxNoOutput = errors.New("tx has no output")
41

42
        // ErrThirdPartySpent is returned when a third party has spent the
43
        // input in the sweeping tx.
44
        ErrThirdPartySpent = errors.New("third party spent the output")
45
)
46

47
var (
48
        // dummyChangePkScript is a dummy tapscript change script that's used
49
        // when we don't need a real address, just something that can be used
50
        // for fee estimation.
51
        dummyChangePkScript = []byte{
52
                0x51, 0x20,
53
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
54
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
55
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
56
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
57
        }
58
)
59

60
// Bumper defines an interface that can be used by other subsystems for fee
61
// bumping.
62
type Bumper interface {
63
        // Broadcast is used to publish the tx created from the given inputs
64
        // specified in the request. It handles the tx creation, broadcasts it,
65
        // and monitors its confirmation status for potential fee bumping. It
66
        // returns a chan that the caller can use to receive updates about the
67
        // broadcast result and potential RBF attempts.
68
        Broadcast(req *BumpRequest) (<-chan *BumpResult, error)
69
}
70

71
// BumpEvent represents the event of a fee bumping attempt.
72
type BumpEvent uint8
73

74
const (
75
        // TxPublished is sent when the broadcast attempt is finished.
76
        TxPublished BumpEvent = iota
77

78
        // TxFailed is sent when the broadcast attempt fails.
79
        TxFailed
80

81
        // TxReplaced is sent when the original tx is replaced by a new one.
82
        TxReplaced
83

84
        // TxConfirmed is sent when the tx is confirmed.
85
        TxConfirmed
86

87
        // sentinalEvent is used to check if an event is unknown.
88
        sentinalEvent
89
)
90

91
// String returns a human-readable string for the event.
92
func (e BumpEvent) String() string {
2✔
93
        switch e {
2✔
94
        case TxPublished:
2✔
95
                return "Published"
2✔
96
        case TxFailed:
2✔
97
                return "Failed"
2✔
98
        case TxReplaced:
2✔
99
                return "Replaced"
2✔
100
        case TxConfirmed:
2✔
101
                return "Confirmed"
2✔
102
        default:
×
103
                return "Unknown"
×
104
        }
105
}
106

107
// Unknown returns true if the event is unknown.
108
func (e BumpEvent) Unknown() bool {
2✔
109
        return e >= sentinalEvent
2✔
110
}
2✔
111

112
// BumpRequest is used by the caller to give the Bumper the necessary info to
113
// create and manage potential fee bumps for a set of inputs.
114
type BumpRequest struct {
115
        // Budget givens the total amount that can be used as fees by these
116
        // inputs.
117
        Budget btcutil.Amount
118

119
        // Inputs is the set of inputs to sweep.
120
        Inputs []input.Input
121

122
        // DeadlineHeight is the block height at which the tx should be
123
        // confirmed.
124
        DeadlineHeight int32
125

126
        // DeliveryAddress is the script to send the change output to.
127
        DeliveryAddress lnwallet.AddrWithKey
128

129
        // MaxFeeRate is the maximum fee rate that can be used for fee bumping.
130
        MaxFeeRate chainfee.SatPerKWeight
131

132
        // StartingFeeRate is an optional parameter that can be used to specify
133
        // the initial fee rate to use for the fee function.
134
        StartingFeeRate fn.Option[chainfee.SatPerKWeight]
135

136
        // ExtraTxOut tracks if this bump request has an optional set of extra
137
        // outputs to add to the transaction.
138
        ExtraTxOut fn.Option[SweepOutput]
139
}
140

141
// MaxFeeRateAllowed returns the maximum fee rate allowed for the given
142
// request. It calculates the feerate using the supplied budget and the weight,
143
// compares it with the specified MaxFeeRate, and returns the smaller of the
144
// two.
145
func (r *BumpRequest) MaxFeeRateAllowed() (chainfee.SatPerKWeight, error) {
2✔
146
        // We'll want to know if we have any blobs, as we need to factor this
2✔
147
        // into the max fee rate for this bump request.
2✔
148
        hasBlobs := fn.Any(func(i input.Input) bool {
4✔
149
                return fn.MapOptionZ(
2✔
150
                        i.ResolutionBlob(), func(b tlv.Blob) bool {
4✔
151
                                return len(b) > 0
2✔
152
                        },
2✔
153
                )
154
        }, r.Inputs)
155

156
        sweepAddrs := [][]byte{
2✔
157
                r.DeliveryAddress.DeliveryAddress,
2✔
158
        }
2✔
159

2✔
160
        // If we have blobs, then we'll add an extra sweep addr for the size
2✔
161
        // estimate below. We know that these blobs will also always be based on
2✔
162
        // p2tr addrs.
2✔
163
        if hasBlobs {
2✔
164
                // We need to pass in a real address, so we'll use a dummy
×
165
                // tapscript change script that's used elsewhere for tests.
×
166
                sweepAddrs = append(sweepAddrs, dummyChangePkScript)
×
167
        }
×
168

169
        // Get the size of the sweep tx, which will be used to calculate the
170
        // budget fee rate.
171
        size, err := calcSweepTxWeight(
2✔
172
                r.Inputs, sweepAddrs,
2✔
173
        )
2✔
174
        if err != nil {
2✔
UNCOV
175
                return 0, err
×
UNCOV
176
        }
×
177

178
        // Use the budget and MaxFeeRate to decide the max allowed fee rate.
179
        // This is needed as, when the input has a large value and the user
180
        // sets the budget to be proportional to the input value, the fee rate
181
        // can be very high and we need to make sure it doesn't exceed the max
182
        // fee rate.
183
        maxFeeRateAllowed := chainfee.NewSatPerKWeight(r.Budget, size)
2✔
184
        if maxFeeRateAllowed > r.MaxFeeRate {
4✔
185
                log.Debugf("Budget feerate %v exceeds MaxFeeRate %v, use "+
2✔
186
                        "MaxFeeRate instead, txWeight=%v", maxFeeRateAllowed,
2✔
187
                        r.MaxFeeRate, size)
2✔
188

2✔
189
                return r.MaxFeeRate, nil
2✔
190
        }
2✔
191

192
        log.Debugf("Budget feerate %v below MaxFeeRate %v, use budget feerate "+
2✔
193
                "instead, txWeight=%v", maxFeeRateAllowed, r.MaxFeeRate, size)
2✔
194

2✔
195
        return maxFeeRateAllowed, nil
2✔
196
}
197

198
// calcSweepTxWeight calculates the weight of the sweep tx. It assumes a
199
// sweeping tx always has a single output(change).
200
func calcSweepTxWeight(inputs []input.Input,
201
        outputPkScript [][]byte) (lntypes.WeightUnit, error) {
2✔
202

2✔
203
        // Use a const fee rate as we only use the weight estimator to
2✔
204
        // calculate the size.
2✔
205
        const feeRate = 1
2✔
206

2✔
207
        // Initialize the tx weight estimator with,
2✔
208
        // - nil outputs as we only have one single change output.
2✔
209
        // - const fee rate as we don't care about the fees here.
2✔
210
        // - 0 maxfeerate as we don't care about fees here.
2✔
211
        //
2✔
212
        // TODO(yy): we should refactor the weight estimator to not require a
2✔
213
        // fee rate and max fee rate and make it a pure tx weight calculator.
2✔
214
        _, estimator, err := getWeightEstimate(
2✔
215
                inputs, nil, feeRate, 0, outputPkScript,
2✔
216
        )
2✔
217
        if err != nil {
2✔
UNCOV
218
                return 0, err
×
UNCOV
219
        }
×
220

221
        return estimator.weight(), nil
2✔
222
}
223

224
// BumpResult is used by the Bumper to send updates about the tx being
225
// broadcast.
226
type BumpResult struct {
227
        // Event is the type of event that the result is for.
228
        Event BumpEvent
229

230
        // Tx is the tx being broadcast.
231
        Tx *wire.MsgTx
232

233
        // ReplacedTx is the old, replaced tx if a fee bump is attempted.
234
        ReplacedTx *wire.MsgTx
235

236
        // FeeRate is the fee rate used for the new tx.
237
        FeeRate chainfee.SatPerKWeight
238

239
        // Fee is the fee paid by the new tx.
240
        Fee btcutil.Amount
241

242
        // Err is the error that occurred during the broadcast.
243
        Err error
244

245
        // requestID is the ID of the request that created this record.
246
        requestID uint64
247
}
248

249
// Validate validates the BumpResult so it's safe to use.
250
func (b *BumpResult) Validate() error {
2✔
251
        // Every result must have a tx.
2✔
252
        if b.Tx == nil {
2✔
UNCOV
253
                return fmt.Errorf("%w: nil tx", ErrInvalidBumpResult)
×
UNCOV
254
        }
×
255

256
        // Every result must have a known event.
257
        if b.Event.Unknown() {
2✔
UNCOV
258
                return fmt.Errorf("%w: unknown event", ErrInvalidBumpResult)
×
UNCOV
259
        }
×
260

261
        // If it's a replacing event, it must have a replaced tx.
262
        if b.Event == TxReplaced && b.ReplacedTx == nil {
2✔
UNCOV
263
                return fmt.Errorf("%w: nil replacing tx", ErrInvalidBumpResult)
×
UNCOV
264
        }
×
265

266
        // If it's a failed event, it must have an error.
267
        if b.Event == TxFailed && b.Err == nil {
2✔
UNCOV
268
                return fmt.Errorf("%w: nil error", ErrInvalidBumpResult)
×
UNCOV
269
        }
×
270

271
        // If it's a confirmed event, it must have a fee rate and fee.
272
        if b.Event == TxConfirmed && (b.FeeRate == 0 || b.Fee == 0) {
2✔
UNCOV
273
                return fmt.Errorf("%w: missing fee rate or fee",
×
UNCOV
274
                        ErrInvalidBumpResult)
×
UNCOV
275
        }
×
276

277
        return nil
2✔
278
}
279

280
// TxPublisherConfig is the config used to create a new TxPublisher.
281
type TxPublisherConfig struct {
282
        // Signer is used to create the tx signature.
283
        Signer input.Signer
284

285
        // Wallet is used primarily to publish the tx.
286
        Wallet Wallet
287

288
        // Estimator is used to estimate the fee rate for the new tx based on
289
        // its deadline conf target.
290
        Estimator chainfee.Estimator
291

292
        // Notifier is used to monitor the confirmation status of the tx.
293
        Notifier chainntnfs.ChainNotifier
294

295
        // AuxSweeper is an optional interface that can be used to modify the
296
        // way sweep transaction are generated.
297
        AuxSweeper fn.Option[AuxSweeper]
298
}
299

300
// TxPublisher is an implementation of the Bumper interface. It utilizes the
301
// `testmempoolaccept` RPC to bump the fee of txns it created based on
302
// different fee function selected or configed by the caller. Its purpose is to
303
// take a list of inputs specified, and create a tx that spends them to a
304
// specified output. It will then monitor the confirmation status of the tx,
305
// and if it's not confirmed within a certain time frame, it will attempt to
306
// bump the fee of the tx by creating a new tx that spends the same inputs to
307
// the same output, but with a higher fee rate. It will continue to do this
308
// until the tx is confirmed or the fee rate reaches the maximum fee rate
309
// specified by the caller.
310
type TxPublisher struct {
311
        started atomic.Bool
312
        stopped atomic.Bool
313

314
        wg sync.WaitGroup
315

316
        // cfg specifies the configuration of the TxPublisher.
317
        cfg *TxPublisherConfig
318

319
        // currentHeight is the current block height.
320
        currentHeight atomic.Int32
321

322
        // records is a map keyed by the requestCounter and the value is the tx
323
        // being monitored.
324
        records lnutils.SyncMap[uint64, *monitorRecord]
325

326
        // requestCounter is a monotonically increasing counter used to keep
327
        // track of how many requests have been made.
328
        requestCounter atomic.Uint64
329

330
        // subscriberChans is a map keyed by the requestCounter, each item is
331
        // the chan that the publisher sends the fee bump result to.
332
        subscriberChans lnutils.SyncMap[uint64, chan *BumpResult]
333

334
        // quit is used to signal the publisher to stop.
335
        quit chan struct{}
336
}
337

338
// Compile-time constraint to ensure TxPublisher implements Bumper.
339
var _ Bumper = (*TxPublisher)(nil)
340

341
// NewTxPublisher creates a new TxPublisher.
342
func NewTxPublisher(cfg TxPublisherConfig) *TxPublisher {
2✔
343
        return &TxPublisher{
2✔
344
                cfg:             &cfg,
2✔
345
                records:         lnutils.SyncMap[uint64, *monitorRecord]{},
2✔
346
                subscriberChans: lnutils.SyncMap[uint64, chan *BumpResult]{},
2✔
347
                quit:            make(chan struct{}),
2✔
348
        }
2✔
349
}
2✔
350

351
// isNeutrinoBackend checks if the wallet backend is neutrino.
352
func (t *TxPublisher) isNeutrinoBackend() bool {
2✔
353
        return t.cfg.Wallet.BackEnd() == "neutrino"
2✔
354
}
2✔
355

356
// Broadcast is used to publish the tx created from the given inputs. It will,
357
// 1. init a fee function based on the given strategy.
358
// 2. create an RBF-compliant tx and monitor it for confirmation.
359
// 3. notify the initial broadcast result back to the caller.
360
// The initial broadcast is guaranteed to be RBF-compliant unless the budget
361
// specified cannot cover the fee.
362
//
363
// NOTE: part of the Bumper interface.
364
func (t *TxPublisher) Broadcast(req *BumpRequest) (<-chan *BumpResult, error) {
2✔
365
        log.Tracef("Received broadcast request: %s", lnutils.SpewLogClosure(
2✔
366
                req))
2✔
367

2✔
368
        // Attempt an initial broadcast which is guaranteed to comply with the
2✔
369
        // RBF rules.
2✔
370
        result, err := t.initialBroadcast(req)
2✔
371
        if err != nil {
4✔
372
                log.Errorf("Initial broadcast failed: %v", err)
2✔
373

2✔
374
                return nil, err
2✔
375
        }
2✔
376

377
        // Create a chan to send the result to the caller.
378
        subscriber := make(chan *BumpResult, 1)
2✔
379
        t.subscriberChans.Store(result.requestID, subscriber)
2✔
380

2✔
381
        // Send the initial broadcast result to the caller.
2✔
382
        t.handleResult(result)
2✔
383

2✔
384
        return subscriber, nil
2✔
385
}
386

387
// initialBroadcast initializes a fee function, creates an RBF-compliant tx and
388
// broadcasts it.
389
func (t *TxPublisher) initialBroadcast(req *BumpRequest) (*BumpResult, error) {
2✔
390
        // Create a fee bumping algorithm to be used for future RBF.
2✔
391
        feeAlgo, err := t.initializeFeeFunction(req)
2✔
392
        if err != nil {
4✔
393
                return nil, fmt.Errorf("init fee function: %w", err)
2✔
394
        }
2✔
395

396
        // Create the initial tx to be broadcasted. This tx is guaranteed to
397
        // comply with the RBF restrictions.
398
        requestID, err := t.createRBFCompliantTx(req, feeAlgo)
2✔
399
        if err != nil {
4✔
400
                return nil, fmt.Errorf("create RBF-compliant tx: %w", err)
2✔
401
        }
2✔
402

403
        // Broadcast the tx and return the monitored record.
404
        result, err := t.broadcast(requestID)
2✔
405
        if err != nil {
2✔
406
                return nil, fmt.Errorf("broadcast sweep tx: %w", err)
×
407
        }
×
408

409
        return result, nil
2✔
410
}
411

412
// initializeFeeFunction initializes a fee function to be used for this request
413
// for future fee bumping.
414
func (t *TxPublisher) initializeFeeFunction(
415
        req *BumpRequest) (FeeFunction, error) {
2✔
416

2✔
417
        // Get the max allowed feerate.
2✔
418
        maxFeeRateAllowed, err := req.MaxFeeRateAllowed()
2✔
419
        if err != nil {
2✔
420
                return nil, err
×
421
        }
×
422

423
        // Get the initial conf target.
424
        confTarget := calcCurrentConfTarget(
2✔
425
                t.currentHeight.Load(), req.DeadlineHeight,
2✔
426
        )
2✔
427

2✔
428
        log.Debugf("Initializing fee function with conf target=%v, budget=%v, "+
2✔
429
                "maxFeeRateAllowed=%v", confTarget, req.Budget,
2✔
430
                maxFeeRateAllowed)
2✔
431

2✔
432
        // Initialize the fee function and return it.
2✔
433
        //
2✔
434
        // TODO(yy): return based on differet req.Strategy?
2✔
435
        return NewLinearFeeFunction(
2✔
436
                maxFeeRateAllowed, confTarget, t.cfg.Estimator,
2✔
437
                req.StartingFeeRate,
2✔
438
        )
2✔
439
}
440

441
// createRBFCompliantTx creates a tx that is compliant with RBF rules. It does
442
// so by creating a tx, validate it using `TestMempoolAccept`, and bump its fee
443
// and redo the process until the tx is valid, or return an error when non-RBF
444
// related errors occur or the budget has been used up.
445
func (t *TxPublisher) createRBFCompliantTx(req *BumpRequest,
446
        f FeeFunction) (uint64, error) {
2✔
447

2✔
448
        for {
4✔
449
                // Create a new tx with the given fee rate and check its
2✔
450
                // mempool acceptance.
2✔
451
                sweepCtx, err := t.createAndCheckTx(req, f)
2✔
452

2✔
453
                switch {
2✔
454
                case err == nil:
2✔
455
                        // The tx is valid, return the request ID.
2✔
456
                        requestID := t.storeRecord(
2✔
457
                                sweepCtx.tx, req, f, sweepCtx.fee,
2✔
458
                        )
2✔
459

2✔
460
                        log.Infof("Created tx %v for %v inputs: feerate=%v, "+
2✔
461
                                "fee=%v, inputs=%v", sweepCtx.tx.TxHash(),
2✔
462
                                len(req.Inputs), f.FeeRate(), sweepCtx.fee,
2✔
463
                                inputTypeSummary(req.Inputs))
2✔
464

2✔
465
                        return requestID, nil
2✔
466

467
                // If the error indicates the fees paid is not enough, we will
468
                // ask the fee function to increase the fee rate and retry.
UNCOV
469
                case errors.Is(err, lnwallet.ErrMempoolFee):
×
UNCOV
470
                        // We should at least start with a feerate above the
×
UNCOV
471
                        // mempool min feerate, so if we get this error, it
×
UNCOV
472
                        // means something is wrong earlier in the pipeline.
×
UNCOV
473
                        log.Errorf("Current fee=%v, feerate=%v, %v",
×
UNCOV
474
                                sweepCtx.fee, f.FeeRate(), err)
×
UNCOV
475

×
UNCOV
476
                        fallthrough
×
477

478
                // We are not paying enough fees so we increase it.
479
                case errors.Is(err, chain.ErrInsufficientFee):
2✔
480
                        increased := false
2✔
481

2✔
482
                        // Keep calling the fee function until the fee rate is
2✔
483
                        // increased or maxed out.
2✔
484
                        for !increased {
4✔
485
                                log.Debugf("Increasing fee for next round, "+
2✔
486
                                        "current fee=%v, feerate=%v",
2✔
487
                                        sweepCtx.fee, f.FeeRate())
2✔
488

2✔
489
                                // If the fee function tells us that we have
2✔
490
                                // used up the budget, we will return an error
2✔
491
                                // indicating this tx cannot be made. The
2✔
492
                                // sweeper should handle this error and try to
2✔
493
                                // cluster these inputs differetly.
2✔
494
                                increased, err = f.Increment()
2✔
495
                                if err != nil {
4✔
496
                                        return 0, err
2✔
497
                                }
2✔
498
                        }
499

500
                // TODO(yy): suppose there's only one bad input, we can do a
501
                // binary search to find out which input is causing this error
502
                // by recreating a tx using half of the inputs and check its
503
                // mempool acceptance.
504
                default:
2✔
505
                        log.Debugf("Failed to create RBF-compliant tx: %v", err)
2✔
506
                        return 0, err
2✔
507
                }
508
        }
509
}
510

511
// storeRecord stores the given record in the records map.
512
func (t *TxPublisher) storeRecord(tx *wire.MsgTx, req *BumpRequest,
513
        f FeeFunction, fee btcutil.Amount) uint64 {
2✔
514

2✔
515
        // Increase the request counter.
2✔
516
        //
2✔
517
        // NOTE: this is the only place where we increase the
2✔
518
        // counter.
2✔
519
        requestID := t.requestCounter.Add(1)
2✔
520

2✔
521
        // Register the record.
2✔
522
        t.records.Store(requestID, &monitorRecord{
2✔
523
                tx:          tx,
2✔
524
                req:         req,
2✔
525
                feeFunction: f,
2✔
526
                fee:         fee,
2✔
527
        })
2✔
528

2✔
529
        return requestID
2✔
530
}
2✔
531

532
// createAndCheckTx creates a tx based on the given inputs, change output
533
// script, and the fee rate. In addition, it validates the tx's mempool
534
// acceptance before returning a tx that can be published directly, along with
535
// its fee.
536
func (t *TxPublisher) createAndCheckTx(req *BumpRequest,
537
        f FeeFunction) (*sweepTxCtx, error) {
2✔
538

2✔
539
        // Create the sweep tx with max fee rate of 0 as the fee function
2✔
540
        // guarantees the fee rate used here won't exceed the max fee rate.
2✔
541
        sweepCtx, err := t.createSweepTx(
2✔
542
                req.Inputs, req.DeliveryAddress, f.FeeRate(),
2✔
543
        )
2✔
544
        if err != nil {
4✔
545
                return sweepCtx, fmt.Errorf("create sweep tx: %w", err)
2✔
546
        }
2✔
547

548
        // Sanity check the budget still covers the fee.
549
        if sweepCtx.fee > req.Budget {
2✔
UNCOV
550
                return sweepCtx, fmt.Errorf("%w: budget=%v, fee=%v",
×
UNCOV
551
                        ErrNotEnoughBudget, req.Budget, sweepCtx.fee)
×
UNCOV
552
        }
×
553

554
        // If we had an extra txOut, then we'll update the result to include
555
        // it.
556
        req.ExtraTxOut = sweepCtx.extraTxOut
2✔
557

2✔
558
        // Validate the tx's mempool acceptance.
2✔
559
        err = t.cfg.Wallet.CheckMempoolAcceptance(sweepCtx.tx)
2✔
560

2✔
561
        // Exit early if the tx is valid.
2✔
562
        if err == nil {
4✔
563
                return sweepCtx, nil
2✔
564
        }
2✔
565

566
        // Print an error log if the chain backend doesn't support the mempool
567
        // acceptance test RPC.
568
        if errors.Is(err, rpcclient.ErrBackendVersion) {
2✔
569
                log.Errorf("TestMempoolAccept not supported by backend, " +
×
570
                        "consider upgrading it to a newer version")
×
571
                return sweepCtx, nil
×
572
        }
×
573

574
        // We are running on a backend that doesn't implement the RPC
575
        // testmempoolaccept, eg, neutrino, so we'll skip the check.
576
        if errors.Is(err, chain.ErrUnimplemented) {
2✔
UNCOV
577
                log.Debug("Skipped testmempoolaccept due to not implemented")
×
UNCOV
578
                return sweepCtx, nil
×
UNCOV
579
        }
×
580

581
        return sweepCtx, fmt.Errorf("tx=%v failed mempool check: %w",
2✔
582
                sweepCtx.tx.TxHash(), err)
2✔
583
}
584

585
// broadcast takes a monitored tx and publishes it to the network. Prior to the
586
// broadcast, it will subscribe the tx's confirmation notification and attach
587
// the event channel to the record. Any broadcast-related errors will not be
588
// returned here, instead, they will be put inside the `BumpResult` and
589
// returned to the caller.
590
func (t *TxPublisher) broadcast(requestID uint64) (*BumpResult, error) {
2✔
591
        // Get the record being monitored.
2✔
592
        record, ok := t.records.Load(requestID)
2✔
593
        if !ok {
2✔
UNCOV
594
                return nil, fmt.Errorf("tx record %v not found", requestID)
×
UNCOV
595
        }
×
596

597
        txid := record.tx.TxHash()
2✔
598

2✔
599
        tx := record.tx
2✔
600
        log.Debugf("Publishing sweep tx %v, num_inputs=%v, height=%v",
2✔
601
                txid, len(tx.TxIn), t.currentHeight.Load())
2✔
602

2✔
603
        // Before we go to broadcast, we'll notify the aux sweeper, if it's
2✔
604
        // present of this new broadcast attempt.
2✔
605
        err := fn.MapOptionZ(t.cfg.AuxSweeper, func(aux AuxSweeper) error {
2✔
UNCOV
606
                return aux.NotifyBroadcast(record.req, tx, record.fee)
×
UNCOV
607
        })
×
608
        if err != nil {
2✔
609
                return nil, fmt.Errorf("unable to notify aux sweeper: %w", err)
×
610
        }
×
611

612
        // Set the event, and change it to TxFailed if the wallet fails to
613
        // publish it.
614
        event := TxPublished
2✔
615

2✔
616
        // Publish the sweeping tx with customized label. If the publish fails,
2✔
617
        // this error will be saved in the `BumpResult` and it will be removed
2✔
618
        // from being monitored.
2✔
619
        err = t.cfg.Wallet.PublishTransaction(
2✔
620
                tx, labels.MakeLabel(labels.LabelTypeSweepTransaction, nil),
2✔
621
        )
2✔
622
        if err != nil {
2✔
UNCOV
623
                // NOTE: we decide to attach this error to the result instead
×
UNCOV
624
                // of returning it here because by the time the tx reaches
×
UNCOV
625
                // here, it should have passed the mempool acceptance check. If
×
UNCOV
626
                // it still fails to be broadcast, it's likely a non-RBF
×
UNCOV
627
                // related error happened. So we send this error back to the
×
UNCOV
628
                // caller so that it can handle it properly.
×
UNCOV
629
                //
×
UNCOV
630
                // TODO(yy): find out which input is causing the failure.
×
UNCOV
631
                log.Errorf("Failed to publish tx %v: %v", txid, err)
×
UNCOV
632
                event = TxFailed
×
UNCOV
633
        }
×
634

635
        result := &BumpResult{
2✔
636
                Event:     event,
2✔
637
                Tx:        record.tx,
2✔
638
                Fee:       record.fee,
2✔
639
                FeeRate:   record.feeFunction.FeeRate(),
2✔
640
                Err:       err,
2✔
641
                requestID: requestID,
2✔
642
        }
2✔
643

2✔
644
        return result, nil
2✔
645
}
646

647
// notifyResult sends the result to the resultChan specified by the requestID.
648
// This channel is expected to be read by the caller.
649
func (t *TxPublisher) notifyResult(result *BumpResult) {
2✔
650
        id := result.requestID
2✔
651
        subscriber, ok := t.subscriberChans.Load(id)
2✔
652
        if !ok {
2✔
UNCOV
653
                log.Errorf("Result chan for id=%v not found", id)
×
UNCOV
654
                return
×
UNCOV
655
        }
×
656

657
        log.Debugf("Sending result for requestID=%v, tx=%v", id,
2✔
658
                result.Tx.TxHash())
2✔
659

2✔
660
        select {
2✔
661
        // Send the result to the subscriber.
662
        //
663
        // TODO(yy): Add timeout in case it's blocking?
664
        case subscriber <- result:
2✔
UNCOV
665
        case <-t.quit:
×
UNCOV
666
                log.Debug("Fee bumper stopped")
×
667
        }
668
}
669

670
// removeResult removes the tracking of the result if the result contains a
671
// non-nil error, or the tx is confirmed, the record will be removed from the
672
// maps.
673
func (t *TxPublisher) removeResult(result *BumpResult) {
2✔
674
        id := result.requestID
2✔
675

2✔
676
        // Remove the record from the maps if there's an error. This means this
2✔
677
        // tx has failed its broadcast and cannot be retried. There are two
2✔
678
        // cases,
2✔
679
        // - when the budget cannot cover the fee.
2✔
680
        // - when a non-RBF related error occurs.
2✔
681
        switch result.Event {
2✔
682
        case TxFailed:
2✔
683
                log.Errorf("Removing monitor record=%v, tx=%v, due to err: %v",
2✔
684
                        id, result.Tx.TxHash(), result.Err)
2✔
685

686
        case TxConfirmed:
2✔
687
                // Remove the record is the tx is confirmed.
2✔
688
                log.Debugf("Removing confirmed monitor record=%v, tx=%v", id,
2✔
689
                        result.Tx.TxHash())
2✔
690

691
        // Do nothing if it's neither failed or confirmed.
692
        default:
2✔
693
                log.Tracef("Skipping record removal for id=%v, event=%v", id,
2✔
694
                        result.Event)
2✔
695

2✔
696
                return
2✔
697
        }
698

699
        t.records.Delete(id)
2✔
700
        t.subscriberChans.Delete(id)
2✔
701
}
702

703
// handleResult handles the result of a tx broadcast. It will notify the
704
// subscriber and remove the record if the tx is confirmed or failed to be
705
// broadcast.
706
func (t *TxPublisher) handleResult(result *BumpResult) {
2✔
707
        // Notify the subscriber.
2✔
708
        t.notifyResult(result)
2✔
709

2✔
710
        // Remove the record if it's failed or confirmed.
2✔
711
        t.removeResult(result)
2✔
712
}
2✔
713

714
// monitorRecord is used to keep track of the tx being monitored by the
715
// publisher internally.
716
type monitorRecord struct {
717
        // tx is the tx being monitored.
718
        tx *wire.MsgTx
719

720
        // req is the original request.
721
        req *BumpRequest
722

723
        // feeFunction is the fee bumping algorithm used by the publisher.
724
        feeFunction FeeFunction
725

726
        // fee is the fee paid by the tx.
727
        fee btcutil.Amount
728
}
729

730
// Start starts the publisher by subscribing to block epoch updates and kicking
731
// off the monitor loop.
732
func (t *TxPublisher) Start() error {
2✔
733
        log.Info("TxPublisher starting...")
2✔
734

2✔
735
        if t.started.Swap(true) {
2✔
736
                return fmt.Errorf("TxPublisher started more than once")
×
737
        }
×
738

739
        blockEvent, err := t.cfg.Notifier.RegisterBlockEpochNtfn(nil)
2✔
740
        if err != nil {
2✔
741
                return fmt.Errorf("register block epoch ntfn: %w", err)
×
742
        }
×
743

744
        t.wg.Add(1)
2✔
745
        go t.monitor(blockEvent)
2✔
746

2✔
747
        log.Debugf("TxPublisher started")
2✔
748

2✔
749
        return nil
2✔
750
}
751

752
// Stop stops the publisher and waits for the monitor loop to exit.
753
func (t *TxPublisher) Stop() error {
2✔
754
        log.Info("TxPublisher stopping...")
2✔
755

2✔
756
        if t.stopped.Swap(true) {
2✔
757
                return fmt.Errorf("TxPublisher stopped more than once")
×
758
        }
×
759

760
        close(t.quit)
2✔
761
        t.wg.Wait()
2✔
762

2✔
763
        log.Debug("TxPublisher stopped")
2✔
764

2✔
765
        return nil
2✔
766
}
767

768
// monitor is the main loop driven by new blocks. Whevenr a new block arrives,
769
// it will examine all the txns being monitored, and check if any of them needs
770
// to be bumped. If so, it will attempt to bump the fee of the tx.
771
//
772
// NOTE: Must be run as a goroutine.
773
func (t *TxPublisher) monitor(blockEvent *chainntnfs.BlockEpochEvent) {
2✔
774
        defer blockEvent.Cancel()
2✔
775
        defer t.wg.Done()
2✔
776

2✔
777
        for {
4✔
778
                select {
2✔
779
                case epoch, ok := <-blockEvent.Epochs:
2✔
780
                        if !ok {
2✔
781
                                // We should stop the publisher before stopping
×
782
                                // the chain service. Otherwise it indicates an
×
783
                                // error.
×
784
                                log.Error("Block epoch channel closed, exit " +
×
785
                                        "monitor")
×
786

×
787
                                return
×
788
                        }
×
789

790
                        log.Debugf("TxPublisher received new block: %v",
2✔
791
                                epoch.Height)
2✔
792

2✔
793
                        // Update the best known height for the publisher.
2✔
794
                        t.currentHeight.Store(epoch.Height)
2✔
795

2✔
796
                        // Check all monitored txns to see if any of them needs
2✔
797
                        // to be bumped.
2✔
798
                        t.processRecords()
2✔
799

800
                case <-t.quit:
2✔
801
                        log.Debug("Fee bumper stopped, exit monitor")
2✔
802
                        return
2✔
803
                }
804
        }
805
}
806

807
// processRecords checks all the txns being monitored, and checks if any of
808
// them needs to be bumped. If so, it will attempt to bump the fee of the tx.
809
func (t *TxPublisher) processRecords() {
2✔
810
        // confirmedRecords stores a map of the records which have been
2✔
811
        // confirmed.
2✔
812
        confirmedRecords := make(map[uint64]*monitorRecord)
2✔
813

2✔
814
        // feeBumpRecords stores a map of the records which need to be bumped.
2✔
815
        feeBumpRecords := make(map[uint64]*monitorRecord)
2✔
816

2✔
817
        // failedRecords stores a map of the records which has inputs being
2✔
818
        // spent by a third party.
2✔
819
        //
2✔
820
        // NOTE: this is only used for neutrino backend.
2✔
821
        failedRecords := make(map[uint64]*monitorRecord)
2✔
822

2✔
823
        // visitor is a helper closure that visits each record and divides them
2✔
824
        // into two groups.
2✔
825
        visitor := func(requestID uint64, r *monitorRecord) error {
4✔
826
                log.Tracef("Checking monitor recordID=%v for tx=%v", requestID,
2✔
827
                        r.tx.TxHash())
2✔
828

2✔
829
                // If the tx is already confirmed, we can stop monitoring it.
2✔
830
                if t.isConfirmed(r.tx.TxHash()) {
4✔
831
                        confirmedRecords[requestID] = r
2✔
832

2✔
833
                        // Move to the next record.
2✔
834
                        return nil
2✔
835
                }
2✔
836

837
                // Check whether the inputs has been spent by a third party.
838
                //
839
                // NOTE: this check is only done for neutrino backend.
840
                if t.isThirdPartySpent(r.tx.TxHash(), r.req.Inputs) {
2✔
UNCOV
841
                        failedRecords[requestID] = r
×
UNCOV
842

×
UNCOV
843
                        // Move to the next record.
×
UNCOV
844
                        return nil
×
UNCOV
845
                }
×
846

847
                feeBumpRecords[requestID] = r
2✔
848

2✔
849
                // Return nil to move to the next record.
2✔
850
                return nil
2✔
851
        }
852

853
        // Iterate through all the records and divide them into two groups.
854
        t.records.ForEach(visitor)
2✔
855

2✔
856
        // For records that are confirmed, we'll notify the caller about this
2✔
857
        // result.
2✔
858
        for requestID, r := range confirmedRecords {
4✔
859
                rec := r
2✔
860

2✔
861
                log.Debugf("Tx=%v is confirmed", r.tx.TxHash())
2✔
862
                t.wg.Add(1)
2✔
863
                go t.handleTxConfirmed(rec, requestID)
2✔
864
        }
2✔
865

866
        // Get the current height to be used in the following goroutines.
867
        currentHeight := t.currentHeight.Load()
2✔
868

2✔
869
        // For records that are not confirmed, we perform a fee bump if needed.
2✔
870
        for requestID, r := range feeBumpRecords {
4✔
871
                rec := r
2✔
872

2✔
873
                log.Debugf("Attempting to fee bump Tx=%v", r.tx.TxHash())
2✔
874
                t.wg.Add(1)
2✔
875
                go t.handleFeeBumpTx(requestID, rec, currentHeight)
2✔
876
        }
2✔
877

878
        // For records that are failed, we'll notify the caller about this
879
        // result.
880
        for requestID, r := range failedRecords {
2✔
UNCOV
881
                rec := r
×
UNCOV
882

×
UNCOV
883
                log.Debugf("Tx=%v has inputs been spent by a third party, "+
×
UNCOV
884
                        "failing it now", r.tx.TxHash())
×
UNCOV
885
                t.wg.Add(1)
×
UNCOV
886
                go t.handleThirdPartySpent(rec, requestID)
×
UNCOV
887
        }
×
888
}
889

890
// handleTxConfirmed is called when a monitored tx is confirmed. It will
891
// notify the subscriber then remove the record from the maps .
892
//
893
// NOTE: Must be run as a goroutine to avoid blocking on sending the result.
894
func (t *TxPublisher) handleTxConfirmed(r *monitorRecord, requestID uint64) {
2✔
895
        defer t.wg.Done()
2✔
896

2✔
897
        // Create a result that will be sent to the resultChan which is
2✔
898
        // listened by the caller.
2✔
899
        result := &BumpResult{
2✔
900
                Event:     TxConfirmed,
2✔
901
                Tx:        r.tx,
2✔
902
                requestID: requestID,
2✔
903
                Fee:       r.fee,
2✔
904
                FeeRate:   r.feeFunction.FeeRate(),
2✔
905
        }
2✔
906

2✔
907
        // Notify that this tx is confirmed and remove the record from the map.
2✔
908
        t.handleResult(result)
2✔
909
}
2✔
910

911
// handleFeeBumpTx checks if the tx needs to be bumped, and if so, it will
912
// attempt to bump the fee of the tx.
913
//
914
// NOTE: Must be run as a goroutine to avoid blocking on sending the result.
915
func (t *TxPublisher) handleFeeBumpTx(requestID uint64, r *monitorRecord,
916
        currentHeight int32) {
2✔
917

2✔
918
        defer t.wg.Done()
2✔
919

2✔
920
        oldTxid := r.tx.TxHash()
2✔
921

2✔
922
        // Get the current conf target for this record.
2✔
923
        confTarget := calcCurrentConfTarget(currentHeight, r.req.DeadlineHeight)
2✔
924

2✔
925
        // Ask the fee function whether a bump is needed. We expect the fee
2✔
926
        // function to increase its returned fee rate after calling this
2✔
927
        // method.
2✔
928
        increased, err := r.feeFunction.IncreaseFeeRate(confTarget)
2✔
929
        if err != nil {
4✔
930
                // TODO(yy): send this error back to the sweeper so it can
2✔
931
                // re-group the inputs?
2✔
932
                log.Errorf("Failed to increase fee rate for tx %v at "+
2✔
933
                        "height=%v: %v", oldTxid, t.currentHeight.Load(), err)
2✔
934

2✔
935
                return
2✔
936
        }
2✔
937

938
        // If the fee rate was not increased, there's no need to bump the fee.
939
        if !increased {
4✔
940
                log.Tracef("Skip bumping tx %v at height=%v", oldTxid,
2✔
941
                        t.currentHeight.Load())
2✔
942

2✔
943
                return
2✔
944
        }
2✔
945

946
        // The fee function now has a new fee rate, we will use it to bump the
947
        // fee of the tx.
948
        resultOpt := t.createAndPublishTx(requestID, r)
2✔
949

2✔
950
        // If there's a result, we will notify the caller about the result.
2✔
951
        resultOpt.WhenSome(func(result BumpResult) {
4✔
952
                // Notify the new result.
2✔
953
                t.handleResult(&result)
2✔
954
        })
2✔
955
}
956

957
// handleThirdPartySpent is called when the inputs in an unconfirmed tx is
958
// spent. It will notify the subscriber then remove the record from the maps
959
// and send a TxFailed event to the subscriber.
960
//
961
// NOTE: Must be run as a goroutine to avoid blocking on sending the result.
962
func (t *TxPublisher) handleThirdPartySpent(r *monitorRecord,
UNCOV
963
        requestID uint64) {
×
UNCOV
964

×
UNCOV
965
        defer t.wg.Done()
×
UNCOV
966

×
UNCOV
967
        // Create a result that will be sent to the resultChan which is
×
UNCOV
968
        // listened by the caller.
×
UNCOV
969
        //
×
UNCOV
970
        // TODO(yy): create a new state `TxThirdPartySpent` to notify the
×
UNCOV
971
        // sweeper to remove the input, hence moving the monitoring of inputs
×
UNCOV
972
        // spent inside the fee bumper.
×
UNCOV
973
        result := &BumpResult{
×
UNCOV
974
                Event:     TxFailed,
×
UNCOV
975
                Tx:        r.tx,
×
UNCOV
976
                requestID: requestID,
×
UNCOV
977
                Err:       ErrThirdPartySpent,
×
UNCOV
978
        }
×
UNCOV
979

×
UNCOV
980
        // Notify that this tx is confirmed and remove the record from the map.
×
UNCOV
981
        t.handleResult(result)
×
UNCOV
982
}
×
983

984
// createAndPublishTx creates a new tx with a higher fee rate and publishes it
985
// to the network. It will update the record with the new tx and fee rate if
986
// successfully created, and return the result when published successfully.
987
func (t *TxPublisher) createAndPublishTx(requestID uint64,
988
        r *monitorRecord) fn.Option[BumpResult] {
2✔
989

2✔
990
        // Fetch the old tx.
2✔
991
        oldTx := r.tx
2✔
992

2✔
993
        // Create a new tx with the new fee rate.
2✔
994
        //
2✔
995
        // NOTE: The fee function is expected to have increased its returned
2✔
996
        // fee rate after calling the SkipFeeBump method. So we can use it
2✔
997
        // directly here.
2✔
998
        sweepCtx, err := t.createAndCheckTx(r.req, r.feeFunction)
2✔
999

2✔
1000
        // If the error is fee related, we will return no error and let the fee
2✔
1001
        // bumper retry it at next block.
2✔
1002
        //
2✔
1003
        // NOTE: we can check the RBF error here and ask the fee function to
2✔
1004
        // recalculate the fee rate. However, this would defeat the purpose of
2✔
1005
        // using a deadline based fee function:
2✔
1006
        // - if the deadline is far away, there's no rush to RBF the tx.
2✔
1007
        // - if the deadline is close, we expect the fee function to give us a
2✔
1008
        //   higher fee rate. If the fee rate cannot satisfy the RBF rules, it
2✔
1009
        //   means the budget is not enough.
2✔
1010
        if errors.Is(err, chain.ErrInsufficientFee) ||
2✔
1011
                errors.Is(err, lnwallet.ErrMempoolFee) {
4✔
1012

2✔
1013
                log.Debugf("Failed to bump tx %v: %v", oldTx.TxHash(), err)
2✔
1014
                return fn.None[BumpResult]()
2✔
1015
        }
2✔
1016

1017
        // If the error is not fee related, we will return a `TxFailed` event
1018
        // so this input can be retried.
1019
        if err != nil {
4✔
1020
                // If the tx doesn't not have enought budget, we will return a
2✔
1021
                // result so the sweeper can handle it by re-clustering the
2✔
1022
                // utxos.
2✔
1023
                if errors.Is(err, ErrNotEnoughBudget) {
2✔
UNCOV
1024
                        log.Warnf("Fail to fee bump tx %v: %v", oldTx.TxHash(),
×
UNCOV
1025
                                err)
×
1026
                } else {
2✔
1027
                        // Otherwise, an unexpected error occurred, we will
2✔
1028
                        // fail the tx and let the sweeper retry the whole
2✔
1029
                        // process.
2✔
1030
                        log.Errorf("Failed to bump tx %v: %v", oldTx.TxHash(),
2✔
1031
                                err)
2✔
1032
                }
2✔
1033

1034
                return fn.Some(BumpResult{
2✔
1035
                        Event:     TxFailed,
2✔
1036
                        Tx:        oldTx,
2✔
1037
                        Err:       err,
2✔
1038
                        requestID: requestID,
2✔
1039
                })
2✔
1040
        }
1041

1042
        // The tx has been created without any errors, we now register a new
1043
        // record by overwriting the same requestID.
1044
        t.records.Store(requestID, &monitorRecord{
2✔
1045
                tx:          sweepCtx.tx,
2✔
1046
                req:         r.req,
2✔
1047
                feeFunction: r.feeFunction,
2✔
1048
                fee:         sweepCtx.fee,
2✔
1049
        })
2✔
1050

2✔
1051
        // Attempt to broadcast this new tx.
2✔
1052
        result, err := t.broadcast(requestID)
2✔
1053
        if err != nil {
2✔
1054
                log.Infof("Failed to broadcast replacement tx %v: %v",
×
1055
                        sweepCtx.tx.TxHash(), err)
×
1056

×
1057
                return fn.None[BumpResult]()
×
1058
        }
×
1059

1060
        // If the result error is fee related, we will return no error and let
1061
        // the fee bumper retry it at next block.
1062
        //
1063
        // NOTE: we may get this error if we've bypassed the mempool check,
1064
        // which means we are suing neutrino backend.
1065
        if errors.Is(result.Err, chain.ErrInsufficientFee) ||
2✔
1066
                errors.Is(result.Err, lnwallet.ErrMempoolFee) {
2✔
UNCOV
1067

×
UNCOV
1068
                log.Debugf("Failed to bump tx %v: %v", oldTx.TxHash(), err)
×
UNCOV
1069
                return fn.None[BumpResult]()
×
UNCOV
1070
        }
×
1071

1072
        // A successful replacement tx is created, attach the old tx.
1073
        result.ReplacedTx = oldTx
2✔
1074

2✔
1075
        // If the new tx failed to be published, we will return the result so
2✔
1076
        // the caller can handle it.
2✔
1077
        if result.Event == TxFailed {
2✔
UNCOV
1078
                return fn.Some(*result)
×
UNCOV
1079
        }
×
1080

1081
        log.Infof("Replaced tx=%v with new tx=%v", oldTx.TxHash(),
2✔
1082
                sweepCtx.tx.TxHash())
2✔
1083

2✔
1084
        // Otherwise, it's a successful RBF, set the event and return.
2✔
1085
        result.Event = TxReplaced
2✔
1086

2✔
1087
        return fn.Some(*result)
2✔
1088
}
1089

1090
// isConfirmed checks the btcwallet to see whether the tx is confirmed.
1091
func (t *TxPublisher) isConfirmed(txid chainhash.Hash) bool {
2✔
1092
        details, err := t.cfg.Wallet.GetTransactionDetails(&txid)
2✔
1093
        if err != nil {
4✔
1094
                log.Warnf("Failed to get tx details for %v: %v", txid, err)
2✔
1095
                return false
2✔
1096
        }
2✔
1097

1098
        return details.NumConfirmations > 0
2✔
1099
}
1100

1101
// isThirdPartySpent checks whether the inputs of the tx has already been spent
1102
// by a third party. When a tx is not confirmed, yet its inputs has been spent,
1103
// then it must be spent by a different tx other than the sweeping tx here.
1104
//
1105
// NOTE: this check is only performed for neutrino backend as it has no
1106
// reliable way to tell a tx has been replaced.
1107
func (t *TxPublisher) isThirdPartySpent(txid chainhash.Hash,
1108
        inputs []input.Input) bool {
2✔
1109

2✔
1110
        // Skip this check for if this is not neutrino backend.
2✔
1111
        if !t.isNeutrinoBackend() {
4✔
1112
                return false
2✔
1113
        }
2✔
1114

1115
        // Iterate all the inputs and check if they have been spent already.
UNCOV
1116
        for _, inp := range inputs {
×
UNCOV
1117
                op := inp.OutPoint()
×
UNCOV
1118

×
UNCOV
1119
                // For wallet utxos, the height hint is not set - we don't need
×
UNCOV
1120
                // to monitor them for third party spend.
×
UNCOV
1121
                heightHint := inp.HeightHint()
×
UNCOV
1122
                if heightHint == 0 {
×
UNCOV
1123
                        log.Debugf("Skipped third party check for wallet "+
×
UNCOV
1124
                                "input %v", op)
×
UNCOV
1125

×
UNCOV
1126
                        continue
×
1127
                }
1128

1129
                // If the input has already been spent after the height hint, a
1130
                // spend event is sent back immediately.
UNCOV
1131
                spendEvent, err := t.cfg.Notifier.RegisterSpendNtfn(
×
UNCOV
1132
                        &op, inp.SignDesc().Output.PkScript, heightHint,
×
UNCOV
1133
                )
×
UNCOV
1134
                if err != nil {
×
1135
                        log.Criticalf("Failed to register spend ntfn for "+
×
1136
                                "input=%v: %v", op, err)
×
1137
                        return false
×
1138
                }
×
1139

1140
                // Remove the subscription when exit.
UNCOV
1141
                defer spendEvent.Cancel()
×
UNCOV
1142

×
UNCOV
1143
                // Do a non-blocking read to see if the output has been spent.
×
UNCOV
1144
                select {
×
UNCOV
1145
                case spend, ok := <-spendEvent.Spend:
×
UNCOV
1146
                        if !ok {
×
1147
                                log.Debugf("Spend ntfn for %v canceled", op)
×
1148
                                return false
×
1149
                        }
×
1150

UNCOV
1151
                        spendingTxID := spend.SpendingTx.TxHash()
×
UNCOV
1152

×
UNCOV
1153
                        // If the spending tx is the same as the sweeping tx
×
UNCOV
1154
                        // then we are good.
×
UNCOV
1155
                        if spendingTxID == txid {
×
UNCOV
1156
                                continue
×
1157
                        }
1158

UNCOV
1159
                        log.Warnf("Detected third party spent of output=%v "+
×
UNCOV
1160
                                "in tx=%v", op, spend.SpendingTx.TxHash())
×
UNCOV
1161

×
UNCOV
1162
                        return true
×
1163

1164
                // Move to the next input.
UNCOV
1165
                default:
×
1166
                }
1167
        }
1168

UNCOV
1169
        return false
×
1170
}
1171

1172
// calcCurrentConfTarget calculates the current confirmation target based on
1173
// the deadline height. The conf target is capped at 0 if the deadline has
1174
// already been past.
1175
func calcCurrentConfTarget(currentHeight, deadline int32) uint32 {
2✔
1176
        var confTarget uint32
2✔
1177

2✔
1178
        // Calculate how many blocks left until the deadline.
2✔
1179
        deadlineDelta := deadline - currentHeight
2✔
1180

2✔
1181
        // If we are already past the deadline, we will set the conf target to
2✔
1182
        // be 1.
2✔
1183
        if deadlineDelta < 0 {
4✔
1184
                log.Warnf("Deadline is %d blocks behind current height %v",
2✔
1185
                        -deadlineDelta, currentHeight)
2✔
1186

2✔
1187
                confTarget = 0
2✔
1188
        } else {
4✔
1189
                confTarget = uint32(deadlineDelta)
2✔
1190
        }
2✔
1191

1192
        return confTarget
2✔
1193
}
1194

1195
// sweepTxCtx houses a sweep transaction with additional context.
1196
type sweepTxCtx struct {
1197
        tx *wire.MsgTx
1198

1199
        fee btcutil.Amount
1200

1201
        extraTxOut fn.Option[SweepOutput]
1202
}
1203

1204
// createSweepTx creates a sweeping tx based on the given inputs, change
1205
// address and fee rate.
1206
func (t *TxPublisher) createSweepTx(inputs []input.Input,
1207
        changePkScript lnwallet.AddrWithKey,
1208
        feeRate chainfee.SatPerKWeight) (*sweepTxCtx, error) {
2✔
1209

2✔
1210
        // Validate and calculate the fee and change amount.
2✔
1211
        txFee, changeOutputsOpt, locktimeOpt, err := prepareSweepTx(
2✔
1212
                inputs, changePkScript, feeRate, t.currentHeight.Load(),
2✔
1213
                t.cfg.AuxSweeper,
2✔
1214
        )
2✔
1215
        if err != nil {
4✔
1216
                return nil, err
2✔
1217
        }
2✔
1218

1219
        var (
2✔
1220
                // Create the sweep transaction that we will be building. We
2✔
1221
                // use version 2 as it is required for CSV.
2✔
1222
                sweepTx = wire.NewMsgTx(2)
2✔
1223

2✔
1224
                // We'll add the inputs as we go so we know the final ordering
2✔
1225
                // of inputs to sign.
2✔
1226
                idxs []input.Input
2✔
1227
        )
2✔
1228

2✔
1229
        // We start by adding all inputs that commit to an output. We do this
2✔
1230
        // since the input and output index must stay the same for the
2✔
1231
        // signatures to be valid.
2✔
1232
        for _, o := range inputs {
4✔
1233
                if o.RequiredTxOut() == nil {
4✔
1234
                        continue
2✔
1235
                }
1236

1237
                idxs = append(idxs, o)
2✔
1238
                sweepTx.AddTxIn(&wire.TxIn{
2✔
1239
                        PreviousOutPoint: o.OutPoint(),
2✔
1240
                        Sequence:         o.BlocksToMaturity(),
2✔
1241
                })
2✔
1242
                sweepTx.AddTxOut(o.RequiredTxOut())
2✔
1243
        }
1244

1245
        // Sum up the value contained in the remaining inputs, and add them to
1246
        // the sweep transaction.
1247
        for _, o := range inputs {
4✔
1248
                if o.RequiredTxOut() != nil {
4✔
1249
                        continue
2✔
1250
                }
1251

1252
                idxs = append(idxs, o)
2✔
1253
                sweepTx.AddTxIn(&wire.TxIn{
2✔
1254
                        PreviousOutPoint: o.OutPoint(),
2✔
1255
                        Sequence:         o.BlocksToMaturity(),
2✔
1256
                })
2✔
1257
        }
1258

1259
        // If we have change outputs to add, then add it the sweep transaction
1260
        // here.
1261
        changeOutputsOpt.WhenSome(func(changeOuts []SweepOutput) {
4✔
1262
                for i := range changeOuts {
4✔
1263
                        sweepTx.AddTxOut(&changeOuts[i].TxOut)
2✔
1264
                }
2✔
1265
        })
1266

1267
        // We'll default to using the current block height as locktime, if none
1268
        // of the inputs commits to a different locktime.
1269
        sweepTx.LockTime = uint32(locktimeOpt.UnwrapOr(t.currentHeight.Load()))
2✔
1270

2✔
1271
        prevInputFetcher, err := input.MultiPrevOutFetcher(inputs)
2✔
1272
        if err != nil {
2✔
1273
                return nil, fmt.Errorf("error creating prev input fetcher "+
×
1274
                        "for hash cache: %v", err)
×
1275
        }
×
1276
        hashCache := txscript.NewTxSigHashes(sweepTx, prevInputFetcher)
2✔
1277

2✔
1278
        // With all the inputs in place, use each output's unique input script
2✔
1279
        // function to generate the final witness required for spending.
2✔
1280
        addInputScript := func(idx int, tso input.Input) error {
4✔
1281
                inputScript, err := tso.CraftInputScript(
2✔
1282
                        t.cfg.Signer, sweepTx, hashCache, prevInputFetcher, idx,
2✔
1283
                )
2✔
1284
                if err != nil {
2✔
1285
                        return err
×
1286
                }
×
1287

1288
                sweepTx.TxIn[idx].Witness = inputScript.Witness
2✔
1289

2✔
1290
                if len(inputScript.SigScript) == 0 {
4✔
1291
                        return nil
2✔
1292
                }
2✔
1293

1294
                sweepTx.TxIn[idx].SignatureScript = inputScript.SigScript
×
1295

×
1296
                return nil
×
1297
        }
1298

1299
        for idx, inp := range idxs {
4✔
1300
                if err := addInputScript(idx, inp); err != nil {
2✔
1301
                        return nil, err
×
1302
                }
×
1303
        }
1304

1305
        log.Debugf("Created sweep tx %v for inputs:\n%v", sweepTx.TxHash(),
2✔
1306
                inputTypeSummary(inputs))
2✔
1307

2✔
1308
        // Try to locate the extra change output, though there might be None.
2✔
1309
        extraTxOut := fn.MapOption(
2✔
1310
                func(sweepOuts []SweepOutput) fn.Option[SweepOutput] {
4✔
1311
                        for _, sweepOut := range sweepOuts {
4✔
1312
                                if !sweepOut.IsExtra {
4✔
1313
                                        continue
2✔
1314
                                }
1315

1316
                                // If we sweep outputs of a custom channel, the
1317
                                // custom leaves in those outputs will be merged
1318
                                // into a single output, even if we sweep
1319
                                // multiple outputs (e.g. to_remote and breached
1320
                                // to_local of a breached channel) at the same
1321
                                // time. So there will only ever be one extra
1322
                                // output.
1323
                                log.Debugf("Sweep produced extra_sweep_out=%v",
×
1324
                                        lnutils.SpewLogClosure(sweepOut))
×
1325

×
1326
                                return fn.Some(sweepOut)
×
1327
                        }
1328

1329
                        return fn.None[SweepOutput]()
2✔
1330
                },
1331
        )(changeOutputsOpt)
1332

1333
        return &sweepTxCtx{
2✔
1334
                tx:         sweepTx,
2✔
1335
                fee:        txFee,
2✔
1336
                extraTxOut: fn.FlattenOption(extraTxOut),
2✔
1337
        }, nil
2✔
1338
}
1339

1340
// prepareSweepTx returns the tx fee, a set of optional change outputs and an
1341
// optional locktime after a series of validations:
1342
// 1. check the locktime has been reached.
1343
// 2. check the locktimes are the same.
1344
// 3. check the inputs cover the outputs.
1345
//
1346
// NOTE: if the change amount is below dust, it will be added to the tx fee.
1347
func prepareSweepTx(inputs []input.Input, changePkScript lnwallet.AddrWithKey,
1348
        feeRate chainfee.SatPerKWeight, currentHeight int32,
1349
        auxSweeper fn.Option[AuxSweeper]) (
1350
        btcutil.Amount, fn.Option[[]SweepOutput], fn.Option[int32], error) {
2✔
1351

2✔
1352
        noChange := fn.None[[]SweepOutput]()
2✔
1353
        noLocktime := fn.None[int32]()
2✔
1354

2✔
1355
        // Given the set of inputs we have, if we have an aux sweeper, then
2✔
1356
        // we'll attempt to see if we have any other change outputs we'll need
2✔
1357
        // to add to the sweep transaction.
2✔
1358
        changePkScripts := [][]byte{changePkScript.DeliveryAddress}
2✔
1359

2✔
1360
        var extraChangeOut fn.Option[SweepOutput]
2✔
1361
        err := fn.MapOptionZ(
2✔
1362
                auxSweeper, func(aux AuxSweeper) error {
2✔
UNCOV
1363
                        extraOut := aux.DeriveSweepAddr(inputs, changePkScript)
×
UNCOV
1364
                        if err := extraOut.Err(); err != nil {
×
1365
                                return err
×
1366
                        }
×
1367

UNCOV
1368
                        extraChangeOut = extraOut.LeftToOption()
×
UNCOV
1369

×
UNCOV
1370
                        return nil
×
1371
                },
1372
        )
1373
        if err != nil {
2✔
1374
                return 0, noChange, noLocktime, err
×
1375
        }
×
1376

1377
        // Creating a weight estimator with nil outputs and zero max fee rate.
1378
        // We don't allow adding customized outputs in the sweeping tx, and the
1379
        // fee rate is already being managed before we get here.
1380
        inputs, estimator, err := getWeightEstimate(
2✔
1381
                inputs, nil, feeRate, 0, changePkScripts,
2✔
1382
        )
2✔
1383
        if err != nil {
2✔
1384
                return 0, noChange, noLocktime, err
×
1385
        }
×
1386

1387
        txFee := estimator.fee()
2✔
1388

2✔
1389
        var (
2✔
1390
                // Track whether any of the inputs require a certain locktime.
2✔
1391
                locktime = int32(-1)
2✔
1392

2✔
1393
                // We keep track of total input amount, and required output
2✔
1394
                // amount to use for calculating the change amount below.
2✔
1395
                totalInput     btcutil.Amount
2✔
1396
                requiredOutput btcutil.Amount
2✔
1397
        )
2✔
1398

2✔
1399
        // If we have an extra change output, then we'll add it as a required
2✔
1400
        // output amt.
2✔
1401
        extraChangeOut.WhenSome(func(o SweepOutput) {
2✔
UNCOV
1402
                requiredOutput += btcutil.Amount(o.Value)
×
UNCOV
1403
        })
×
1404

1405
        // Go through each input and check if the required lock times have
1406
        // reached and are the same.
1407
        for _, o := range inputs {
4✔
1408
                // If the input has a required output, we'll add it to the
2✔
1409
                // required output amount.
2✔
1410
                if o.RequiredTxOut() != nil {
4✔
1411
                        requiredOutput += btcutil.Amount(
2✔
1412
                                o.RequiredTxOut().Value,
2✔
1413
                        )
2✔
1414
                }
2✔
1415

1416
                // Update the total input amount.
1417
                totalInput += btcutil.Amount(o.SignDesc().Output.Value)
2✔
1418

2✔
1419
                lt, ok := o.RequiredLockTime()
2✔
1420

2✔
1421
                // Skip if the input doesn't require a lock time.
2✔
1422
                if !ok {
4✔
1423
                        continue
2✔
1424
                }
1425

1426
                // Check if the lock time has reached
1427
                if lt > uint32(currentHeight) {
2✔
1428
                        return 0, noChange, noLocktime, ErrLocktimeImmature
×
1429
                }
×
1430

1431
                // If another input commits to a different locktime, they
1432
                // cannot be combined in the same transaction.
1433
                if locktime != -1 && locktime != int32(lt) {
2✔
1434
                        return 0, noChange, noLocktime, ErrLocktimeConflict
×
1435
                }
×
1436

1437
                // Update the locktime for next iteration.
1438
                locktime = int32(lt)
2✔
1439
        }
1440

1441
        // Make sure total output amount is less than total input amount.
1442
        if requiredOutput+txFee > totalInput {
2✔
1443
                return 0, noChange, noLocktime, fmt.Errorf("insufficient "+
×
1444
                        "input to create sweep tx: input_sum=%v, "+
×
1445
                        "output_sum=%v", totalInput, requiredOutput+txFee)
×
1446
        }
×
1447

1448
        // The value remaining after the required output and fees is the
1449
        // change output.
1450
        changeAmt := totalInput - requiredOutput - txFee
2✔
1451
        changeOuts := make([]SweepOutput, 0, 2)
2✔
1452

2✔
1453
        extraChangeOut.WhenSome(func(o SweepOutput) {
2✔
UNCOV
1454
                changeOuts = append(changeOuts, o)
×
UNCOV
1455
        })
×
1456

1457
        // We'll calculate the dust limit for the given changePkScript since it
1458
        // is variable.
1459
        changeFloor := lnwallet.DustLimitForSize(
2✔
1460
                len(changePkScript.DeliveryAddress),
2✔
1461
        )
2✔
1462

2✔
1463
        switch {
2✔
1464
        // If the change amount is dust, we'll move it into the fees, and
1465
        // ignore it.
1466
        case changeAmt < changeFloor:
2✔
1467
                log.Infof("Change amt %v below dustlimit %v, not adding "+
2✔
1468
                        "change output", changeAmt, changeFloor)
2✔
1469

2✔
1470
                // If there's no required output, and the change output is a
2✔
1471
                // dust, it means we are creating a tx without any outputs. In
2✔
1472
                // this case we'll return an error. This could happen when
2✔
1473
                // creating a tx that has an anchor as the only input.
2✔
1474
                if requiredOutput == 0 {
4✔
1475
                        return 0, noChange, noLocktime, ErrTxNoOutput
2✔
1476
                }
2✔
1477

1478
                // The dust amount is added to the fee.
1479
                txFee += changeAmt
×
1480

1481
        // Otherwise, we'll actually recognize it as a change output.
1482
        default:
2✔
1483
                changeOuts = append(changeOuts, SweepOutput{
2✔
1484
                        TxOut: wire.TxOut{
2✔
1485
                                Value:    int64(changeAmt),
2✔
1486
                                PkScript: changePkScript.DeliveryAddress,
2✔
1487
                        },
2✔
1488
                        IsExtra:     false,
2✔
1489
                        InternalKey: changePkScript.InternalKey,
2✔
1490
                })
2✔
1491
        }
1492

1493
        // Optionally set the locktime.
1494
        locktimeOpt := fn.Some(locktime)
2✔
1495
        if locktime == -1 {
4✔
1496
                locktimeOpt = noLocktime
2✔
1497
        }
2✔
1498

1499
        var changeOutsOpt fn.Option[[]SweepOutput]
2✔
1500
        if len(changeOuts) > 0 {
4✔
1501
                changeOutsOpt = fn.Some(changeOuts)
2✔
1502
        }
2✔
1503

1504
        log.Debugf("Creating sweep tx for %v inputs (%s) using %v, "+
2✔
1505
                "tx_weight=%v, tx_fee=%v, locktime=%v, parents_count=%v, "+
2✔
1506
                "parents_fee=%v, parents_weight=%v, current_height=%v",
2✔
1507
                len(inputs), inputTypeSummary(inputs), feeRate,
2✔
1508
                estimator.weight(), txFee, locktimeOpt, len(estimator.parents),
2✔
1509
                estimator.parentsFee, estimator.parentsWeight, currentHeight)
2✔
1510

2✔
1511
        return txFee, changeOutsOpt, locktimeOpt, nil
2✔
1512
}
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