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

lightningnetwork / lnd / 10207481183

01 Aug 2024 11:52PM UTC coverage: 58.679% (+0.09%) from 58.591%
10207481183

push

github

web-flow
Merge pull request #8836 from hieblmi/payment-failure-reason-cancel

routing: add payment failure reason `FailureReasonCancel`

7 of 30 new or added lines in 5 files covered. (23.33%)

1662 existing lines in 21 files now uncovered.

125454 of 213798 relevant lines covered (58.68%)

28679.1 hits per line

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

92.72
/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
)
24

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

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

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

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

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

46
// Bumper defines an interface that can be used by other subsystems for fee
47
// bumping.
48
type Bumper interface {
49
        // Broadcast is used to publish the tx created from the given inputs
50
        // specified in the request. It handles the tx creation, broadcasts it,
51
        // and monitors its confirmation status for potential fee bumping. It
52
        // returns a chan that the caller can use to receive updates about the
53
        // broadcast result and potential RBF attempts.
54
        Broadcast(req *BumpRequest) (<-chan *BumpResult, error)
55
}
56

57
// BumpEvent represents the event of a fee bumping attempt.
58
type BumpEvent uint8
59

60
const (
61
        // TxPublished is sent when the broadcast attempt is finished.
62
        TxPublished BumpEvent = iota
63

64
        // TxFailed is sent when the broadcast attempt fails.
65
        TxFailed
66

67
        // TxReplaced is sent when the original tx is replaced by a new one.
68
        TxReplaced
69

70
        // TxConfirmed is sent when the tx is confirmed.
71
        TxConfirmed
72

73
        // sentinalEvent is used to check if an event is unknown.
74
        sentinalEvent
75
)
76

77
// String returns a human-readable string for the event.
78
func (e BumpEvent) String() string {
4✔
79
        switch e {
4✔
80
        case TxPublished:
4✔
81
                return "Published"
4✔
82
        case TxFailed:
4✔
83
                return "Failed"
4✔
84
        case TxReplaced:
4✔
85
                return "Replaced"
4✔
86
        case TxConfirmed:
4✔
87
                return "Confirmed"
4✔
88
        default:
×
89
                return "Unknown"
×
90
        }
91
}
92

93
// Unknown returns true if the event is unknown.
94
func (e BumpEvent) Unknown() bool {
12✔
95
        return e >= sentinalEvent
12✔
96
}
12✔
97

98
// BumpRequest is used by the caller to give the Bumper the necessary info to
99
// create and manage potential fee bumps for a set of inputs.
100
type BumpRequest struct {
101
        // Budget givens the total amount that can be used as fees by these
102
        // inputs.
103
        Budget btcutil.Amount
104

105
        // Inputs is the set of inputs to sweep.
106
        Inputs []input.Input
107

108
        // DeadlineHeight is the block height at which the tx should be
109
        // confirmed.
110
        DeadlineHeight int32
111

112
        // DeliveryAddress is the script to send the change output to.
113
        DeliveryAddress []byte
114

115
        // MaxFeeRate is the maximum fee rate that can be used for fee bumping.
116
        MaxFeeRate chainfee.SatPerKWeight
117

118
        // StartingFeeRate is an optional parameter that can be used to specify
119
        // the initial fee rate to use for the fee function.
120
        StartingFeeRate fn.Option[chainfee.SatPerKWeight]
121
}
122

123
// MaxFeeRateAllowed returns the maximum fee rate allowed for the given
124
// request. It calculates the feerate using the supplied budget and the weight,
125
// compares it with the specified MaxFeeRate, and returns the smaller of the
126
// two.
127
func (r *BumpRequest) MaxFeeRateAllowed() (chainfee.SatPerKWeight, error) {
12✔
128
        // Get the size of the sweep tx, which will be used to calculate the
12✔
129
        // budget fee rate.
12✔
130
        size, err := calcSweepTxWeight(r.Inputs, r.DeliveryAddress)
12✔
131
        if err != nil {
13✔
132
                return 0, err
1✔
133
        }
1✔
134

135
        // Use the budget and MaxFeeRate to decide the max allowed fee rate.
136
        // This is needed as, when the input has a large value and the user
137
        // sets the budget to be proportional to the input value, the fee rate
138
        // can be very high and we need to make sure it doesn't exceed the max
139
        // fee rate.
140
        maxFeeRateAllowed := chainfee.NewSatPerKWeight(r.Budget, size)
11✔
141
        if maxFeeRateAllowed > r.MaxFeeRate {
16✔
142
                log.Debugf("Budget feerate %v exceeds MaxFeeRate %v, use "+
5✔
143
                        "MaxFeeRate instead, txWeight=%v", maxFeeRateAllowed,
5✔
144
                        r.MaxFeeRate, size)
5✔
145

5✔
146
                return r.MaxFeeRate, nil
5✔
147
        }
5✔
148

149
        log.Debugf("Budget feerate %v below MaxFeeRate %v, use budget feerate "+
10✔
150
                "instead, txWeight=%v", maxFeeRateAllowed, r.MaxFeeRate, size)
10✔
151

10✔
152
        return maxFeeRateAllowed, nil
10✔
153
}
154

155
// calcSweepTxWeight calculates the weight of the sweep tx. It assumes a
156
// sweeping tx always has a single output(change).
157
func calcSweepTxWeight(inputs []input.Input,
158
        outputPkScript []byte) (lntypes.WeightUnit, error) {
15✔
159

15✔
160
        // Use a const fee rate as we only use the weight estimator to
15✔
161
        // calculate the size.
15✔
162
        const feeRate = 1
15✔
163

15✔
164
        // Initialize the tx weight estimator with,
15✔
165
        // - nil outputs as we only have one single change output.
15✔
166
        // - const fee rate as we don't care about the fees here.
15✔
167
        // - 0 maxfeerate as we don't care about fees here.
15✔
168
        //
15✔
169
        // TODO(yy): we should refactor the weight estimator to not require a
15✔
170
        // fee rate and max fee rate and make it a pure tx weight calculator.
15✔
171
        _, estimator, err := getWeightEstimate(
15✔
172
                inputs, nil, feeRate, 0, outputPkScript,
15✔
173
        )
15✔
174
        if err != nil {
17✔
175
                return 0, err
2✔
176
        }
2✔
177

178
        return estimator.weight(), nil
13✔
179
}
180

181
// BumpResult is used by the Bumper to send updates about the tx being
182
// broadcast.
183
type BumpResult struct {
184
        // Event is the type of event that the result is for.
185
        Event BumpEvent
186

187
        // Tx is the tx being broadcast.
188
        Tx *wire.MsgTx
189

190
        // ReplacedTx is the old, replaced tx if a fee bump is attempted.
191
        ReplacedTx *wire.MsgTx
192

193
        // FeeRate is the fee rate used for the new tx.
194
        FeeRate chainfee.SatPerKWeight
195

196
        // Fee is the fee paid by the new tx.
197
        Fee btcutil.Amount
198

199
        // Err is the error that occurred during the broadcast.
200
        Err error
201

202
        // requestID is the ID of the request that created this record.
203
        requestID uint64
204
}
205

206
// Validate validates the BumpResult so it's safe to use.
207
func (b *BumpResult) Validate() error {
13✔
208
        // Every result must have a tx.
13✔
209
        if b.Tx == nil {
14✔
210
                return fmt.Errorf("%w: nil tx", ErrInvalidBumpResult)
1✔
211
        }
1✔
212

213
        // Every result must have a known event.
214
        if b.Event.Unknown() {
13✔
215
                return fmt.Errorf("%w: unknown event", ErrInvalidBumpResult)
1✔
216
        }
1✔
217

218
        // If it's a replacing event, it must have a replaced tx.
219
        if b.Event == TxReplaced && b.ReplacedTx == nil {
12✔
220
                return fmt.Errorf("%w: nil replacing tx", ErrInvalidBumpResult)
1✔
221
        }
1✔
222

223
        // If it's a failed event, it must have an error.
224
        if b.Event == TxFailed && b.Err == nil {
11✔
225
                return fmt.Errorf("%w: nil error", ErrInvalidBumpResult)
1✔
226
        }
1✔
227

228
        // If it's a confirmed event, it must have a fee rate and fee.
229
        if b.Event == TxConfirmed && (b.FeeRate == 0 || b.Fee == 0) {
10✔
230
                return fmt.Errorf("%w: missing fee rate or fee",
1✔
231
                        ErrInvalidBumpResult)
1✔
232
        }
1✔
233

234
        return nil
8✔
235
}
236

237
// TxPublisherConfig is the config used to create a new TxPublisher.
238
type TxPublisherConfig struct {
239
        // Signer is used to create the tx signature.
240
        Signer input.Signer
241

242
        // Wallet is used primarily to publish the tx.
243
        Wallet Wallet
244

245
        // Estimator is used to estimate the fee rate for the new tx based on
246
        // its deadline conf target.
247
        Estimator chainfee.Estimator
248

249
        // Notifier is used to monitor the confirmation status of the tx.
250
        Notifier chainntnfs.ChainNotifier
251
}
252

253
// TxPublisher is an implementation of the Bumper interface. It utilizes the
254
// `testmempoolaccept` RPC to bump the fee of txns it created based on
255
// different fee function selected or configed by the caller. Its purpose is to
256
// take a list of inputs specified, and create a tx that spends them to a
257
// specified output. It will then monitor the confirmation status of the tx,
258
// and if it's not confirmed within a certain time frame, it will attempt to
259
// bump the fee of the tx by creating a new tx that spends the same inputs to
260
// the same output, but with a higher fee rate. It will continue to do this
261
// until the tx is confirmed or the fee rate reaches the maximum fee rate
262
// specified by the caller.
263
type TxPublisher struct {
264
        started atomic.Bool
265
        stopped atomic.Bool
266

267
        wg sync.WaitGroup
268

269
        // cfg specifies the configuration of the TxPublisher.
270
        cfg *TxPublisherConfig
271

272
        // currentHeight is the current block height.
273
        currentHeight atomic.Int32
274

275
        // records is a map keyed by the requestCounter and the value is the tx
276
        // being monitored.
277
        records lnutils.SyncMap[uint64, *monitorRecord]
278

279
        // requestCounter is a monotonically increasing counter used to keep
280
        // track of how many requests have been made.
281
        requestCounter atomic.Uint64
282

283
        // subscriberChans is a map keyed by the requestCounter, each item is
284
        // the chan that the publisher sends the fee bump result to.
285
        subscriberChans lnutils.SyncMap[uint64, chan *BumpResult]
286

287
        // quit is used to signal the publisher to stop.
288
        quit chan struct{}
289
}
290

291
// Compile-time constraint to ensure TxPublisher implements Bumper.
292
var _ Bumper = (*TxPublisher)(nil)
293

294
// NewTxPublisher creates a new TxPublisher.
295
func NewTxPublisher(cfg TxPublisherConfig) *TxPublisher {
18✔
296
        return &TxPublisher{
18✔
297
                cfg:             &cfg,
18✔
298
                records:         lnutils.SyncMap[uint64, *monitorRecord]{},
18✔
299
                subscriberChans: lnutils.SyncMap[uint64, chan *BumpResult]{},
18✔
300
                quit:            make(chan struct{}),
18✔
301
        }
18✔
302
}
18✔
303

304
// isNeutrinoBackend checks if the wallet backend is neutrino.
305
func (t *TxPublisher) isNeutrinoBackend() bool {
5✔
306
        return t.cfg.Wallet.BackEnd() == "neutrino"
5✔
307
}
5✔
308

309
// Broadcast is used to publish the tx created from the given inputs. It will,
310
// 1. init a fee function based on the given strategy.
311
// 2. create an RBF-compliant tx and monitor it for confirmation.
312
// 3. notify the initial broadcast result back to the caller.
313
// The initial broadcast is guaranteed to be RBF-compliant unless the budget
314
// specified cannot cover the fee.
315
//
316
// NOTE: part of the Bumper interface.
317
func (t *TxPublisher) Broadcast(req *BumpRequest) (<-chan *BumpResult, error) {
7✔
318
        log.Tracef("Received broadcast request: %s", lnutils.SpewLogClosure(
7✔
319
                req))
7✔
320

7✔
321
        // Attempt an initial broadcast which is guaranteed to comply with the
7✔
322
        // RBF rules.
7✔
323
        result, err := t.initialBroadcast(req)
7✔
324
        if err != nil {
12✔
325
                log.Errorf("Initial broadcast failed: %v", err)
5✔
326

5✔
327
                return nil, err
5✔
328
        }
5✔
329

330
        // Create a chan to send the result to the caller.
331
        subscriber := make(chan *BumpResult, 1)
6✔
332
        t.subscriberChans.Store(result.requestID, subscriber)
6✔
333

6✔
334
        // Send the initial broadcast result to the caller.
6✔
335
        t.handleResult(result)
6✔
336

6✔
337
        return subscriber, nil
6✔
338
}
339

340
// initialBroadcast initializes a fee function, creates an RBF-compliant tx and
341
// broadcasts it.
342
func (t *TxPublisher) initialBroadcast(req *BumpRequest) (*BumpResult, error) {
7✔
343
        // Create a fee bumping algorithm to be used for future RBF.
7✔
344
        feeAlgo, err := t.initializeFeeFunction(req)
7✔
345
        if err != nil {
11✔
346
                return nil, fmt.Errorf("init fee function: %w", err)
4✔
347
        }
4✔
348

349
        // Create the initial tx to be broadcasted. This tx is guaranteed to
350
        // comply with the RBF restrictions.
351
        requestID, err := t.createRBFCompliantTx(req, feeAlgo)
7✔
352
        if err != nil {
12✔
353
                return nil, fmt.Errorf("create RBF-compliant tx: %w", err)
5✔
354
        }
5✔
355

356
        // Broadcast the tx and return the monitored record.
357
        result, err := t.broadcast(requestID)
6✔
358
        if err != nil {
6✔
UNCOV
359
                return nil, fmt.Errorf("broadcast sweep tx: %w", err)
×
UNCOV
360
        }
×
361

362
        return result, nil
6✔
363
}
364

365
// initializeFeeFunction initializes a fee function to be used for this request
366
// for future fee bumping.
367
func (t *TxPublisher) initializeFeeFunction(
368
        req *BumpRequest) (FeeFunction, error) {
9✔
369

9✔
370
        // Get the max allowed feerate.
9✔
371
        maxFeeRateAllowed, err := req.MaxFeeRateAllowed()
9✔
372
        if err != nil {
9✔
UNCOV
373
                return nil, err
×
UNCOV
374
        }
×
375

376
        // Get the initial conf target.
377
        confTarget := calcCurrentConfTarget(
9✔
378
                t.currentHeight.Load(), req.DeadlineHeight,
9✔
379
        )
9✔
380

9✔
381
        log.Debugf("Initializing fee function with conf target=%v, budget=%v, "+
9✔
382
                "maxFeeRateAllowed=%v", confTarget, req.Budget,
9✔
383
                maxFeeRateAllowed)
9✔
384

9✔
385
        // Initialize the fee function and return it.
9✔
386
        //
9✔
387
        // TODO(yy): return based on differet req.Strategy?
9✔
388
        return NewLinearFeeFunction(
9✔
389
                maxFeeRateAllowed, confTarget, t.cfg.Estimator,
9✔
390
                req.StartingFeeRate,
9✔
391
        )
9✔
392
}
393

394
// createRBFCompliantTx creates a tx that is compliant with RBF rules. It does
395
// so by creating a tx, validate it using `TestMempoolAccept`, and bump its fee
396
// and redo the process until the tx is valid, or return an error when non-RBF
397
// related errors occur or the budget has been used up.
398
func (t *TxPublisher) createRBFCompliantTx(req *BumpRequest,
399
        f FeeFunction) (uint64, error) {
13✔
400

13✔
401
        for {
29✔
402
                // Create a new tx with the given fee rate and check its
16✔
403
                // mempool acceptance.
16✔
404
                tx, fee, err := t.createAndCheckTx(req, f)
16✔
405

16✔
406
                switch {
16✔
407
                case err == nil:
10✔
408
                        // The tx is valid, return the request ID.
10✔
409
                        requestID := t.storeRecord(tx, req, f, fee)
10✔
410

10✔
411
                        log.Infof("Created tx %v for %v inputs: feerate=%v, "+
10✔
412
                                "fee=%v, inputs=%v", tx.TxHash(),
10✔
413
                                len(req.Inputs), f.FeeRate(), fee,
10✔
414
                                inputTypeSummary(req.Inputs))
10✔
415

10✔
416
                        return requestID, nil
10✔
417

418
                // If the error indicates the fees paid is not enough, we will
419
                // ask the fee function to increase the fee rate and retry.
420
                case errors.Is(err, lnwallet.ErrMempoolFee):
2✔
421
                        // We should at least start with a feerate above the
2✔
422
                        // mempool min feerate, so if we get this error, it
2✔
423
                        // means something is wrong earlier in the pipeline.
2✔
424
                        log.Errorf("Current fee=%v, feerate=%v, %v", fee,
2✔
425
                                f.FeeRate(), err)
2✔
426

2✔
427
                        fallthrough
2✔
428

429
                // We are not paying enough fees so we increase it.
430
                case errors.Is(err, chain.ErrInsufficientFee):
7✔
431
                        increased := false
7✔
432

7✔
433
                        // Keep calling the fee function until the fee rate is
7✔
434
                        // increased or maxed out.
7✔
435
                        for !increased {
15✔
436
                                log.Debugf("Increasing fee for next round, "+
8✔
437
                                        "current fee=%v, feerate=%v", fee,
8✔
438
                                        f.FeeRate())
8✔
439

8✔
440
                                // If the fee function tells us that we have
8✔
441
                                // used up the budget, we will return an error
8✔
442
                                // indicating this tx cannot be made. The
8✔
443
                                // sweeper should handle this error and try to
8✔
444
                                // cluster these inputs differetly.
8✔
445
                                increased, err = f.Increment()
8✔
446
                                if err != nil {
12✔
447
                                        return 0, err
4✔
448
                                }
4✔
449
                        }
450

451
                // TODO(yy): suppose there's only one bad input, we can do a
452
                // binary search to find out which input is causing this error
453
                // by recreating a tx using half of the inputs and check its
454
                // mempool acceptance.
455
                default:
6✔
456
                        log.Debugf("Failed to create RBF-compliant tx: %v", err)
6✔
457
                        return 0, err
6✔
458
                }
459
        }
460
}
461

462
// storeRecord stores the given record in the records map.
463
func (t *TxPublisher) storeRecord(tx *wire.MsgTx, req *BumpRequest,
464
        f FeeFunction, fee btcutil.Amount) uint64 {
18✔
465

18✔
466
        // Increase the request counter.
18✔
467
        //
18✔
468
        // NOTE: this is the only place where we increase the
18✔
469
        // counter.
18✔
470
        requestID := t.requestCounter.Add(1)
18✔
471

18✔
472
        // Register the record.
18✔
473
        t.records.Store(requestID, &monitorRecord{
18✔
474
                tx:          tx,
18✔
475
                req:         req,
18✔
476
                feeFunction: f,
18✔
477
                fee:         fee,
18✔
478
        })
18✔
479

18✔
480
        return requestID
18✔
481
}
18✔
482

483
// createAndCheckTx creates a tx based on the given inputs, change output
484
// script, and the fee rate. In addition, it validates the tx's mempool
485
// acceptance before returning a tx that can be published directly, along with
486
// its fee.
487
func (t *TxPublisher) createAndCheckTx(req *BumpRequest, f FeeFunction) (
488
        *wire.MsgTx, btcutil.Amount, error) {
26✔
489

26✔
490
        // Create the sweep tx with max fee rate of 0 as the fee function
26✔
491
        // guarantees the fee rate used here won't exceed the max fee rate.
26✔
492
        tx, fee, err := t.createSweepTx(
26✔
493
                req.Inputs, req.DeliveryAddress, f.FeeRate(),
26✔
494
        )
26✔
495
        if err != nil {
30✔
496
                return nil, fee, fmt.Errorf("create sweep tx: %w", err)
4✔
497
        }
4✔
498

499
        // Sanity check the budget still covers the fee.
500
        if fee > req.Budget {
28✔
501
                return nil, fee, fmt.Errorf("%w: budget=%v, fee=%v",
2✔
502
                        ErrNotEnoughBudget, req.Budget, fee)
2✔
503
        }
2✔
504

505
        // Validate the tx's mempool acceptance.
506
        err = t.cfg.Wallet.CheckMempoolAcceptance(tx)
24✔
507

24✔
508
        // Exit early if the tx is valid.
24✔
509
        if err == nil {
38✔
510
                return tx, fee, nil
14✔
511
        }
14✔
512

513
        // Print an error log if the chain backend doesn't support the mempool
514
        // acceptance test RPC.
515
        if errors.Is(err, rpcclient.ErrBackendVersion) {
13✔
516
                log.Errorf("TestMempoolAccept not supported by backend, " +
×
UNCOV
517
                        "consider upgrading it to a newer version")
×
UNCOV
518
                return tx, fee, nil
×
UNCOV
519
        }
×
520

521
        // We are running on a backend that doesn't implement the RPC
522
        // testmempoolaccept, eg, neutrino, so we'll skip the check.
523
        if errors.Is(err, chain.ErrUnimplemented) {
14✔
524
                log.Debug("Skipped testmempoolaccept due to not implemented")
1✔
525
                return tx, fee, nil
1✔
526
        }
1✔
527

528
        return nil, fee, fmt.Errorf("tx=%v failed mempool check: %w",
12✔
529
                tx.TxHash(), err)
12✔
530
}
531

532
// broadcast takes a monitored tx and publishes it to the network. Prior to the
533
// broadcast, it will subscribe the tx's confirmation notification and attach
534
// the event channel to the record. Any broadcast-related errors will not be
535
// returned here, instead, they will be put inside the `BumpResult` and
536
// returned to the caller.
537
func (t *TxPublisher) broadcast(requestID uint64) (*BumpResult, error) {
13✔
538
        // Get the record being monitored.
13✔
539
        record, ok := t.records.Load(requestID)
13✔
540
        if !ok {
14✔
541
                return nil, fmt.Errorf("tx record %v not found", requestID)
1✔
542
        }
1✔
543

544
        txid := record.tx.TxHash()
12✔
545

12✔
546
        tx := record.tx
12✔
547
        log.Debugf("Publishing sweep tx %v, num_inputs=%v, height=%v",
12✔
548
                txid, len(tx.TxIn), t.currentHeight.Load())
12✔
549

12✔
550
        // Set the event, and change it to TxFailed if the wallet fails to
12✔
551
        // publish it.
12✔
552
        event := TxPublished
12✔
553

12✔
554
        // Publish the sweeping tx with customized label. If the publish fails,
12✔
555
        // this error will be saved in the `BumpResult` and it will be removed
12✔
556
        // from being monitored.
12✔
557
        err := t.cfg.Wallet.PublishTransaction(
12✔
558
                tx, labels.MakeLabel(labels.LabelTypeSweepTransaction, nil),
12✔
559
        )
12✔
560
        if err != nil {
16✔
561
                // NOTE: we decide to attach this error to the result instead
4✔
562
                // of returning it here because by the time the tx reaches
4✔
563
                // here, it should have passed the mempool acceptance check. If
4✔
564
                // it still fails to be broadcast, it's likely a non-RBF
4✔
565
                // related error happened. So we send this error back to the
4✔
566
                // caller so that it can handle it properly.
4✔
567
                //
4✔
568
                // TODO(yy): find out which input is causing the failure.
4✔
569
                log.Errorf("Failed to publish tx %v: %v", txid, err)
4✔
570
                event = TxFailed
4✔
571
        }
4✔
572

573
        result := &BumpResult{
12✔
574
                Event:     event,
12✔
575
                Tx:        record.tx,
12✔
576
                Fee:       record.fee,
12✔
577
                FeeRate:   record.feeFunction.FeeRate(),
12✔
578
                Err:       err,
12✔
579
                requestID: requestID,
12✔
580
        }
12✔
581

12✔
582
        return result, nil
12✔
583
}
584

585
// notifyResult sends the result to the resultChan specified by the requestID.
586
// This channel is expected to be read by the caller.
587
func (t *TxPublisher) notifyResult(result *BumpResult) {
13✔
588
        id := result.requestID
13✔
589
        subscriber, ok := t.subscriberChans.Load(id)
13✔
590
        if !ok {
14✔
591
                log.Errorf("Result chan for id=%v not found", id)
1✔
592
                return
1✔
593
        }
1✔
594

595
        log.Debugf("Sending result for requestID=%v, tx=%v", id,
13✔
596
                result.Tx.TxHash())
13✔
597

13✔
598
        select {
13✔
599
        // Send the result to the subscriber.
600
        //
601
        // TODO(yy): Add timeout in case it's blocking?
602
        case subscriber <- result:
12✔
603
        case <-t.quit:
2✔
604
                log.Debug("Fee bumper stopped")
2✔
605
        }
606
}
607

608
// removeResult removes the tracking of the result if the result contains a
609
// non-nil error, or the tx is confirmed, the record will be removed from the
610
// maps.
611
func (t *TxPublisher) removeResult(result *BumpResult) {
13✔
612
        id := result.requestID
13✔
613

13✔
614
        // Remove the record from the maps if there's an error. This means this
13✔
615
        // tx has failed its broadcast and cannot be retried. There are two
13✔
616
        // cases,
13✔
617
        // - when the budget cannot cover the fee.
13✔
618
        // - when a non-RBF related error occurs.
13✔
619
        switch result.Event {
13✔
620
        case TxFailed:
6✔
621
                log.Errorf("Removing monitor record=%v, tx=%v, due to err: %v",
6✔
622
                        id, result.Tx.TxHash(), result.Err)
6✔
623

624
        case TxConfirmed:
7✔
625
                // Remove the record is the tx is confirmed.
7✔
626
                log.Debugf("Removing confirmed monitor record=%v, tx=%v", id,
7✔
627
                        result.Tx.TxHash())
7✔
628

629
        // Do nothing if it's neither failed or confirmed.
630
        default:
8✔
631
                log.Tracef("Skipping record removal for id=%v, event=%v", id,
8✔
632
                        result.Event)
8✔
633

8✔
634
                return
8✔
635
        }
636

637
        t.records.Delete(id)
9✔
638
        t.subscriberChans.Delete(id)
9✔
639
}
640

641
// handleResult handles the result of a tx broadcast. It will notify the
642
// subscriber and remove the record if the tx is confirmed or failed to be
643
// broadcast.
644
func (t *TxPublisher) handleResult(result *BumpResult) {
10✔
645
        // Notify the subscriber.
10✔
646
        t.notifyResult(result)
10✔
647

10✔
648
        // Remove the record if it's failed or confirmed.
10✔
649
        t.removeResult(result)
10✔
650
}
10✔
651

652
// monitorRecord is used to keep track of the tx being monitored by the
653
// publisher internally.
654
type monitorRecord struct {
655
        // tx is the tx being monitored.
656
        tx *wire.MsgTx
657

658
        // req is the original request.
659
        req *BumpRequest
660

661
        // feeFunction is the fee bumping algorithm used by the publisher.
662
        feeFunction FeeFunction
663

664
        // fee is the fee paid by the tx.
665
        fee btcutil.Amount
666
}
667

668
// Start starts the publisher by subscribing to block epoch updates and kicking
669
// off the monitor loop.
670
func (t *TxPublisher) Start() error {
4✔
671
        log.Info("TxPublisher starting...")
4✔
672

4✔
673
        if t.started.Swap(true) {
4✔
674
                return fmt.Errorf("TxPublisher started more than once")
×
UNCOV
675
        }
×
676

677
        blockEvent, err := t.cfg.Notifier.RegisterBlockEpochNtfn(nil)
4✔
678
        if err != nil {
4✔
UNCOV
679
                return fmt.Errorf("register block epoch ntfn: %w", err)
×
UNCOV
680
        }
×
681

682
        t.wg.Add(1)
4✔
683
        go t.monitor(blockEvent)
4✔
684

4✔
685
        log.Debugf("TxPublisher started")
4✔
686

4✔
687
        return nil
4✔
688
}
689

690
// Stop stops the publisher and waits for the monitor loop to exit.
691
func (t *TxPublisher) Stop() error {
4✔
692
        log.Info("TxPublisher stopping...")
4✔
693

4✔
694
        if t.stopped.Swap(true) {
4✔
UNCOV
695
                return fmt.Errorf("TxPublisher stopped more than once")
×
UNCOV
696
        }
×
697

698
        close(t.quit)
4✔
699
        t.wg.Wait()
4✔
700

4✔
701
        log.Debug("TxPublisher stopped")
4✔
702

4✔
703
        return nil
4✔
704
}
705

