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

lightningnetwork / lnd / 11166428937

03 Oct 2024 05:07PM UTC coverage: 58.738% (-0.08%) from 58.817%
11166428937

push

github

web-flow
Merge pull request #8960 from lightningnetwork/0-19-staging-rebased

[custom channels 5/5]: merge custom channel staging branch into master

657 of 875 new or added lines in 29 files covered. (75.09%)

260 existing lines in 20 files now uncovered.

130540 of 222243 relevant lines covered (58.74%)

28084.43 hits per line

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

92.23
/sweep/fee_bumper.go
1
package sweep
2

3
import (
4
        "errors"
5
        "fmt"
6
        "sync"
7
        "sync/atomic"
8

9
        "github.com/btcsuite/btcd/btcutil"
10
        "github.com/btcsuite/btcd/chaincfg/chainhash"
11
        "github.com/btcsuite/btcd/rpcclient"
12
        "github.com/btcsuite/btcd/txscript"
13
        "github.com/btcsuite/btcd/wire"
14
        "github.com/btcsuite/btcwallet/chain"
15
        "github.com/lightningnetwork/lnd/chainntnfs"
16
        "github.com/lightningnetwork/lnd/fn"
17
        "github.com/lightningnetwork/lnd/input"
18
        "github.com/lightningnetwork/lnd/labels"
19
        "github.com/lightningnetwork/lnd/lntypes"
20
        "github.com/lightningnetwork/lnd/lnutils"
21
        "github.com/lightningnetwork/lnd/lnwallet"
22
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
23
        "github.com/lightningnetwork/lnd/tlv"
24
)
25

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

277
        return nil
7✔
278
}
279

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

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

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

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

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

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

314
        wg sync.WaitGroup
315

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

409
        return result, nil
5✔
410
}
411

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

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

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

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

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

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

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

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

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

9✔
465
                        return requestID, nil
9✔
466

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

2✔
476
                        fallthrough
2✔
477

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

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

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

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

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

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

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

17✔
529
        return requestID
17✔
530
}
17✔
531

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

7✔
696
                return
7✔
697
        }
698

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

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

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

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

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

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

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

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

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

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

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

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

3✔
749
        return nil
3✔
750
}
751

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

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

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

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

3✔
765
        return nil
3✔
766
}
767

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

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

×
787
                                return
×
788
                        }
×
789

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

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

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

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

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

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

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

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

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

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

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

1✔
843
                        // Move to the next record.
1✔
844
                        return nil
1✔
845
                }
1✔
846

847
                feeBumpRecords[requestID] = r
4✔
848

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4✔
935
                return
4✔
936
        }
4✔
937

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

4✔
943
                return
4✔
944
        }
4✔
945

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

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

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

1✔
965
        defer t.wg.Done()
1✔
966

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1✔
1126
                        continue
1✔
1127
                }
1128

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

1140
                // Remove the subscription when exit.
1141
                defer spendEvent.Cancel()
1✔
1142

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

1151
                        spendingTxID := spend.SpendingTx.TxHash()
1✔
1152

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

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

1✔
1162
                        return true
1✔
1163

1164
                // Move to the next input.
1165
                default:
1✔
1166
                }
1167
        }
1168

1169
        return false
1✔
1170
}
1171

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

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

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

7✔
1187
                confTarget = 0
7✔
1188
        } else {
17✔
1189
                confTarget = uint32(deadlineDelta)
10✔
1190
        }
10✔
1191

1192
        return confTarget
14✔
1193
}
1194

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

1199
        fee btcutil.Amount
1200

1201
        extraTxOut fn.Option[SweepOutput]
1202
}
1203

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1296
                return nil
×
1297
        }
1298

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

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

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

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

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

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

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

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

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

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

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

1368
                        extraChangeOut = extraOut.LeftToOption()
22✔
1369

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

25✔
1453
        extraChangeOut.WhenSome(func(o SweepOutput) {
47✔
1454
                changeOuts = append(changeOuts, o)
22✔
1455
        })
22✔
1456

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

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

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

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

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

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

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

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

25✔
1511
        return txFee, changeOutsOpt, locktimeOpt, nil
25✔
1512
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc