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

lightningnetwork / lnd / 9111774206

pending completion
9111774206

Pull #8765

github

hieblmi
routing: log edge when skipping it
Pull Request #8765: routing: log edge when skipping it

1 of 1 new or added line in 1 file covered. (100.0%)

104 existing lines in 27 files now uncovered.

122984 of 210570 relevant lines covered (58.41%)

28065.14 hits per line

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

93.12
/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/davecgh/go-spew/spew"
16
        "github.com/lightningnetwork/lnd/chainntnfs"
17
        "github.com/lightningnetwork/lnd/fn"
18
        "github.com/lightningnetwork/lnd/input"
19
        "github.com/lightningnetwork/lnd/labels"
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) (uint64, 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 uint64(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
        wg sync.WaitGroup
265

266
        // cfg specifies the configuration of the TxPublisher.
267
        cfg *TxPublisherConfig
268

269
        // currentHeight is the current block height.
270
        currentHeight atomic.Int32
271

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

276
        // requestCounter is a monotonically increasing counter used to keep
277
        // track of how many requests have been made.
278
        requestCounter atomic.Uint64
279

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

284
        // quit is used to signal the publisher to stop.
285
        quit chan struct{}
286
}
287

288
// Compile-time constraint to ensure TxPublisher implements Bumper.
289
var _ Bumper = (*TxPublisher)(nil)
290

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

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

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

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

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

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

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

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

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

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

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

361
        return result, nil
6✔
362
}
363

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

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

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

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

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

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

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

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

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

10✔
415
                        return requestID, nil
10✔
416

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

2✔
426
                        fallthrough
2✔
427

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

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

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

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

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

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

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

18✔
479
        return requestID
18✔
480
}
18✔
481

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

8✔
633
                return
8✔
634
        }
635

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

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

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

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

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

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

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

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

4✔
673
        blockEvent, err := t.cfg.Notifier.RegisterBlockEpochNtfn(nil)
4✔
674
        if err != nil {
4✔
675
                return fmt.Errorf("register block epoch ntfn: %w", err)
×
676
        }
×
677

678
        t.wg.Add(1)
4✔
679
        go t.monitor(blockEvent)
4✔
680

4✔
681
        return nil
4✔
682
}
683

684
// Stop stops the publisher and waits for the monitor loop to exit.
685
func (t *TxPublisher) Stop() {
4✔
686
        log.Info("TxPublisher stopping...")
4✔
687
        defer log.Debugf("TxPublisher stopped")
4✔
688

4✔
689
        close(t.quit)
4✔
690

4✔
691
        t.wg.Wait()
4✔
692
}
4✔
693

694
// monitor is the main loop driven by new blocks. Whevenr a new block arrives,
695
// it will examine all the txns being monitored, and check if any of them needs
696
// to be bumped. If so, it will attempt to bump the fee of the tx.
697
//
698
// NOTE: Must be run as a goroutine.
699
func (t *TxPublisher) monitor(blockEvent *chainntnfs.BlockEpochEvent) {
4✔
700
        defer blockEvent.Cancel()
4✔
701
        defer t.wg.Done()
4✔
702

4✔
703
        for {
8✔
704
                select {
4✔
705
                case epoch, ok := <-blockEvent.Epochs:
4✔
706
                        if !ok {
4✔
707
                                // We should stop the publisher before stopping
×
708
                                // the chain service. Otherwise it indicates an
×
709
                                // error.
×
710
                                log.Error("Block epoch channel closed, exit " +
×
711
                                        "monitor")
×
712

×
713
                                return
×
714
                        }
×
715

716
                        log.Debugf("TxPublisher received new block: %v",
4✔
717
                                epoch.Height)
4✔
718

4✔
719
                        // Update the best known height for the publisher.
4✔
720
                        t.currentHeight.Store(epoch.Height)
4✔
721

4✔
722
                        // Check all monitored txns to see if any of them needs
4✔
723
                        // to be bumped.
4✔
724
                        t.processRecords()
4✔
725

726
                case <-t.quit:
4✔
727
                        log.Debug("Fee bumper stopped, exit monitor")
4✔
728
                        return
4✔
729
                }
730
        }
731
}
732

733
// processRecords checks all the txns being monitored, and checks if any of
734
// them needs to be bumped. If so, it will attempt to bump the fee of the tx.
735
func (t *TxPublisher) processRecords() {
5✔
736
        // confirmedRecords stores a map of the records which have been
5✔
737
        // confirmed.
5✔
738
        confirmedRecords := make(map[uint64]*monitorRecord)
5✔
739

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

5✔
743
        // failedRecords stores a map of the records which has inputs being
5✔
744
        // spent by a third party.
5✔
745
        //
5✔
746
        // NOTE: this is only used for neutrino backend.
5✔
747
        failedRecords := make(map[uint64]*monitorRecord)
5✔
748

5✔
749
        // visitor is a helper closure that visits each record and divides them
5✔
750
        // into two groups.
5✔
751
        visitor := func(requestID uint64, r *monitorRecord) error {
11✔
752
                log.Tracef("Checking monitor recordID=%v for tx=%v", requestID,
6✔
753
                        r.tx.TxHash())
6✔
754

6✔
755
                // If the tx is already confirmed, we can stop monitoring it.
6✔
756
                if t.isConfirmed(r.tx.TxHash()) {
11✔
757
                        confirmedRecords[requestID] = r
5✔
758

5✔
759
                        // Move to the next record.
5✔
760
                        return nil
5✔
761
                }
5✔
762

763
                // Check whether the inputs has been spent by a third party.
764
                //
765
                // NOTE: this check is only done for neutrino backend.
766
                if t.isThirdPartySpent(r.tx.TxHash(), r.req.Inputs) {
6✔
767
                        failedRecords[requestID] = r
1✔
768

1✔
769
                        // Move to the next record.
1✔
770
                        return nil
1✔
771
                }
1✔
772

773
                feeBumpRecords[requestID] = r
5✔
774

5✔
775
                // Return nil to move to the next record.
5✔
776
                return nil
5✔
777
        }
778

779
        // Iterate through all the records and divide them into two groups.
780
        t.records.ForEach(visitor)
5✔
781

5✔
782
        // For records that are confirmed, we'll notify the caller about this
5✔
783
        // result.
5✔
784
        for requestID, r := range confirmedRecords {
10✔
785
                rec := r
5✔
786

5✔
787
                log.Debugf("Tx=%v is confirmed", r.tx.TxHash())
5✔
788
                t.wg.Add(1)
5✔
789
                go t.handleTxConfirmed(rec, requestID)
5✔
790
        }
5✔
791

792
        // Get the current height to be used in the following goroutines.
793
        currentHeight := t.currentHeight.Load()
5✔
794

5✔
795
        // For records that are not confirmed, we perform a fee bump if needed.
5✔
796
        for requestID, r := range feeBumpRecords {
10✔
797
                rec := r
5✔
798

5✔
799
                log.Debugf("Attempting to fee bump Tx=%v", r.tx.TxHash())
5✔
800
                t.wg.Add(1)
5✔
801
                go t.handleFeeBumpTx(requestID, rec, currentHeight)
5✔
802
        }
5✔
803

804
        // For records that are failed, we'll notify the caller about this
805
        // result.
806
        for requestID, r := range failedRecords {
6✔
807
                rec := r
1✔
808

1✔
809
                log.Debugf("Tx=%v has inputs been spent by a third party, "+
1✔
810
                        "failing it now", r.tx.TxHash())
1✔
811
                t.wg.Add(1)
1✔
812
                go t.handleThirdPartySpent(rec, requestID)
1✔
813
        }
1✔
814
}
815

816
// handleTxConfirmed is called when a monitored tx is confirmed. It will
817
// notify the subscriber then remove the record from the maps .
818
//
819
// NOTE: Must be run as a goroutine to avoid blocking on sending the result.
820
func (t *TxPublisher) handleTxConfirmed(r *monitorRecord, requestID uint64) {
6✔
821
        defer t.wg.Done()
6✔
822

6✔
823
        // Create a result that will be sent to the resultChan which is
6✔
824
        // listened by the caller.
6✔
825
        result := &BumpResult{
6✔
826
                Event:     TxConfirmed,
6✔
827
                Tx:        r.tx,
6✔
828
                requestID: requestID,
6✔
829
                Fee:       r.fee,
6✔
830
                FeeRate:   r.feeFunction.FeeRate(),
6✔
831
        }
6✔
832

6✔
833
        // Notify that this tx is confirmed and remove the record from the map.
6✔
834
        t.handleResult(result)
6✔
835
}
6✔
836

837
// handleFeeBumpTx checks if the tx needs to be bumped, and if so, it will
838
// attempt to bump the fee of the tx.
839
//
840
// NOTE: Must be run as a goroutine to avoid blocking on sending the result.
841
func (t *TxPublisher) handleFeeBumpTx(requestID uint64, r *monitorRecord,
842
        currentHeight int32) {
8✔
843

8✔
844
        defer t.wg.Done()
8✔
845

8✔
846
        oldTxid := r.tx.TxHash()
8✔
847

8✔
848
        // Get the current conf target for this record.
8✔
849
        confTarget := calcCurrentConfTarget(currentHeight, r.req.DeadlineHeight)
8✔
850

8✔
851
        // Ask the fee function whether a bump is needed. We expect the fee
8✔
852
        // function to increase its returned fee rate after calling this
8✔
853
        // method.
8✔
854
        increased, err := r.feeFunction.IncreaseFeeRate(confTarget)
8✔
855
        if err != nil {
9✔
856
                // TODO(yy): send this error back to the sweeper so it can
1✔
857
                // re-group the inputs?
1✔
858
                log.Errorf("Failed to increase fee rate for tx %v at "+
1✔
859
                        "height=%v: %v", oldTxid, t.currentHeight.Load(), err)
1✔
860

1✔
861
                return
1✔
862
        }
1✔
863

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

5✔
869
                return
5✔
870
        }
5✔
871

872
        // The fee function now has a new fee rate, we will use it to bump the
873
        // fee of the tx.
874
        resultOpt := t.createAndPublishTx(requestID, r)
6✔
875

6✔
876
        // If there's a result, we will notify the caller about the result.
6✔
877
        resultOpt.WhenSome(func(result BumpResult) {
12✔
878
                // Notify the new result.
6✔
879
                t.handleResult(&result)
6✔
880
        })
6✔
881
}
882