706
// monitor is the main loop driven by new blocks. Whevenr a new block arrives,
707
// it will examine all the txns being monitored, and check if any of them needs
708
// to be bumped. If so, it will attempt to bump the fee of the tx.
709
//
710
// NOTE: Must be run as a goroutine.
711
func (t *TxPublisher) monitor(blockEvent *chainntnfs.BlockEpochEvent) {
4✔
712
        defer blockEvent.Cancel()
4✔
713
        defer t.wg.Done()
4✔
714

4✔
715
        for {
8✔
716
                select {
4✔
717
                case epoch, ok := <-blockEvent.Epochs:
4✔
718
                        if !ok {
4✔
UNCOV
719
                                // We should stop the publisher before stopping
×
UNCOV
720
                                // the chain service. Otherwise it indicates an
×
UNCOV
721
                                // error.
×
UNCOV
722
                                log.Error("Block epoch channel closed, exit " +
×
UNCOV
723
                                        "monitor")
×
UNCOV
724

×
UNCOV
725
                                return
×
UNCOV
726
                        }
×
727

728
                        log.Debugf("TxPublisher received new block: %v",
4✔
729
                                epoch.Height)
4✔
730

4✔
731
                        // Update the best known height for the publisher.
4✔
732
                        t.currentHeight.Store(epoch.Height)
4✔
733

4✔
734
                        // Check all monitored txns to see if any of them needs
4✔
735
                        // to be bumped.
4✔
736
                        t.processRecords()
4✔
737

738
                case <-t.quit:
4✔
739
                        log.Debug("Fee bumper stopped, exit monitor")
4✔
740
                        return
4✔
741
                }
742
        }
743
}
744

745
// processRecords checks all the txns being monitored, and checks if any of
746
// them needs to be bumped. If so, it will attempt to bump the fee of the tx.
747
func (t *TxPublisher) processRecords() {
5✔
748
        // confirmedRecords stores a map of the records which have been
5✔
749
        // confirmed.
5✔
750
        confirmedRecords := make(map[uint64]*monitorRecord)
5✔
751

5✔
752
        // feeBumpRecords stores a map of the records which need to be bumped.
5✔
753
        feeBumpRecords := make(map[uint64]*monitorRecord)
5✔
754

5✔
755
        // failedRecords stores a map of the records which has inputs being
5✔
756
        // spent by a third party.
5✔
757
        //
5✔
758
        // NOTE: this is only used for neutrino backend.
5✔
759
        failedRecords := make(map[uint64]*monitorRecord)
5✔
760

5✔
761
        // visitor is a helper closure that visits each record and divides them
5✔
762
        // into two groups.
5✔
763
        visitor := func(requestID uint64, r *monitorRecord) error {
11✔
764
                log.Tracef("Checking monitor recordID=%v for tx=%v", requestID,
6✔
765
                        r.tx.TxHash())
6✔
766

6✔
767
                // If the tx is already confirmed, we can stop monitoring it.
6✔
768
                if t.isConfirmed(r.tx.TxHash()) {
11✔
769
                        confirmedRecords[requestID] = r
5✔
770

5✔
771
                        // Move to the next record.
5✔
772
                        return nil
5✔
773
                }
5✔
774

775
                // Check whether the inputs has been spent by a third party.
776
                //
777
                // NOTE: this check is only done for neutrino backend.
778
                if t.isThirdPartySpent(r.tx.TxHash(), r.req.Inputs) {
6✔
779
                        failedRecords[requestID] = r
1✔
780

1✔
781
                        // Move to the next record.
1✔
782
                        return nil
1✔
783
                }
1✔
784

785
                feeBumpRecords[requestID] = r
5✔
786

5✔
787
                // Return nil to move to the next record.
5✔
788
                return nil
5✔
789
        }
790

791
        // Iterate through all the records and divide them into two groups.
792
        t.records.ForEach(visitor)
5✔
793

5✔
794
        // For records that are confirmed, we'll notify the caller about this
5✔
795
        // result.
5✔
796
        for requestID, r := range confirmedRecords {
10✔
797
                rec := r
5✔
798

5✔
799
                log.Debugf("Tx=%v is confirmed", r.tx.TxHash())
5✔
800
                t.wg.Add(1)
5✔
801
                go t.handleTxConfirmed(rec, requestID)
5✔
802
        }
5✔
803

804
        // Get the current height to be used in the following goroutines.
805
        currentHeight := t.currentHeight.Load()
5✔
806

5✔
807
        // For records that are not confirmed, we perform a fee bump if needed.
5✔
808
        for requestID, r := range feeBumpRecords {
10✔
809
                rec := r
5✔
810

5✔
811
                log.Debugf("Attempting to fee bump Tx=%v", r.tx.TxHash())
5✔
812
                t.wg.Add(1)
5✔
813
                go t.handleFeeBumpTx(requestID, rec, currentHeight)
5✔
814
        }
5✔
815

816
        // For records that are failed, we'll notify the caller about this
817
        // result.
818
        for requestID, r := range failedRecords {
6✔
819
                rec := r
1✔
820

1✔
821
                log.Debugf("Tx=%v has inputs been spent by a third party, "+
1✔
822
                        "failing it now", r.tx.TxHash())
1✔
823
                t.wg.Add(1)
1✔
824
                go t.handleThirdPartySpent(rec, requestID)
1✔
825
        }
1✔
826
}
827

828
// handleTxConfirmed is called when a monitored tx is confirmed. It will
829
// notify the subscriber then remove the record from the maps .
830
//
831
// NOTE: Must be run as a goroutine to avoid blocking on sending the result.
832
func (t *TxPublisher) handleTxConfirmed(r *monitorRecord, requestID uint64) {
6✔
833
        defer t.wg.Done()
6✔
834

6✔
835
        // Create a result that will be sent to the resultChan which is
6✔
836
        // listened by the caller.
6✔
837
        result := &BumpResult{
6✔
838
                Event:     TxConfirmed,
6✔
839
                Tx:        r.tx,
6✔
840
                requestID: requestID,
6✔
841
                Fee:       r.fee,
6✔
842
                FeeRate:   r.feeFunction.FeeRate(),
6✔
843
        }
6✔
844

6✔
845
        // Notify that this tx is confirmed and remove the record from the map.
6✔
846
        t.handleResult(result)
6✔
847
}
6✔
848

849
// handleFeeBumpTx checks if the tx needs to be bumped, and if so, it will
850
// attempt to bump the fee of the tx.
851
//
852
// NOTE: Must be run as a goroutine to avoid blocking on sending the result.
853
func (t *TxPublisher) handleFeeBumpTx(requestID uint64, r *monitorRecord,
854
        currentHeight int32) {
8✔
855

8✔
856
        defer t.wg.Done()
8✔
857

8✔
858
        oldTxid := r.tx.TxHash()
8✔
859

8✔
860
        // Get the current conf target for this record.
8✔
861
        confTarget := calcCurrentConfTarget(currentHeight, r.req.DeadlineHeight)
8✔
862

8✔
863
        // Ask the fee function whether a bump is needed. We expect the fee
8✔
864
        // function to increase its returned fee rate after calling this
8✔
865
        // method.
8✔
866
        increased, err := r.feeFunction.IncreaseFeeRate(confTarget)
8✔
867
        if err != nil {
13✔
868
                // TODO(yy): send this error back to the sweeper so it can
5✔
869
                // re-group the inputs?
5✔
870
                log.Errorf("Failed to increase fee rate for tx %v at "+
5✔
871
                        "height=%v: %v", oldTxid, t.currentHeight.Load(), err)
5✔
872

5✔
873
                return
5✔
874
        }
5✔
875

876
        // If the fee rate was not increased, there's no need to bump the fee.
877
        if !increased {
12✔
878
                log.Tracef("Skip bumping tx %v at height=%v", oldTxid,
5✔
879
                        t.currentHeight.Load())
5✔
880

5✔
881
                return
5✔
882
        }
5✔
883

884
        // The fee function now has a new fee rate, we will use it to bump the
885
        // fee of the tx.
886
        resultOpt := t.createAndPublishTx(requestID, r)
6✔
887

6✔
888
        // If there's a result, we will notify the caller about the result.
6✔
889
        resultOpt.WhenSome(func(result BumpResult) {
12✔
890
                // Notify the new result.
6✔
891
                t.handleResult(&result)
6✔
892
        })
6✔
893
}
894

895
// handleThirdPartySpent is called when the inputs in an unconfirmed tx is
896
// spent. It will notify the subscriber then remove the record from the maps
897
// and send a TxFailed event to the subscriber.
898
//
899
// NOTE: Must be run as a goroutine to avoid blocking on sending the result.
900
func (t *TxPublisher) handleThirdPartySpent(r *monitorRecord,
901
        requestID uint64) {
1✔
902

1✔
903
        defer t.wg.Done()
1✔
904

1✔
905
        // Create a result that will be sent to the resultChan which is
1✔
906
        // listened by the caller.
1✔
907
        //
1✔
908
        // TODO(yy): create a new state `TxThirdPartySpent` to notify the
1✔
909
        // sweeper to remove the input, hence moving the monitoring of inputs
1✔
910
        // spent inside the fee bumper.
1✔
911
        result := &BumpResult{
1✔
912
                Event:     TxFailed,
1✔
913
                Tx:        r.tx,
1✔
914
                requestID: requestID,
1✔
915
                Err:       ErrThirdPartySpent,
1✔
916
        }
1✔
917

1✔
918
        // Notify that this tx is confirmed and remove the record from the map.
1✔
919
        t.handleResult(result)
1✔
920
}
1✔
921

922
// createAndPublishTx creates a new tx with a higher fee rate and publishes it
923
// to the network. It will update the record with the new tx and fee rate if
924
// successfully created, and return the result when published successfully.
925
func (t *TxPublisher) createAndPublishTx(requestID uint64,
926
        r *monitorRecord) fn.Option[BumpResult] {
11✔
927

11✔
928
        // Fetch the old tx.
11✔
929
        oldTx := r.tx
11✔
930

11✔
931
        // Create a new tx with the new fee rate.
11✔
932
        //
11✔
933
        // NOTE: The fee function is expected to have increased its returned
11✔
934
        // fee rate after calling the SkipFeeBump method. So we can use it
11✔
935
        // directly here.
11✔
936
        tx, fee, err := t.createAndCheckTx(r.req, r.feeFunction)
11✔
937

11✔
938
        // If the error is fee related, we will return no error and let the fee
11✔
939
        // bumper retry it at next block.
11✔
940
        //
11✔
941
        // NOTE: we can check the RBF error here and ask the fee function to
11✔
942
        // recalculate the fee rate. However, this would defeat the purpose of
11✔
943
        // using a deadline based fee function:
11✔
944
        // - if the deadline is far away, there's no rush to RBF the tx.
11✔
945
        // - if the deadline is close, we expect the fee function to give us a
11✔
946
        //   higher fee rate. If the fee rate cannot satisfy the RBF rules, it
11✔
947
        //   means the budget is not enough.
11✔
948
        if errors.Is(err, chain.ErrInsufficientFee) ||
11✔
949
                errors.Is(err, lnwallet.ErrMempoolFee) {
16✔
950

5✔
951
                log.Debugf("Failed to bump tx %v: %v", oldTx.TxHash(), err)
5✔
952
                return fn.None[BumpResult]()
5✔
953
        }
5✔
954

955
        // If the error is not fee related, we will return a `TxFailed` event
956
        // so this input can be retried.
957
        if err != nil {
13✔
958
                // If the tx doesn't not have enought budget, we will return a
4✔
959
                // result so the sweeper can handle it by re-clustering the
4✔
960
                // utxos.
4✔
961
                if errors.Is(err, ErrNotEnoughBudget) {
5✔
962
                        log.Warnf("Fail to fee bump tx %v: %v", oldTx.TxHash(),
1✔
963
                                err)
1✔
964
                } else {
4✔
965
                        // Otherwise, an unexpected error occurred, we will
3✔
966
                        // fail the tx and let the sweeper retry the whole
3✔
967
                        // process.
3✔
968
                        log.Errorf("Failed to bump tx %v: %v", oldTx.TxHash(),
3✔
969
                                err)
3✔
970
                }
3✔
971

972
                return fn.Some(BumpResult{
4✔
973
                        Event:     TxFailed,
4✔
974
                        Tx:        oldTx,
4✔
975
                        Err:       err,
4✔
976
                        requestID: requestID,
4✔
977
                })
4✔
978
        }
979

980
        // The tx has been created without any errors, we now register a new
981
        // record by overwriting the same requestID.
982
        t.records.Store(requestID, &monitorRecord{
8✔
983
                tx:          tx,
8✔
984
                req:         r.req,
8✔
985
                feeFunction: r.feeFunction,
8✔
986
                fee:         fee,
8✔
987
        })
8✔
988

8✔
989
        // Attempt to broadcast this new tx.
8✔
990
        result, err := t.broadcast(requestID)
8✔
991
        if err != nil {
8✔
UNCOV
992
                log.Infof("Failed to broadcast replacement tx %v: %v",
×
UNCOV
993
                        tx.TxHash(), err)
×
UNCOV
994

×
UNCOV
995
                return fn.None[BumpResult]()
×
UNCOV
996
        }
×
997

998
        // If the result error is fee related, we will return no error and let
999
        // the fee bumper retry it at next block.
1000
        //
1001
        // NOTE: we may get this error if we've bypassed the mempool check,
1002
        // which means we are suing neutrino backend.
1003
        if errors.Is(result.Err, chain.ErrInsufficientFee) ||
8✔
1004
                errors.Is(result.Err, lnwallet.ErrMempoolFee) {
9✔
1005

1✔
1006
                log.Debugf("Failed to bump tx %v: %v", oldTx.TxHash(), err)
1✔
1007
                return fn.None[BumpResult]()
1✔
1008
        }
1✔
1009

1010
        // A successful replacement tx is created, attach the old tx.
1011
        result.ReplacedTx = oldTx
8✔
1012

8✔
1013
        // If the new tx failed to be published, we will return the result so
8✔
1014
        // the caller can handle it.
8✔
1015
        if result.Event == TxFailed {
9✔
1016
                return fn.Some(*result)
1✔
1017
        }
1✔
1018

1019
        log.Infof("Replaced tx=%v with new tx=%v", oldTx.TxHash(), tx.TxHash())
7✔
1020

7✔
1021
        // Otherwise, it's a successful RBF, set the event and return.
7✔
1022
        result.Event = TxReplaced
7✔
1023

7✔
1024
        return fn.Some(*result)
7✔
1025
}
1026

1027
// isConfirmed checks the btcwallet to see whether the tx is confirmed.
1028
func (t *TxPublisher) isConfirmed(txid chainhash.Hash) bool {
6✔
1029
        details, err := t.cfg.Wallet.GetTransactionDetails(&txid)
6✔
1030
        if err != nil {
10✔
1031
                log.Warnf("Failed to get tx details for %v: %v", txid, err)
4✔
1032
                return false
4✔
1033
        }
4✔
1034

1035
        return details.NumConfirmations > 0
6✔
1036
}
1037