883
// handleThirdPartySpent is called when the inputs in an unconfirmed tx is
884
// spent. It will notify the subscriber then remove the record from the maps
885
// and send a TxFailed event to the subscriber.
886
//
887
// NOTE: Must be run as a goroutine to avoid blocking on sending the result.
888
func (t *TxPublisher) handleThirdPartySpent(r *monitorRecord,
889
        requestID uint64) {
1✔
890

1✔
891
        defer t.wg.Done()
1✔
892

1✔
893
        // Create a result that will be sent to the resultChan which is
1✔
894
        // listened by the caller.
1✔
895
        //
1✔
896
        // TODO(yy): create a new state `TxThirdPartySpent` to notify the
1✔
897
        // sweeper to remove the input, hence moving the monitoring of inputs
1✔
898
        // spent inside the fee bumper.
1✔
899
        result := &BumpResult{
1✔
900
                Event:     TxFailed,
1✔
901
                Tx:        r.tx,
1✔
902
                requestID: requestID,
1✔
903
                Err:       ErrThirdPartySpent,
1✔
904
        }
1✔
905

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

910
// createAndPublishTx creates a new tx with a higher fee rate and publishes it
911
// to the network. It will update the record with the new tx and fee rate if
912
// successfully created, and return the result when published successfully.
913
func (t *TxPublisher) createAndPublishTx(requestID uint64,
914
        r *monitorRecord) fn.Option[BumpResult] {
11✔
915

11✔
916
        // Fetch the old tx.
11✔
917
        oldTx := r.tx
11✔
918

11✔
919
        // Create a new tx with the new fee rate.
11✔
920
        //
11✔
921
        // NOTE: The fee function is expected to have increased its returned
11✔
922
        // fee rate after calling the SkipFeeBump method. So we can use it
11✔
923
        // directly here.
11✔
924
        tx, fee, err := t.createAndCheckTx(r.req, r.feeFunction)
11✔
925

11✔
926
        // If the error is fee related, we will return no error and let the fee
11✔
927
        // bumper retry it at next block.
11✔
928
        //
11✔
929
        // NOTE: we can check the RBF error here and ask the fee function to
11✔
930
        // recalculate the fee rate. However, this would defeat the purpose of
11✔
931
        // using a deadline based fee function:
11✔
932
        // - if the deadline is far away, there's no rush to RBF the tx.
11✔
933
        // - if the deadline is close, we expect the fee function to give us a
11✔
934
        //   higher fee rate. If the fee rate cannot satisfy the RBF rules, it
11✔
935
        //   means the budget is not enough.
11✔
936
        if errors.Is(err, rpcclient.ErrInsufficientFee) ||
11✔
937
                errors.Is(err, lnwallet.ErrMempoolFee) {
16✔
938

5✔
939
                log.Debugf("Failed to bump tx %v: %v", oldTx.TxHash(), err)
5✔
940
                return fn.None[BumpResult]()
5✔
941
        }
5✔
942

943
        // If the error is not fee related, we will return a `TxFailed` event
944
        // so this input can be retried.
945
        if err != nil {
13✔
946
                // If the tx doesn't not have enought budget, we will return a
4✔
947
                // result so the sweeper can handle it by re-clustering the
4✔
948
                // utxos.
4✔
949
                if errors.Is(err, ErrNotEnoughBudget) {
5✔
950
                        log.Warnf("Fail to fee bump tx %v: %v", oldTx.TxHash(),
1✔
951
                                err)
1✔
952
                } else {
4✔
953
                        // Otherwise, an unexpected error occurred, we will
3✔
954
                        // fail the tx and let the sweeper retry the whole
3✔
955
                        // process.
3✔
956
                        log.Errorf("Failed to bump tx %v: %v", oldTx.TxHash(),
3✔
957
                                err)
3✔
958
                }
3✔
959

960
                return fn.Some(BumpResult{
4✔
961
                        Event:     TxFailed,
4✔
962
                        Tx:        oldTx,
4✔
963
                        Err:       err,
4✔
964
                        requestID: requestID,
4✔
965
                })
4✔
966
        }
967

968
        // The tx has been created without any errors, we now register a new
969
        // record by overwriting the same requestID.
970
        t.records.Store(requestID, &monitorRecord{
8✔
971
                tx:          tx,
8✔
972
                req:         r.req,
8✔
973
                feeFunction: r.feeFunction,
8✔
974
                fee:         fee,
8✔
975
        })
8✔
976

8✔
977
        // Attempt to broadcast this new tx.
8✔
978
        result, err := t.broadcast(requestID)
8✔
979
        if err != nil {
8✔
980
                log.Infof("Failed to broadcast replacement tx %v: %v",
×
981
                        tx.TxHash(), err)
×
982

×
983
                return fn.None[BumpResult]()
×
984
        }
×
985

986
        // If the result error is fee related, we will return no error and let
987
        // the fee bumper retry it at next block.
988
        //
989
        // NOTE: we may get this error if we've bypassed the mempool check,
990
        // which means we are suing neutrino backend.
991
        if errors.Is(result.Err, rpcclient.ErrInsufficientFee) ||
8✔
992
                errors.Is(result.Err, lnwallet.ErrMempoolFee) {
9✔
993

1✔
994
                log.Debugf("Failed to bump tx %v: %v", oldTx.TxHash(), err)
1✔
995
                return fn.None[BumpResult]()
1✔
996
        }
1✔
997

998
        // A successful replacement tx is created, attach the old tx.
999
        result.ReplacedTx = oldTx
8✔
1000

8✔
1001
        // If the new tx failed to be published, we will return the result so
8✔
1002
        // the caller can handle it.
8✔
1003
        if result.Event == TxFailed {
9✔
1004
                return fn.Some(*result)
1✔
1005
        }
1✔
1006

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

7✔
1009
        // Otherwise, it's a successful RBF, set the event and return.
7✔
1010
        result.Event = TxReplaced
7✔
1011

7✔
1012
        return fn.Some(*result)
7✔
1013
}
1014

1015
// isConfirmed checks the btcwallet to see whether the tx is confirmed.
1016
func (t *TxPublisher) isConfirmed(txid chainhash.Hash) bool {
6✔
1017
        details, err := t.cfg.Wallet.GetTransactionDetails(&txid)
6✔
1018
        if err != nil {
10✔
1019
                log.Warnf("Failed to get tx details for %v: %v", txid, err)
4✔
1020
                return false
4✔
1021
        }
4✔
1022

1023
        return details.NumConfirmations > 0
6✔
1024
}
1025

1026
// isThirdPartySpent checks whether the inputs of the tx has already been spent
1027
// by a third party. When a tx is not confirmed, yet its inputs has been spent,
1028
// then it must be spent by a different tx other than the sweeping tx here.
1029
//
1030
// NOTE: this check is only performed for neutrino backend as it has no
1031
// reliable way to tell a tx has been replaced.
1032
func (t *TxPublisher) isThirdPartySpent(txid chainhash.Hash,
1033
        inputs []input.Input) bool {
5✔
1034

5✔
1035
        // Skip this check for if this is not neutrino backend.
5✔
1036
        if !t.isNeutrinoBackend() {
9✔
1037
                return false
4✔
1038
        }
4✔
1039

1040
        // Iterate all the inputs and check if they have been spent already.
1041
        for _, inp := range inputs {
2✔
1042
                op := inp.OutPoint()
1✔
1043

1✔
1044
                // For wallet utxos, the height hint is not set - we don't need
1✔
1045
                // to monitor them for third party spend.
1✔
1046
                heightHint := inp.HeightHint()
1✔
1047
                if heightHint == 0 {
2✔
1048
                        log.Debugf("Skipped third party check for wallet "+
1✔
1049
                                "input %v", op)
1✔
1050

1✔
1051
                        continue
1✔
1052
                }
1053

1054
                // If the input has already been spent after the height hint, a
1055
                // spend event is sent back immediately.
1056
                spendEvent, err := t.cfg.Notifier.RegisterSpendNtfn(
1✔
1057
                        &op, inp.SignDesc().Output.PkScript, heightHint,
1✔
1058
                )
1✔
1059
                if err != nil {
1✔
1060
                        log.Criticalf("Failed to register spend ntfn for "+
×
1061
                                "input=%v: %v", op, err)
×
1062
                        return false
×
1063
                }
×
1064

1065
                // Remove the subscription when exit.
1066
                defer spendEvent.Cancel()
1✔
1067

1✔
1068
                // Do a non-blocking read to see if the output has been spent.
1✔
1069
                select {
1✔
1070
                case spend, ok := <-spendEvent.Spend:
1✔
1071
                        if !ok {
1✔
1072
                                log.Debugf("Spend ntfn for %v canceled", op)
×
1073
                                return false
×
1074
                        }
×
1075

1076
                        spendingTxID := spend.SpendingTx.TxHash()
1✔
1077

1✔
1078
                        // If the spending tx is the same as the sweeping tx
1✔
1079
                        // then we are good.
1✔
1080
                        if spendingTxID == txid {
1✔
UNCOV
1081
                                continue
×
1082
                        }
1083

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

1✔
1087
                        return true
1✔
1088

1089
                // Move to the next input.
1090
                default:
1✔
1091
                }
1092
        }
1093

1094
        return false
1✔
1095
}
1096

1097
// calcCurrentConfTarget calculates the current confirmation target based on
1098
// the deadline height. The conf target is capped at 0 if the deadline has
1099
// already been past.
1100
func calcCurrentConfTarget(currentHeight, deadline int32) uint32 {
15✔
1101
        var confTarget uint32
15✔
1102

15✔
1103
        // Calculate how many blocks left until the deadline.
15✔
1104
        deadlineDelta := deadline - currentHeight
15✔
1105

15✔
1106
        // If we are already past the deadline, we will set the conf target to
15✔
1107
        // be 1.
15✔
1108
        if deadlineDelta < 0 {
23✔
1109
                log.Warnf("Deadline is %d blocks behind current height %v",
8✔
1110
                        -deadlineDelta, currentHeight)
8✔
1111

8✔
1112
                confTarget = 0
8✔
1113
        } else {
19✔
1114
                confTarget = uint32(deadlineDelta)
11✔
1115
        }
11✔
1116

1117
        return confTarget
15✔
1118
}
1119

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

26✔
1125
        // Validate and calculate the fee and change amount.
26✔
1126
        txFee, changeAmtOpt, locktimeOpt, err := prepareSweepTx(
26✔
1127
                inputs, changePkScript, feeRate, t.currentHeight.Load(),
26✔
1128
        )
26✔
1129
        if err != nil {
30✔
1130
                return nil, 0, err
4✔
1131
        }
4✔
1132

1133
        var (
26✔
1134
                // Create the sweep transaction that we will be building. We
26✔
1135
                // use version 2 as it is required for CSV.
26✔
1136
                sweepTx = wire.NewMsgTx(2)
26✔
1137

26✔
1138
                // We'll add the inputs as we go so we know the final ordering
26✔
1139
                // of inputs to sign.
26✔
1140
                idxs []input.Input
26✔
1141
        )
26✔
1142

26✔
1143
        // We start by adding all inputs that commit to an output. We do this
26✔
1144
        // since the input and output index must stay the same for the
26✔
1145
        // signatures to be valid.
26✔
1146
        for _, o := range inputs {
52✔
1147
                if o.RequiredTxOut() == nil {
52✔
1148
                        continue
26✔
1149
                }
1150

1151
                idxs = append(idxs, o)
4✔
1152
                sweepTx.AddTxIn(&wire.TxIn{
4✔
1153
                        PreviousOutPoint: o.OutPoint(),
4✔
1154
                        Sequence:         o.BlocksToMaturity(),
4✔
1155
                })
4✔
1156
                sweepTx.AddTxOut(o.RequiredTxOut())
4✔
1157
        }
1158

1159
        // Sum up the value contained in the remaining inputs, and add them to
1160
        // the sweep transaction.
1161
        for _, o := range inputs {
52✔
1162
                if o.RequiredTxOut() != nil {
30✔
1163
                        continue
4✔
1164
                }
1165

1166
                idxs = append(idxs, o)
26✔
1167
                sweepTx.AddTxIn(&wire.TxIn{
26✔
1168
                        PreviousOutPoint: o.OutPoint(),
26✔
1169
                        Sequence:         o.BlocksToMaturity(),
26✔
1170
                })
26✔
1171
        }
1172

1173
        // If there's a change amount, add it to the transaction.
1174
        changeAmtOpt.WhenSome(func(changeAmt btcutil.Amount) {
52✔
1175
                sweepTx.AddTxOut(&wire.TxOut{
26✔
1176
                        PkScript: changePkScript,
26✔
1177
                        Value:    int64(changeAmt),
26✔
1178
                })
26✔
1179
        })
26✔
1180

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

26✔
1185
        prevInputFetcher, err := input.MultiPrevOutFetcher(inputs)
26✔
1186
        if err != nil {
26✔
1187
                return nil, 0, fmt.Errorf("error creating prev input fetcher "+
×
1188
                        "for hash cache: %v", err)
×
1189
        }
×
1190
        hashCache := txscript.NewTxSigHashes(sweepTx, prevInputFetcher)
26✔
1191

26✔
1192
        // With all the inputs in place, use each output's unique input script
26✔
1193
        // function to generate the final witness required for spending.
26✔
1194
        addInputScript := func(idx int, tso input.Input) error {
52✔
1195
                inputScript, err := tso.CraftInputScript(
26✔
1196
                        t.cfg.Signer, sweepTx, hashCache, prevInputFetcher, idx,
26✔
1197
                )
26✔
1198
                if err != nil {
26✔
1199
                        return err
×
1200
                }
×
1201

1202
                sweepTx.TxIn[idx].Witness = inputScript.Witness
26✔
1203

26✔
1204
                if len(inputScript.SigScript) == 0 {
52✔
1205
                        return nil
26✔
1206
                }
26✔
1207

1208
                sweepTx.TxIn[idx].SignatureScript = inputScript.SigScript
×
1209

×
1210
                return nil
×
1211
        }
1212

1213
        for idx, inp := range idxs {
52✔
1214
                if err := addInputScript(idx, inp); err != nil {
26✔
1215
                        return nil, 0, err
×
1216
                }
×
1217
        }
1218

1219
        log.Debugf("Created sweep tx %v for %v inputs", sweepTx.TxHash(),
26✔
1220
                len(inputs))
26✔
1221

26✔
1222
        return sweepTx, txFee, nil
26✔
1223
}
1224