1038
// isThirdPartySpent checks whether the inputs of the tx has already been spent
1039
// by a third party. When a tx is not confirmed, yet its inputs has been spent,
1040
// then it must be spent by a different tx other than the sweeping tx here.
1041
//
1042
// NOTE: this check is only performed for neutrino backend as it has no
1043
// reliable way to tell a tx has been replaced.
1044
func (t *TxPublisher) isThirdPartySpent(txid chainhash.Hash,
1045
        inputs []input.Input) bool {
5✔
1046

5✔
1047
        // Skip this check for if this is not neutrino backend.
5✔
1048
        if !t.isNeutrinoBackend() {
9✔
1049
                return false
4✔
1050
        }
4✔
1051

1052
        // Iterate all the inputs and check if they have been spent already.
1053
        for _, inp := range inputs {
2✔
1054
                op := inp.OutPoint()
1✔
1055

1✔
1056
                // For wallet utxos, the height hint is not set - we don't need
1✔
1057
                // to monitor them for third party spend.
1✔
1058
                heightHint := inp.HeightHint()
1✔
1059
                if heightHint == 0 {
2✔
1060
                        log.Debugf("Skipped third party check for wallet "+
1✔
1061
                                "input %v", op)
1✔
1062

1✔
1063
                        continue
1✔
1064
                }
1065

1066
                // If the input has already been spent after the height hint, a
1067
                // spend event is sent back immediately.
1068
                spendEvent, err := t.cfg.Notifier.RegisterSpendNtfn(
1✔
1069
                        &op, inp.SignDesc().Output.PkScript, heightHint,
1✔
1070
                )
1✔
1071
                if err != nil {
1✔
1072
                        log.Criticalf("Failed to register spend ntfn for "+
×
UNCOV
1073
                                "input=%v: %v", op, err)
×
UNCOV
1074
                        return false
×
UNCOV
1075
                }
×
1076

1077
                // Remove the subscription when exit.
1078
                defer spendEvent.Cancel()
1✔
1079

1✔
1080
                // Do a non-blocking read to see if the output has been spent.
1✔
1081
                select {
1✔
1082
                case spend, ok := <-spendEvent.Spend:
1✔
1083
                        if !ok {
1✔
UNCOV
1084
                                log.Debugf("Spend ntfn for %v canceled", op)
×
UNCOV
1085
                                return false
×
UNCOV
1086
                        }
×
1087

1088
                        spendingTxID := spend.SpendingTx.TxHash()
1✔
1089

1✔
1090
                        // If the spending tx is the same as the sweeping tx
1✔
1091
                        // then we are good.
1✔
1092
                        if spendingTxID == txid {
1✔
UNCOV
1093
                                continue
×
1094
                        }
1095

1096
                        log.Warnf("Detected third party spent of output=%v "+
1✔
1097
                                "in tx=%v", op, spend.SpendingTx.TxHash())
1✔
1098

1✔
1099
                        return true
1✔
1100

1101
                // Move to the next input.
1102
                default:
1✔
1103
                }
1104
        }
1105

1106
        return false
1✔
1107
}
1108

1109
// calcCurrentConfTarget calculates the current confirmation target based on
1110
// the deadline height. The conf target is capped at 0 if the deadline has
1111
// already been past.
1112
func calcCurrentConfTarget(currentHeight, deadline int32) uint32 {
15✔
1113
        var confTarget uint32
15✔
1114

15✔
1115
        // Calculate how many blocks left until the deadline.
15✔
1116
        deadlineDelta := deadline - currentHeight
15✔
1117

15✔
1118
        // If we are already past the deadline, we will set the conf target to
15✔
1119
        // be 1.
15✔
1120
        if deadlineDelta < 0 {
23✔
1121
                log.Warnf("Deadline is %d blocks behind current height %v",
8✔
1122
                        -deadlineDelta, currentHeight)
8✔
1123

8✔
1124
                confTarget = 0
8✔
1125
        } else {
19✔
1126
                confTarget = uint32(deadlineDelta)
11✔
1127
        }
11✔
1128

1129
        return confTarget
15✔
1130
}
1131

1132
// createSweepTx creates a sweeping tx based on the given inputs, change
1133
// address and fee rate.
1134
func (t *TxPublisher) createSweepTx(inputs []input.Input, changePkScript []byte,
1135
        feeRate chainfee.SatPerKWeight) (*wire.MsgTx, btcutil.Amount, error) {
26✔
1136

26✔
1137
        // Validate and calculate the fee and change amount.
26✔
1138
        txFee, changeAmtOpt, locktimeOpt, err := prepareSweepTx(
26✔
1139
                inputs, changePkScript, feeRate, t.currentHeight.Load(),
26✔
1140
        )
26✔
1141
        if err != nil {
30✔
1142
                return nil, 0, err
4✔
1143
        }
4✔
1144

1145
        var (
26✔
1146
                // Create the sweep transaction that we will be building. We
26✔
1147
                // use version 2 as it is required for CSV.
26✔
1148
                sweepTx = wire.NewMsgTx(2)
26✔
1149

26✔
1150
                // We'll add the inputs as we go so we know the final ordering
26✔
1151
                // of inputs to sign.
26✔
1152
                idxs []input.Input
26✔
1153
        )
26✔
1154

26✔
1155
        // We start by adding all inputs that commit to an output. We do this
26✔
1156
        // since the input and output index must stay the same for the
26✔
1157
        // signatures to be valid.
26✔
1158
        for _, o := range inputs {
52✔
1159
                if o.RequiredTxOut() == nil {
52✔
1160
                        continue
26✔
1161
                }
1162

1163
                idxs = append(idxs, o)
4✔
1164
                sweepTx.AddTxIn(&wire.TxIn{
4✔
1165
                        PreviousOutPoint: o.OutPoint(),
4✔
1166
                        Sequence:         o.BlocksToMaturity(),
4✔
1167
                })
4✔
1168
                sweepTx.AddTxOut(o.RequiredTxOut())
4✔
1169
        }
1170

1171
        // Sum up the value contained in the remaining inputs, and add them to
1172
        // the sweep transaction.
1173
        for _, o := range inputs {
52✔
1174
                if o.RequiredTxOut() != nil {
30✔
1175
                        continue
4✔
1176
                }
1177

1178
                idxs = append(idxs, o)
26✔
1179
                sweepTx.AddTxIn(&wire.TxIn{
26✔
1180
                        PreviousOutPoint: o.OutPoint(),
26✔
1181
                        Sequence:         o.BlocksToMaturity(),
26✔
1182
                })
26✔
1183
        }
1184

1185
        // If there's a change amount, add it to the transaction.
1186
        changeAmtOpt.WhenSome(func(changeAmt btcutil.Amount) {
52✔
1187
                sweepTx.AddTxOut(&wire.TxOut{
26✔
1188
                        PkScript: changePkScript,
26✔
1189
                        Value:    int64(changeAmt),
26✔
1190
                })
26✔
1191
        })
26✔
1192

1193
        // We'll default to using the current block height as locktime, if none
1194
        // of the inputs commits to a different locktime.
1195
        sweepTx.LockTime = uint32(locktimeOpt.UnwrapOr(t.currentHeight.Load()))
26✔
1196

26✔
1197
        prevInputFetcher, err := input.MultiPrevOutFetcher(inputs)
26✔
1198
        if err != nil {
26✔
UNCOV
1199
                return nil, 0, fmt.Errorf("error creating prev input fetcher "+
×
UNCOV
1200
                        "for hash cache: %v", err)
×
UNCOV
1201
        }
×
1202
        hashCache := txscript.NewTxSigHashes(sweepTx, prevInputFetcher)
26✔
1203

26✔
1204
        // With all the inputs in place, use each output's unique input script
26✔
1205
        // function to generate the final witness required for spending.
26✔
1206
        addInputScript := func(idx int, tso input.Input) error {
52✔
1207
                inputScript, err := tso.CraftInputScript(
26✔
1208
                        t.cfg.Signer, sweepTx, hashCache, prevInputFetcher, idx,
26✔
1209
                )
26✔
1210
                if err != nil {
26✔
UNCOV
1211
                        return err
×
UNCOV
1212
                }
×
1213

1214
                sweepTx.TxIn[idx].Witness = inputScript.Witness
26✔
1215

26✔
1216
                if len(inputScript.SigScript) == 0 {
52✔
1217
                        return nil
26✔
1218
                }
26✔
1219

UNCOV
1220
                sweepTx.TxIn[idx].SignatureScript = inputScript.SigScript
×
UNCOV
1221

×
UNCOV
1222
                return nil
×
1223
        }
1224

1225
        for idx, inp := range idxs {
52✔
1226
                if err := addInputScript(idx, inp); err != nil {
26✔
UNCOV
1227
                        return nil, 0, err
×
UNCOV
1228
                }
×
1229
        }
1230

1231
        log.Debugf("Created sweep tx %v for inputs:\n%v", sweepTx.TxHash(),
26✔
1232
                inputTypeSummary(inputs))
26✔
1233

26✔
1234
        return sweepTx, txFee, nil
26✔
1235
}
1236

1237
// prepareSweepTx returns the tx fee, an optional change amount and an optional
1238
// locktime after a series of validations:
1239
// 1. check the locktime has been reached.
1240
// 2. check the locktimes are the same.
1241
// 3. check the inputs cover the outputs.
1242
//
1243
// NOTE: if the change amount is below dust, it will be added to the tx fee.
1244
func prepareSweepTx(inputs []input.Input, changePkScript []byte,
1245
        feeRate chainfee.SatPerKWeight, currentHeight int32) (
1246
        btcutil.Amount, fn.Option[btcutil.Amount], fn.Option[int32], error) {
26✔
1247

26✔
1248
        noChange := fn.None[btcutil.Amount]()
26✔
1249
        noLocktime := fn.None[int32]()
26✔
1250

26✔
1251
        // Creating a weight estimator with nil outputs and zero max fee rate.
26✔
1252
        // We don't allow adding customized outputs in the sweeping tx, and the
26✔
1253
        // fee rate is already being managed before we get here.
26✔
1254
        inputs, estimator, err := getWeightEstimate(
26✔
1255
                inputs, nil, feeRate, 0, changePkScript,
26✔
1256
        )
26✔
1257
        if err != nil {
26✔
UNCOV
1258
                return 0, noChange, noLocktime, err
×
UNCOV
1259
        }
×
1260

1261
        txFee := estimator.fee()
26✔
1262

26✔
1263
        var (
26✔
1264
                // Track whether any of the inputs require a certain locktime.
26✔
1265
                locktime = int32(-1)
26✔
1266

26✔
1267
                // We keep track of total input amount, and required output
26✔
1268
                // amount to use for calculating the change amount below.
26✔
1269
                totalInput     btcutil.Amount
26✔
1270
                requiredOutput btcutil.Amount
26✔
1271
        )
26✔
1272

26✔
1273
        // Go through each input and check if the required lock times have
26✔
1274
        // reached and are the same.
26✔
1275
        for _, o := range inputs {
52✔
1276
                // If the input has a required output, we'll add it to the
26✔
1277
                // required output amount.
26✔
1278
                if o.RequiredTxOut() != nil {
30✔
1279
                        requiredOutput += btcutil.Amount(
4✔
1280
                                o.RequiredTxOut().Value,
4✔
1281
                        )
4✔
1282
                }
4✔
1283

1284
                // Update the total input amount.
1285
                totalInput += btcutil.Amount(o.SignDesc().Output.Value)
26✔
1286

26✔
1287
                lt, ok := o.RequiredLockTime()
26✔
1288

26✔
1289
                // Skip if the input doesn't require a lock time.
26✔
1290
                if !ok {
52✔
1291
                        continue
26✔
1292
                }
1293

1294
                // Check if the lock time has reached
1295
                if lt > uint32(currentHeight) {
4✔
UNCOV
1296
                        return 0, noChange, noLocktime, ErrLocktimeImmature
×
1297
                }
×
1298

1299
                // If another input commits to a different locktime, they
1300
                // cannot be combined in the same transaction.
1301
                if locktime != -1 && locktime != int32(lt) {
4✔
UNCOV
1302
                        return 0, noChange, noLocktime, ErrLocktimeConflict
×
UNCOV
1303
                }
×
1304

1305
                // Update the locktime for next iteration.
1306
                locktime = int32(lt)
4✔
1307
        }
1308

1309
        // Make sure total output amount is less than total input amount.
1310
        if requiredOutput+txFee > totalInput {
26✔
UNCOV
1311
                return 0, noChange, noLocktime, fmt.Errorf("insufficient "+
×
UNCOV
1312
                        "input to create sweep tx: input_sum=%v, "+
×
UNCOV
1313
                        "output_sum=%v", totalInput, requiredOutput+txFee)
×
UNCOV
1314
        }
×
1315

1316
        // The value remaining after the required output and fees is the
1317
        // change output.
1318
        changeAmt := totalInput - requiredOutput - txFee
26✔
1319
        changeAmtOpt := fn.Some(changeAmt)
26✔
1320

26✔
1321
        // We'll calculate the dust limit for the given changePkScript since it
26✔
1322
        // is variable.
26✔
1323
        changeFloor := lnwallet.DustLimitForSize(len(changePkScript))
26✔
1324

26✔
1325
        // If the change amount is dust, we'll move it into the fees.
26✔
1326
        if changeAmt < changeFloor {
30✔
1327
                log.Infof("Change amt %v below dustlimit %v, not adding "+
4✔
1328
                        "change output", changeAmt, changeFloor)
4✔
1329

4✔
1330
                // If there's no required output, and the change output is a
4✔
1331
                // dust, it means we are creating a tx without any outputs. In
4✔
1332
                // this case we'll return an error. This could happen when
4✔
1333
                // creating a tx that has an anchor as the only input.
4✔
1334
                if requiredOutput == 0 {
8✔
1335
                        return 0, noChange, noLocktime, ErrTxNoOutput
4✔
1336
                }
4✔
1337

1338
                // The dust amount is added to the fee.
UNCOV
1339
                txFee += changeAmt
×
UNCOV
1340

×
UNCOV
1341
                // Set the change amount to none.
×
UNCOV
1342
                changeAmtOpt = fn.None[btcutil.Amount]()
×
1343
        }
1344

1345
        // Optionally set the locktime.
1346
        locktimeOpt := fn.Some(locktime)
26✔
1347
        if locktime == -1 {
52✔
1348
                locktimeOpt = noLocktime
26✔
1349
        }
26✔
1350

1351
        log.Debugf("Creating sweep tx for %v inputs (%s) using %v, "+
26✔
1352
                "tx_weight=%v, tx_fee=%v, locktime=%v, parents_count=%v, "+
26✔
1353
                "parents_fee=%v, parents_weight=%v, current_height=%v",
26✔
1354
                len(inputs), inputTypeSummary(inputs), feeRate,
26✔
1355
                estimator.weight(), txFee, locktimeOpt, len(estimator.parents),
26✔
1356
                estimator.parentsFee, estimator.parentsWeight, currentHeight)
26✔
1357

26✔
1358
        return txFee, changeAmtOpt, locktimeOpt, nil
26✔
1359
}
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