1225
// prepareSweepTx returns the tx fee, an optional change amount and an optional
1226
// locktime after a series of validations:
1227
// 1. check the locktime has been reached.
1228
// 2. check the locktimes are the same.
1229
// 3. check the inputs cover the outputs.
1230
//
1231
// NOTE: if the change amount is below dust, it will be added to the tx fee.
1232
func prepareSweepTx(inputs []input.Input, changePkScript []byte,
1233
        feeRate chainfee.SatPerKWeight, currentHeight int32) (
1234
        btcutil.Amount, fn.Option[btcutil.Amount], fn.Option[int32], error) {
26✔
1235

26✔
1236
        noChange := fn.None[btcutil.Amount]()
26✔
1237
        noLocktime := fn.None[int32]()
26✔
1238

26✔
1239
        // Creating a weight estimator with nil outputs and zero max fee rate.
26✔
1240
        // We don't allow adding customized outputs in the sweeping tx, and the
26✔
1241
        // fee rate is already being managed before we get here.
26✔
1242
        inputs, estimator, err := getWeightEstimate(
26✔
1243
                inputs, nil, feeRate, 0, changePkScript,
26✔
1244
        )
26✔
1245
        if err != nil {
26✔
1246
                return 0, noChange, noLocktime, err
×
1247
        }
×
1248

1249
        txFee := estimator.fee()
26✔
1250

26✔
1251
        var (
26✔
1252
                // Track whether any of the inputs require a certain locktime.
26✔
1253
                locktime = int32(-1)
26✔
1254

26✔
1255
                // We keep track of total input amount, and required output
26✔
1256
                // amount to use for calculating the change amount below.
26✔
1257
                totalInput     btcutil.Amount
26✔
1258
                requiredOutput btcutil.Amount
26✔
1259
        )
26✔
1260

26✔
1261
        // Go through each input and check if the required lock times have
26✔
1262
        // reached and are the same.
26✔
1263
        for _, o := range inputs {
52✔
1264
                // If the input has a required output, we'll add it to the
26✔
1265
                // required output amount.
26✔
1266
                if o.RequiredTxOut() != nil {
30✔
1267
                        requiredOutput += btcutil.Amount(
4✔
1268
                                o.RequiredTxOut().Value,
4✔
1269
                        )
4✔
1270
                }
4✔
1271

1272
                // Update the total input amount.
1273
                totalInput += btcutil.Amount(o.SignDesc().Output.Value)
26✔
1274

26✔
1275
                lt, ok := o.RequiredLockTime()
26✔
1276

26✔
1277
                // Skip if the input doesn't require a lock time.
26✔
1278
                if !ok {
52✔
1279
                        continue
26✔
1280
                }
1281

1282
                // Check if the lock time has reached
1283
                if lt > uint32(currentHeight) {
4✔
1284
                        return 0, noChange, noLocktime, ErrLocktimeImmature
×
1285
                }
×
1286

1287
                // If another input commits to a different locktime, they
1288
                // cannot be combined in the same transaction.
1289
                if locktime != -1 && locktime != int32(lt) {
4✔
1290
                        return 0, noChange, noLocktime, ErrLocktimeConflict
×
1291
                }
×
1292

1293
                // Update the locktime for next iteration.
1294
                locktime = int32(lt)
4✔
1295
        }
1296

1297
        // Make sure total output amount is less than total input amount.
1298
        if requiredOutput+txFee > totalInput {
26✔
1299
                return 0, noChange, noLocktime, fmt.Errorf("insufficient "+
×
1300
                        "input to create sweep tx: input_sum=%v, "+
×
1301
                        "output_sum=%v", totalInput, requiredOutput+txFee)
×
1302
        }
×
1303

1304
        // The value remaining after the required output and fees is the
1305
        // change output.
1306
        changeAmt := totalInput - requiredOutput - txFee
26✔
1307
        changeAmtOpt := fn.Some(changeAmt)
26✔
1308

26✔
1309
        // We'll calculate the dust limit for the given changePkScript since it
26✔
1310
        // is variable.
26✔
1311
        changeFloor := lnwallet.DustLimitForSize(len(changePkScript))
26✔
1312

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

4✔
1318
                // If there's no required output, and the change output is a
4✔
1319
                // dust, it means we are creating a tx without any outputs. In
4✔
1320
                // this case we'll return an error. This could happen when
4✔
1321
                // creating a tx that has an anchor as the only input.
4✔
1322
                if requiredOutput == 0 {
8✔
1323
                        return 0, noChange, noLocktime, ErrTxNoOutput
4✔
1324
                }
4✔
1325

1326
                // The dust amount is added to the fee.
1327
                txFee += changeAmt
×
1328

×
1329
                // Set the change amount to none.
×
1330
                changeAmtOpt = fn.None[btcutil.Amount]()
×
1331
        }
1332

1333
        // Optionally set the locktime.
1334
        locktimeOpt := fn.Some(locktime)
26✔
1335
        if locktime == -1 {
52✔
1336
                locktimeOpt = noLocktime
26✔
1337
        }
26✔
1338

1339
        log.Debugf("Creating sweep tx for %v inputs (%s) using %v, "+
26✔
1340
                "tx_weight=%v, tx_fee=%v, locktime=%v, parents_count=%v, "+
26✔
1341
                "parents_fee=%v, parents_weight=%v, current_height=%v",
26✔
1342
                len(inputs), inputTypeSummary(inputs), feeRate,
26✔
1343
                estimator.weight(), txFee, locktimeOpt, len(estimator.parents),
26✔
1344
                estimator.parentsFee, estimator.parentsWeight, currentHeight)
26✔
1345

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