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

lightningnetwork / lnd / 15561477203

10 Jun 2025 01:54PM UTC coverage: 58.351% (-10.1%) from 68.487%
15561477203

Pull #9356

github

web-flow
Merge 6440b25db into c6d6d4c0b
Pull Request #9356: lnrpc: add incoming/outgoing channel ids filter to forwarding history request

33 of 36 new or added lines in 2 files covered. (91.67%)

28366 existing lines in 455 files now uncovered.

97715 of 167461 relevant lines covered (58.35%)

1.81 hits per line

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

86.98
/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/chainio"
16
        "github.com/lightningnetwork/lnd/chainntnfs"
17
        "github.com/lightningnetwork/lnd/fn/v2"
18
        "github.com/lightningnetwork/lnd/input"
19
        "github.com/lightningnetwork/lnd/labels"
20
        "github.com/lightningnetwork/lnd/lntypes"
21
        "github.com/lightningnetwork/lnd/lnutils"
22
        "github.com/lightningnetwork/lnd/lnwallet"
23
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
24
        "github.com/lightningnetwork/lnd/tlv"
25
)
26

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

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

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

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

43
        // ErrUnknownSpent is returned when an unknown tx has spent an input in
44
        // the sweeping tx.
45
        ErrUnknownSpent = errors.New("unknown spend of input")
46

47
        // ErrInputMissing is returned when a given input no longer exists,
48
        // e.g., spending from an orphan tx.
49
        ErrInputMissing = errors.New("input no longer exists")
50
)
51

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

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

76
// BumpEvent represents the event of a fee bumping attempt.
77
type BumpEvent uint8
78

79
const (
80
        // TxPublished is sent when the broadcast attempt is finished.
81
        TxPublished BumpEvent = iota
82

83
        // TxFailed is sent when the tx has encountered a fee-related error
84
        // during its creation or broadcast, or an internal error from the fee
85
        // bumper. In either case the inputs in this tx should be retried with
86
        // either a different grouping strategy or an increased budget.
87
        //
88
        // TODO(yy): Remove the above usage once we remove sweeping non-CPFP
89
        // anchors.
90
        TxFailed
91

92
        // TxReplaced is sent when the original tx is replaced by a new one.
93
        TxReplaced
94

95
        // TxConfirmed is sent when the tx is confirmed.
96
        TxConfirmed
97

98
        // TxUnknownSpend is sent when at least one of the inputs is spent but
99
        // not by the current sweeping tx, this can happen when,
100
        // - a remote party has replaced our sweeping tx by spending the
101
        //   input(s), e.g., via the direct preimage spend on our outgoing HTLC.
102
        // - a third party has replaced our sweeping tx, e.g., the anchor output
103
        //   after 16 blocks.
104
        // - A previous sweeping tx has confirmed but the fee bumper is not
105
        //   aware of it, e.g., a restart happens right after the sweeping tx is
106
        //   broadcast and confirmed.
107
        TxUnknownSpend
108

109
        // TxFatal is sent when the inputs in this tx cannot be retried. Txns
110
        // will end up in this state if they have encountered a non-fee related
111
        // error, which means they cannot be retried with increased budget.
112
        TxFatal
113

114
        // sentinalEvent is used to check if an event is unknown.
115
        sentinalEvent
116
)
117

118
// String returns a human-readable string for the event.
119
func (e BumpEvent) String() string {
3✔
120
        switch e {
3✔
121
        case TxPublished:
3✔
122
                return "Published"
3✔
123
        case TxFailed:
3✔
124
                return "Failed"
3✔
125
        case TxReplaced:
3✔
126
                return "Replaced"
3✔
127
        case TxConfirmed:
3✔
128
                return "Confirmed"
3✔
129
        case TxUnknownSpend:
3✔
130
                return "UnknownSpend"
3✔
131
        case TxFatal:
2✔
132
                return "Fatal"
2✔
133
        default:
×
134
                return "Unknown"
×
135
        }
136
}
137

138
// Unknown returns true if the event is unknown.
139
func (e BumpEvent) Unknown() bool {
3✔
140
        return e >= sentinalEvent
3✔
141
}
3✔
142

143
// BumpRequest is used by the caller to give the Bumper the necessary info to
144
// create and manage potential fee bumps for a set of inputs.
145
type BumpRequest struct {
146
        // Budget givens the total amount that can be used as fees by these
147
        // inputs.
148
        Budget btcutil.Amount
149

150
        // Inputs is the set of inputs to sweep.
151
        Inputs []input.Input
152

153
        // DeadlineHeight is the block height at which the tx should be
154
        // confirmed.
155
        DeadlineHeight int32
156

157
        // DeliveryAddress is the script to send the change output to.
158
        DeliveryAddress lnwallet.AddrWithKey
159

160
        // MaxFeeRate is the maximum fee rate that can be used for fee bumping.
161
        MaxFeeRate chainfee.SatPerKWeight
162

163
        // StartingFeeRate is an optional parameter that can be used to specify
164
        // the initial fee rate to use for the fee function.
165
        StartingFeeRate fn.Option[chainfee.SatPerKWeight]
166

167
        // ExtraTxOut tracks if this bump request has an optional set of extra
168
        // outputs to add to the transaction.
169
        ExtraTxOut fn.Option[SweepOutput]
170

171
        // Immediate is used to specify that the tx should be broadcast
172
        // immediately.
173
        Immediate bool
174
}
175

176
// MaxFeeRateAllowed returns the maximum fee rate allowed for the given
177
// request. It calculates the feerate using the supplied budget and the weight,
178
// compares it with the specified MaxFeeRate, and returns the smaller of the
179
// two.
180
func (r *BumpRequest) MaxFeeRateAllowed() (chainfee.SatPerKWeight, error) {
3✔
181
        // We'll want to know if we have any blobs, as we need to factor this
3✔
182
        // into the max fee rate for this bump request.
3✔
183
        hasBlobs := fn.Any(r.Inputs, func(i input.Input) bool {
6✔
184
                return fn.MapOptionZ(
3✔
185
                        i.ResolutionBlob(), func(b tlv.Blob) bool {
6✔
186
                                return len(b) > 0
3✔
187
                        },
3✔
188
                )
189
        })
190

191
        sweepAddrs := [][]byte{
3✔
192
                r.DeliveryAddress.DeliveryAddress,
3✔
193
        }
3✔
194

3✔
195
        // If we have blobs, then we'll add an extra sweep addr for the size
3✔
196
        // estimate below. We know that these blobs will also always be based on
3✔
197
        // p2tr addrs.
3✔
198
        if hasBlobs {
3✔
199
                // We need to pass in a real address, so we'll use a dummy
×
200
                // tapscript change script that's used elsewhere for tests.
×
201
                sweepAddrs = append(sweepAddrs, dummyChangePkScript)
×
202
        }
×
203

204
        // Get the size of the sweep tx, which will be used to calculate the
205
        // budget fee rate.
206
        size, err := calcSweepTxWeight(
3✔
207
                r.Inputs, sweepAddrs,
3✔
208
        )
3✔
209
        if err != nil {
3✔
UNCOV
210
                return 0, err
×
UNCOV
211
        }
×
212

213
        // Use the budget and MaxFeeRate to decide the max allowed fee rate.
214
        // This is needed as, when the input has a large value and the user
215
        // sets the budget to be proportional to the input value, the fee rate
216
        // can be very high and we need to make sure it doesn't exceed the max
217
        // fee rate.
218
        maxFeeRateAllowed := chainfee.NewSatPerKWeight(r.Budget, size)
3✔
219
        if maxFeeRateAllowed > r.MaxFeeRate {
6✔
220
                log.Debugf("Budget feerate %v exceeds MaxFeeRate %v, use "+
3✔
221
                        "MaxFeeRate instead, txWeight=%v", maxFeeRateAllowed,
3✔
222
                        r.MaxFeeRate, size)
3✔
223

3✔
224
                return r.MaxFeeRate, nil
3✔
225
        }
3✔
226

227
        log.Debugf("Budget feerate %v below MaxFeeRate %v, use budget feerate "+
3✔
228
                "instead, txWeight=%v", maxFeeRateAllowed, r.MaxFeeRate, size)
3✔
229

3✔
230
        return maxFeeRateAllowed, nil
3✔
231
}
232

233
// calcSweepTxWeight calculates the weight of the sweep tx. It assumes a
234
// sweeping tx always has a single output(change).
235
func calcSweepTxWeight(inputs []input.Input,
236
        outputPkScript [][]byte) (lntypes.WeightUnit, error) {
3✔
237

3✔
238
        // Use a const fee rate as we only use the weight estimator to
3✔
239
        // calculate the size.
3✔
240
        const feeRate = 1
3✔
241

3✔
242
        // Initialize the tx weight estimator with,
3✔
243
        // - nil outputs as we only have one single change output.
3✔
244
        // - const fee rate as we don't care about the fees here.
3✔
245
        // - 0 maxfeerate as we don't care about fees here.
3✔
246
        //
3✔
247
        // TODO(yy): we should refactor the weight estimator to not require a
3✔
248
        // fee rate and max fee rate and make it a pure tx weight calculator.
3✔
249
        _, estimator, err := getWeightEstimate(
3✔
250
                inputs, nil, feeRate, 0, outputPkScript,
3✔
251
        )
3✔
252
        if err != nil {
3✔
UNCOV
253
                return 0, err
×
UNCOV
254
        }
×
255

256
        return estimator.weight(), nil
3✔
257
}
258

259
// BumpResult is used by the Bumper to send updates about the tx being
260
// broadcast.
261
type BumpResult struct {
262
        // Event is the type of event that the result is for.
263
        Event BumpEvent
264

265
        // Tx is the tx being broadcast.
266
        Tx *wire.MsgTx
267

268
        // ReplacedTx is the old, replaced tx if a fee bump is attempted.
269
        ReplacedTx *wire.MsgTx
270

271
        // FeeRate is the fee rate used for the new tx.
272
        FeeRate chainfee.SatPerKWeight
273

274
        // Fee is the fee paid by the new tx.
275
        Fee btcutil.Amount
276

277
        // Err is the error that occurred during the broadcast.
278
        Err error
279

280
        // SpentInputs are the inputs spent by another tx which caused the
281
        // current tx to be failed.
282
        SpentInputs map[wire.OutPoint]*wire.MsgTx
283

284
        // requestID is the ID of the request that created this record.
285
        requestID uint64
286
}
287

288
// String returns a human-readable string for the result.
289
func (b *BumpResult) String() string {
3✔
290
        desc := fmt.Sprintf("Event=%v", b.Event)
3✔
291
        if b.Tx != nil {
6✔
292
                desc += fmt.Sprintf(", Tx=%v", b.Tx.TxHash())
3✔
293
        }
3✔
294

295
        return fmt.Sprintf("[%s]", desc)
3✔
296
}
297

298
// Validate validates the BumpResult so it's safe to use.
299
func (b *BumpResult) Validate() error {
3✔
300
        isFailureEvent := b.Event == TxFailed || b.Event == TxFatal ||
3✔
301
                b.Event == TxUnknownSpend
3✔
302

3✔
303
        // Every result must have a tx except the fatal or failed case.
3✔
304
        if b.Tx == nil && !isFailureEvent {
3✔
UNCOV
305
                return fmt.Errorf("%w: nil tx", ErrInvalidBumpResult)
×
UNCOV
306
        }
×
307

308
        // Every result must have a known event.
309
        if b.Event.Unknown() {
3✔
UNCOV
310
                return fmt.Errorf("%w: unknown event", ErrInvalidBumpResult)
×
UNCOV
311
        }
×
312

313
        // If it's a replacing event, it must have a replaced tx.
314
        if b.Event == TxReplaced && b.ReplacedTx == nil {
3✔
UNCOV
315
                return fmt.Errorf("%w: nil replacing tx", ErrInvalidBumpResult)
×
UNCOV
316
        }
×
317

318
        // If it's a failed or fatal event, it must have an error.
319
        if isFailureEvent && b.Err == nil {
3✔
UNCOV
320
                return fmt.Errorf("%w: nil error", ErrInvalidBumpResult)
×
UNCOV
321
        }
×
322

323
        // If it's a confirmed event, it must have a fee rate and fee.
324
        if b.Event == TxConfirmed && (b.FeeRate == 0 || b.Fee == 0) {
3✔
UNCOV
325
                return fmt.Errorf("%w: missing fee rate or fee",
×
UNCOV
326
                        ErrInvalidBumpResult)
×
UNCOV
327
        }
×
328

329
        return nil
3✔
330
}
331

332
// TxPublisherConfig is the config used to create a new TxPublisher.
333
type TxPublisherConfig struct {
334
        // Signer is used to create the tx signature.
335
        Signer input.Signer
336

337
        // Wallet is used primarily to publish the tx.
338
        Wallet Wallet
339

340
        // Estimator is used to estimate the fee rate for the new tx based on
341
        // its deadline conf target.
342
        Estimator chainfee.Estimator
343

344
        // Notifier is used to monitor the confirmation status of the tx.
345
        Notifier chainntnfs.ChainNotifier
346

347
        // AuxSweeper is an optional interface that can be used to modify the
348
        // way sweep transaction are generated.
349
        AuxSweeper fn.Option[AuxSweeper]
350
}
351

352
// TxPublisher is an implementation of the Bumper interface. It utilizes the
353
// `testmempoolaccept` RPC to bump the fee of txns it created based on
354
// different fee function selected or configed by the caller. Its purpose is to
355
// take a list of inputs specified, and create a tx that spends them to a
356
// specified output. It will then monitor the confirmation status of the tx,
357
// and if it's not confirmed within a certain time frame, it will attempt to
358
// bump the fee of the tx by creating a new tx that spends the same inputs to
359
// the same output, but with a higher fee rate. It will continue to do this
360
// until the tx is confirmed or the fee rate reaches the maximum fee rate
361
// specified by the caller.
362
type TxPublisher struct {
363
        started atomic.Bool
364
        stopped atomic.Bool
365

366
        // Embed the blockbeat consumer struct to get access to the method
367
        // `NotifyBlockProcessed` and the `BlockbeatChan`.
368
        chainio.BeatConsumer
369

370
        wg sync.WaitGroup
371

372
        // cfg specifies the configuration of the TxPublisher.
373
        cfg *TxPublisherConfig
374

375
        // currentHeight is the current block height.
376
        currentHeight atomic.Int32
377

378
        // records is a map keyed by the requestCounter and the value is the tx
379
        // being monitored.
380
        records lnutils.SyncMap[uint64, *monitorRecord]
381

382
        // requestCounter is a monotonically increasing counter used to keep
383
        // track of how many requests have been made.
384
        requestCounter atomic.Uint64
385

386
        // subscriberChans is a map keyed by the requestCounter, each item is
387
        // the chan that the publisher sends the fee bump result to.
388
        subscriberChans lnutils.SyncMap[uint64, chan *BumpResult]
389

390
        // quit is used to signal the publisher to stop.
391
        quit chan struct{}
392
}
393

394
// Compile-time constraint to ensure TxPublisher implements Bumper.
395
var _ Bumper = (*TxPublisher)(nil)
396

397
// Compile-time check for the chainio.Consumer interface.
398
var _ chainio.Consumer = (*TxPublisher)(nil)
399

400
// NewTxPublisher creates a new TxPublisher.
401
func NewTxPublisher(cfg TxPublisherConfig) *TxPublisher {
3✔
402
        tp := &TxPublisher{
3✔
403
                cfg:             &cfg,
3✔
404
                records:         lnutils.SyncMap[uint64, *monitorRecord]{},
3✔
405
                subscriberChans: lnutils.SyncMap[uint64, chan *BumpResult]{},
3✔
406
                quit:            make(chan struct{}),
3✔
407
        }
3✔
408

3✔
409
        // Mount the block consumer.
3✔
410
        tp.BeatConsumer = chainio.NewBeatConsumer(tp.quit, tp.Name())
3✔
411

3✔
412
        return tp
3✔
413
}
3✔
414

415
// isNeutrinoBackend checks if the wallet backend is neutrino.
416
func (t *TxPublisher) isNeutrinoBackend() bool {
×
417
        return t.cfg.Wallet.BackEnd() == "neutrino"
×
418
}
×
419

420
// Broadcast is used to publish the tx created from the given inputs. It will
421
// register the broadcast request and return a chan to the caller to subscribe
422
// the broadcast result. The initial broadcast is guaranteed to be
423
// RBF-compliant unless the budget specified cannot cover the fee.
424
//
425
// NOTE: part of the Bumper interface.
426
func (t *TxPublisher) Broadcast(req *BumpRequest) <-chan *BumpResult {
3✔
427
        log.Tracef("Received broadcast request: %s",
3✔
428
                lnutils.SpewLogClosure(req))
3✔
429

3✔
430
        // Store the request.
3✔
431
        record := t.storeInitialRecord(req)
3✔
432

3✔
433
        // Create a chan to send the result to the caller.
3✔
434
        subscriber := make(chan *BumpResult, 1)
3✔
435
        t.subscriberChans.Store(record.requestID, subscriber)
3✔
436

3✔
437
        // Publish the tx immediately if specified.
3✔
438
        if req.Immediate {
6✔
439
                t.handleInitialBroadcast(record)
3✔
440
        }
3✔
441

442
        return subscriber
3✔
443
}
444

445
// storeInitialRecord initializes a monitor record and saves it in the map.
446
func (t *TxPublisher) storeInitialRecord(req *BumpRequest) *monitorRecord {
3✔
447
        // Increase the request counter.
3✔
448
        //
3✔
449
        // NOTE: this is the only place where we increase the counter.
3✔
450
        requestID := t.requestCounter.Add(1)
3✔
451

3✔
452
        // Register the record.
3✔
453
        record := &monitorRecord{
3✔
454
                requestID: requestID,
3✔
455
                req:       req,
3✔
456
        }
3✔
457
        t.records.Store(requestID, record)
3✔
458

3✔
459
        return record
3✔
460
}
3✔
461

462
// updateRecord updates the given record's tx and fee, and saves it in the
463
// records map.
464
func (t *TxPublisher) updateRecord(r *monitorRecord,
465
        sweepCtx *sweepTxCtx) *monitorRecord {
3✔
466

3✔
467
        r.tx = sweepCtx.tx
3✔
468
        r.fee = sweepCtx.fee
3✔
469
        r.outpointToTxIndex = sweepCtx.outpointToTxIndex
3✔
470

3✔
471
        // Register the record.
3✔
472
        t.records.Store(r.requestID, r)
3✔
473

3✔
474
        return r
3✔
475
}
3✔
476

477
// NOTE: part of the `chainio.Consumer` interface.
478
func (t *TxPublisher) Name() string {
3✔
479
        return "TxPublisher"
3✔
480
}
3✔
481

482
// initializeTx initializes a fee function and creates an RBF-compliant tx. If
483
// succeeded, the initial tx is stored in the records map.
484
func (t *TxPublisher) initializeTx(r *monitorRecord) (*monitorRecord, error) {
3✔
485
        // Create a fee bumping algorithm to be used for future RBF.
3✔
486
        feeAlgo, err := t.initializeFeeFunction(r.req)
3✔
487
        if err != nil {
6✔
488
                return nil, fmt.Errorf("init fee function: %w", err)
3✔
489
        }
3✔
490

491
        // Attach the newly created fee function.
492
        //
493
        // TODO(yy): current we'd initialize a monitorRecord before creating the
494
        // fee function, while we could instead create the fee function first
495
        // then save it to the record. To make this happen we need to change the
496
        // conf target calculation below since we would be initializing the fee
497
        // function one block before.
498
        r.feeFunction = feeAlgo
3✔
499

3✔
500
        // Create the initial tx to be broadcasted. This tx is guaranteed to
3✔
501
        // comply with the RBF restrictions.
3✔
502
        record, err := t.createRBFCompliantTx(r)
3✔
503
        if err != nil {
6✔
504
                return nil, fmt.Errorf("create RBF-compliant tx: %w", err)
3✔
505
        }
3✔
506

507
        return record, nil
3✔
508
}
509

510
// initializeFeeFunction initializes a fee function to be used for this request
511
// for future fee bumping.
512
func (t *TxPublisher) initializeFeeFunction(
513
        req *BumpRequest) (FeeFunction, error) {
3✔
514

3✔
515
        // Get the max allowed feerate.
3✔
516
        maxFeeRateAllowed, err := req.MaxFeeRateAllowed()
3✔
517
        if err != nil {
3✔
518
                return nil, err
×
519
        }
×
520

521
        // Get the initial conf target.
522
        confTarget := calcCurrentConfTarget(
3✔
523
                t.currentHeight.Load(), req.DeadlineHeight,
3✔
524
        )
3✔
525

3✔
526
        log.Debugf("Initializing fee function with conf target=%v, budget=%v, "+
3✔
527
                "maxFeeRateAllowed=%v", confTarget, req.Budget,
3✔
528
                maxFeeRateAllowed)
3✔
529

3✔
530
        // Initialize the fee function and return it.
3✔
531
        //
3✔
532
        // TODO(yy): return based on differet req.Strategy?
3✔
533
        return NewLinearFeeFunction(
3✔
534
                maxFeeRateAllowed, confTarget, t.cfg.Estimator,
3✔
535
                req.StartingFeeRate,
3✔
536
        )
3✔
537
}
538

539
// createRBFCompliantTx creates a tx that is compliant with RBF rules. It does
540
// so by creating a tx, validate it using `TestMempoolAccept`, and bump its fee
541
// and redo the process until the tx is valid, or return an error when non-RBF
542
// related errors occur or the budget has been used up.
543
func (t *TxPublisher) createRBFCompliantTx(
544
        r *monitorRecord) (*monitorRecord, error) {
3✔
545

3✔
546
        f := r.feeFunction
3✔
547

3✔
548
        for {
6✔
549
                // Create a new tx with the given fee rate and check its
3✔
550
                // mempool acceptance.
3✔
551
                sweepCtx, err := t.createAndCheckTx(r)
3✔
552

3✔
553
                switch {
3✔
554
                case err == nil:
3✔
555
                        // The tx is valid, store it.
3✔
556
                        record := t.updateRecord(r, sweepCtx)
3✔
557

3✔
558
                        log.Infof("Created initial sweep tx=%v for %v inputs: "+
3✔
559
                                "feerate=%v, fee=%v, inputs:\n%v",
3✔
560
                                sweepCtx.tx.TxHash(), len(r.req.Inputs),
3✔
561
                                f.FeeRate(), sweepCtx.fee,
3✔
562
                                inputTypeSummary(r.req.Inputs))
3✔
563

3✔
564
                        return record, nil
3✔
565

566
                // If the error indicates the fees paid is not enough, we will
567
                // ask the fee function to increase the fee rate and retry.
UNCOV
568
                case errors.Is(err, lnwallet.ErrMempoolFee):
×
UNCOV
569
                        // We should at least start with a feerate above the
×
UNCOV
570
                        // mempool min feerate, so if we get this error, it
×
UNCOV
571
                        // means something is wrong earlier in the pipeline.
×
UNCOV
572
                        log.Errorf("Current fee=%v, feerate=%v, %v",
×
UNCOV
573
                                sweepCtx.fee, f.FeeRate(), err)
×
UNCOV
574

×
UNCOV
575
                        fallthrough
×
576

577
                // We are not paying enough fees so we increase it.
578
                case errors.Is(err, chain.ErrInsufficientFee):
2✔
579
                        increased := false
2✔
580

2✔
581
                        // Keep calling the fee function until the fee rate is
2✔
582
                        // increased or maxed out.
2✔
583
                        for !increased {
4✔
584
                                log.Debugf("Increasing fee for next round, "+
2✔
585
                                        "current fee=%v, feerate=%v",
2✔
586
                                        sweepCtx.fee, f.FeeRate())
2✔
587

2✔
588
                                // If the fee function tells us that we have
2✔
589
                                // used up the budget, we will return an error
2✔
590
                                // indicating this tx cannot be made. The
2✔
591
                                // sweeper should handle this error and try to
2✔
592
                                // cluster these inputs differetly.
2✔
593
                                increased, err = f.Increment()
2✔
594
                                if err != nil {
4✔
595
                                        return nil, err
2✔
596
                                }
2✔
597
                        }
598

599
                // TODO(yy): suppose there's only one bad input, we can do a
600
                // binary search to find out which input is causing this error
601
                // by recreating a tx using half of the inputs and check its
602
                // mempool acceptance.
603
                default:
3✔
604
                        log.Debugf("Failed to create RBF-compliant tx: %v", err)
3✔
605
                        return nil, err
3✔
606
                }
607
        }
608
}
609

610
// createAndCheckTx creates a tx based on the given inputs, change output
611
// script, and the fee rate. In addition, it validates the tx's mempool
612
// acceptance before returning a tx that can be published directly, along with
613
// its fee.
614
func (t *TxPublisher) createAndCheckTx(r *monitorRecord) (*sweepTxCtx, error) {
3✔
615
        req := r.req
3✔
616
        f := r.feeFunction
3✔
617

3✔
618
        // Create the sweep tx with max fee rate of 0 as the fee function
3✔
619
        // guarantees the fee rate used here won't exceed the max fee rate.
3✔
620
        sweepCtx, err := t.createSweepTx(
3✔
621
                req.Inputs, req.DeliveryAddress, f.FeeRate(),
3✔
622
        )
3✔
623
        if err != nil {
6✔
624
                return sweepCtx, fmt.Errorf("create sweep tx: %w", err)
3✔
625
        }
3✔
626

627
        // Sanity check the budget still covers the fee.
628
        if sweepCtx.fee > req.Budget {
3✔
UNCOV
629
                return sweepCtx, fmt.Errorf("%w: budget=%v, fee=%v",
×
UNCOV
630
                        ErrNotEnoughBudget, req.Budget, sweepCtx.fee)
×
UNCOV
631
        }
×
632

633
        // If we had an extra txOut, then we'll update the result to include
634
        // it.
635
        req.ExtraTxOut = sweepCtx.extraTxOut
3✔
636

3✔
637
        // Validate the tx's mempool acceptance.
3✔
638
        err = t.cfg.Wallet.CheckMempoolAcceptance(sweepCtx.tx)
3✔
639

3✔
640
        // Exit early if the tx is valid.
3✔
641
        if err == nil {
5✔
642
                return sweepCtx, nil
2✔
643
        }
2✔
644

645
        // Print an error log if the chain backend doesn't support the mempool
646
        // acceptance test RPC.
647
        if errors.Is(err, rpcclient.ErrBackendVersion) {
3✔
648
                log.Errorf("TestMempoolAccept not supported by backend, " +
×
649
                        "consider upgrading it to a newer version")
×
650
                return sweepCtx, nil
×
651
        }
×
652

653
        // We are running on a backend that doesn't implement the RPC
654
        // testmempoolaccept, eg, neutrino, so we'll skip the check.
655
        if errors.Is(err, chain.ErrUnimplemented) {
4✔
656
                log.Debug("Skipped testmempoolaccept due to not implemented")
1✔
657
                return sweepCtx, nil
1✔
658
        }
1✔
659

660
        // If the inputs are spent by another tx, we will exit with the latest
661
        // sweepCtx and an error.
662
        if errors.Is(err, chain.ErrMissingInputs) {
4✔
663
                log.Debugf("Tx %v missing inputs, it's likely the input has "+
2✔
664
                        "been spent by others", sweepCtx.tx.TxHash())
2✔
665

2✔
666
                // Make sure to update the record with the latest attempt.
2✔
667
                t.updateRecord(r, sweepCtx)
2✔
668

2✔
669
                return sweepCtx, ErrInputMissing
2✔
670
        }
2✔
671

672
        return sweepCtx, fmt.Errorf("tx=%v failed mempool check: %w",
2✔
673
                sweepCtx.tx.TxHash(), err)
2✔
674
}
675

676
// handleMissingInputs handles the case when the chain backend reports back a
677
// missing inputs error, which could happen when one of the input has been spent
678
// in another tx, or the input is referencing an orphan. When the input is
679
// spent, it will be handled via the TxUnknownSpend flow by creating a
680
// TxUnknownSpend bump result, otherwise, a TxFatal bump result is returned.
681
func (t *TxPublisher) handleMissingInputs(r *monitorRecord) *BumpResult {
2✔
682
        // Get the spending txns.
2✔
683
        spends := t.getSpentInputs(r)
2✔
684

2✔
685
        // Attach the spending txns.
2✔
686
        r.spentInputs = spends
2✔
687

2✔
688
        // If there are no spending txns found and the input is missing, the
2✔
689
        // input is referencing an orphan tx that's no longer valid, e.g., the
2✔
690
        // spending the anchor output from the remote commitment after the local
2✔
691
        // commitment has confirmed. In this case we will mark it as fatal and
2✔
692
        // exit.
2✔
693
        if len(spends) == 0 {
4✔
694
                log.Warnf("Failing record=%v: found orphan inputs: %v\n",
2✔
695
                        r.requestID, inputTypeSummary(r.req.Inputs))
2✔
696

2✔
697
                // Create a result that will be sent to the resultChan which is
2✔
698
                // listened by the caller.
2✔
699
                result := &BumpResult{
2✔
700
                        Event:     TxFatal,
2✔
701
                        Tx:        r.tx,
2✔
702
                        requestID: r.requestID,
2✔
703
                        Err:       ErrInputMissing,
2✔
704
                }
2✔
705

2✔
706
                return result
2✔
707
        }
2✔
708

709
        // Check that the spending tx matches the sweeping tx - given that the
710
        // current sweeping tx has been failed due to missing inputs, the
711
        // spending tx must be a different tx, thus it should NOT be matched. We
712
        // perform a sanity check here to catch the unexpected state.
713
        if !t.isUnknownSpent(r, spends) {
1✔
714
                log.Errorf("Sweeping tx %v has missing inputs, yet the "+
×
715
                        "spending tx is the sweeping tx itself: %v",
×
716
                        r.tx.TxHash(), r.spentInputs)
×
717
        }
×
718

719
        return t.createUnknownSpentBumpResult(r)
1✔
720
}
721

722
// broadcast takes a monitored tx and publishes it to the network. Prior to the
723
// broadcast, it will subscribe the tx's confirmation notification and attach
724
// the event channel to the record. Any broadcast-related errors will not be
725
// returned here, instead, they will be put inside the `BumpResult` and
726
// returned to the caller.
727
func (t *TxPublisher) broadcast(record *monitorRecord) (*BumpResult, error) {
3✔
728
        txid := record.tx.TxHash()
3✔
729

3✔
730
        tx := record.tx
3✔
731
        log.Debugf("Publishing sweep tx %v, num_inputs=%v, height=%v",
3✔
732
                txid, len(tx.TxIn), t.currentHeight.Load())
3✔
733

3✔
734
        // Before we go to broadcast, we'll notify the aux sweeper, if it's
3✔
735
        // present of this new broadcast attempt.
3✔
736
        err := fn.MapOptionZ(t.cfg.AuxSweeper, func(aux AuxSweeper) error {
3✔
UNCOV
737
                return aux.NotifyBroadcast(
×
UNCOV
738
                        record.req, tx, record.fee, record.outpointToTxIndex,
×
UNCOV
739
                )
×
UNCOV
740
        })
×
741
        if err != nil {
3✔
742
                return nil, fmt.Errorf("unable to notify aux sweeper: %w", err)
×
743
        }
×
744

745
        // Set the event, and change it to TxFailed if the wallet fails to
746
        // publish it.
747
        event := TxPublished
3✔
748

3✔
749
        // Publish the sweeping tx with customized label. If the publish fails,
3✔
750
        // this error will be saved in the `BumpResult` and it will be removed
3✔
751
        // from being monitored.
3✔
752
        err = t.cfg.Wallet.PublishTransaction(
3✔
753
                tx, labels.MakeLabel(labels.LabelTypeSweepTransaction, nil),
3✔
754
        )
3✔
755
        if err != nil {
5✔
756
                // NOTE: we decide to attach this error to the result instead
2✔
757
                // of returning it here because by the time the tx reaches
2✔
758
                // here, it should have passed the mempool acceptance check. If
2✔
759
                // it still fails to be broadcast, it's likely a non-RBF
2✔
760
                // related error happened. So we send this error back to the
2✔
761
                // caller so that it can handle it properly.
2✔
762
                //
2✔
763
                // TODO(yy): find out which input is causing the failure.
2✔
764
                log.Errorf("Failed to publish tx %v: %v", txid, err)
2✔
765
                event = TxFailed
2✔
766
        }
2✔
767

768
        result := &BumpResult{
3✔
769
                Event:     event,
3✔
770
                Tx:        record.tx,
3✔
771
                Fee:       record.fee,
3✔
772
                FeeRate:   record.feeFunction.FeeRate(),
3✔
773
                Err:       err,
3✔
774
                requestID: record.requestID,
3✔
775
        }
3✔
776

3✔
777
        return result, nil
3✔
778
}
779

780
// notifyResult sends the result to the resultChan specified by the requestID.
781
// This channel is expected to be read by the caller.
782
func (t *TxPublisher) notifyResult(result *BumpResult) {
3✔
783
        id := result.requestID
3✔
784
        subscriber, ok := t.subscriberChans.Load(id)
3✔
785
        if !ok {
4✔
786
                log.Errorf("Result chan for id=%v not found", id)
1✔
787
                return
1✔
788
        }
1✔
789

790
        log.Debugf("Sending result %v for requestID=%v", result, id)
3✔
791

3✔
792
        select {
3✔
793
        // Send the result to the subscriber.
794
        //
795
        // TODO(yy): Add timeout in case it's blocking?
796
        case subscriber <- result:
3✔
UNCOV
797
        case <-t.quit:
×
UNCOV
798
                log.Debug("Fee bumper stopped")
×
799
        }
800
}
801

802
// removeResult removes the tracking of the result if the result contains a
803
// non-nil error, or the tx is confirmed, the record will be removed from the
804
// maps.
805
func (t *TxPublisher) removeResult(result *BumpResult) {
3✔
806
        id := result.requestID
3✔
807

3✔
808
        var txid chainhash.Hash
3✔
809
        if result.Tx != nil {
6✔
810
                txid = result.Tx.TxHash()
3✔
811
        }
3✔
812

813
        // Remove the record from the maps if there's an error or the tx is
814
        // confirmed. When there's an error, it means this tx has failed its
815
        // broadcast and cannot be retried. There are two cases it may fail,
816
        // - when the budget cannot cover the increased fee calculated by the
817
        //   fee function, hence the budget is used up.
818
        // - when a non-fee related error returned from PublishTransaction.
819
        switch result.Event {
3✔
820
        case TxFailed:
3✔
821
                log.Errorf("Removing monitor record=%v, tx=%v, due to err: %v",
3✔
822
                        id, txid, result.Err)
3✔
823

824
        case TxConfirmed:
3✔
825
                // Remove the record if the tx is confirmed.
3✔
826
                log.Debugf("Removing confirmed monitor record=%v, tx=%v", id,
3✔
827
                        txid)
3✔
828

829
        case TxFatal:
2✔
830
                // Remove the record if there's an error.
2✔
831
                log.Debugf("Removing monitor record=%v due to fatal err: %v",
2✔
832
                        id, result.Err)
2✔
833

834
        case TxUnknownSpend:
3✔
835
                // Remove the record if there's an unknown spend.
3✔
836
                log.Debugf("Removing monitor record=%v due unknown spent: "+
3✔
837
                        "%v", id, result.Err)
3✔
838

839
        // Do nothing if it's neither failed or confirmed.
840
        default:
3✔
841
                log.Tracef("Skipping record removal for id=%v, event=%v", id,
3✔
842
                        result.Event)
3✔
843

3✔
844
                return
3✔
845
        }
846

847
        t.records.Delete(id)
3✔
848
        t.subscriberChans.Delete(id)
3✔
849
}
850

851
// handleResult handles the result of a tx broadcast. It will notify the
852
// subscriber and remove the record if the tx is confirmed or failed to be
853
// broadcast.
854
func (t *TxPublisher) handleResult(result *BumpResult) {
3✔
855
        // Notify the subscriber.
3✔
856
        t.notifyResult(result)
3✔
857

3✔
858
        // Remove the record if it's failed or confirmed.
3✔
859
        t.removeResult(result)
3✔
860
}
3✔
861

862
// monitorRecord is used to keep track of the tx being monitored by the
863
// publisher internally.
864
type monitorRecord struct {
865
        // requestID is the ID of the request that created this record.
866
        requestID uint64
867

868
        // tx is the tx being monitored.
869
        tx *wire.MsgTx
870

871
        // req is the original request.
872
        req *BumpRequest
873

874
        // feeFunction is the fee bumping algorithm used by the publisher.
875
        feeFunction FeeFunction
876

877
        // fee is the fee paid by the tx.
878
        fee btcutil.Amount
879

880
        // outpointToTxIndex is a map of outpoint to tx index.
881
        outpointToTxIndex map[wire.OutPoint]int
882

883
        // spentInputs are the inputs spent by another tx which caused the
884
        // current tx failed.
885
        spentInputs map[wire.OutPoint]*wire.MsgTx
886
}
887

888
// Start starts the publisher by subscribing to block epoch updates and kicking
889
// off the monitor loop.
890
func (t *TxPublisher) Start(beat chainio.Blockbeat) error {
3✔
891
        log.Info("TxPublisher starting...")
3✔
892

3✔
893
        if t.started.Swap(true) {
3✔
894
                return fmt.Errorf("TxPublisher started more than once")
×
895
        }
×
896

897
        // Set the current height.
898
        t.currentHeight.Store(beat.Height())
3✔
899

3✔
900
        t.wg.Add(1)
3✔
901
        go t.monitor()
3✔
902

3✔
903
        log.Debugf("TxPublisher started")
3✔
904

3✔
905
        return nil
3✔
906
}
907

908
// Stop stops the publisher and waits for the monitor loop to exit.
909
func (t *TxPublisher) Stop() error {
3✔
910
        log.Info("TxPublisher stopping...")
3✔
911

3✔
912
        if t.stopped.Swap(true) {
3✔
913
                return fmt.Errorf("TxPublisher stopped more than once")
×
914
        }
×
915

916
        close(t.quit)
3✔
917
        t.wg.Wait()
3✔
918

3✔
919
        log.Debug("TxPublisher stopped")
3✔
920

3✔
921
        return nil
3✔
922
}
923

924
// monitor is the main loop driven by new blocks. Whevenr a new block arrives,
925
// it will examine all the txns being monitored, and check if any of them needs
926
// to be bumped. If so, it will attempt to bump the fee of the tx.
927
//
928
// NOTE: Must be run as a goroutine.
929
func (t *TxPublisher) monitor() {
3✔
930
        defer t.wg.Done()
3✔
931

3✔
932
        for {
6✔
933
                select {
3✔
934
                case beat := <-t.BlockbeatChan:
3✔
935
                        height := beat.Height()
3✔
936
                        log.Debugf("TxPublisher received new block: %v", height)
3✔
937

3✔
938
                        // Update the best known height for the publisher.
3✔
939
                        t.currentHeight.Store(height)
3✔
940

3✔
941
                        // Check all monitored txns to see if any of them needs
3✔
942
                        // to be bumped.
3✔
943
                        t.processRecords()
3✔
944

3✔
945
                        // Notify we've processed the block.
3✔
946
                        t.NotifyBlockProcessed(beat, nil)
3✔
947

948
                case <-t.quit:
3✔
949
                        log.Debug("Fee bumper stopped, exit monitor")
3✔
950
                        return
3✔
951
                }
952
        }
953
}
954

955
// processRecords checks all the txns being monitored, and checks if any of
956
// them needs to be bumped. If so, it will attempt to bump the fee of the tx.
957
func (t *TxPublisher) processRecords() {
3✔
958
        // confirmedRecords stores a map of the records which have been
3✔
959
        // confirmed.
3✔
960
        confirmedRecords := make(map[uint64]*monitorRecord)
3✔
961

3✔
962
        // feeBumpRecords stores a map of records which need to be bumped.
3✔
963
        feeBumpRecords := make(map[uint64]*monitorRecord)
3✔
964

3✔
965
        // failedRecords stores a map of records which has inputs being spent
3✔
966
        // by a third party.
3✔
967
        failedRecords := make(map[uint64]*monitorRecord)
3✔
968

3✔
969
        // initialRecords stores a map of records which are being created and
3✔
970
        // published for the first time.
3✔
971
        initialRecords := make(map[uint64]*monitorRecord)
3✔
972

3✔
973
        // visitor is a helper closure that visits each record and divides them
3✔
974
        // into two groups.
3✔
975
        visitor := func(requestID uint64, r *monitorRecord) error {
6✔
976
                log.Tracef("Checking monitor recordID=%v", requestID)
3✔
977

3✔
978
                // Check whether the inputs have already been spent.
3✔
979
                spends := t.getSpentInputs(r)
3✔
980

3✔
981
                // If the any of the inputs has been spent, the record will be
3✔
982
                // marked as failed or confirmed.
3✔
983
                if len(spends) != 0 {
6✔
984
                        // Attach the spending txns.
3✔
985
                        r.spentInputs = spends
3✔
986

3✔
987
                        // When tx is nil, it means we haven't tried the initial
3✔
988
                        // broadcast yet the input is already spent. This could
3✔
989
                        // happen when the node shuts down, a previous sweeping
3✔
990
                        // tx confirmed, then the node comes back online and
3✔
991
                        // reoffers the inputs. Another case is the remote node
3✔
992
                        // spends the input quickly before we even attempt the
3✔
993
                        // sweep. In either case we will fail the record and let
3✔
994
                        // the sweeper handles it.
3✔
995
                        if r.tx == nil {
4✔
996
                                failedRecords[requestID] = r
1✔
997
                                return nil
1✔
998
                        }
1✔
999

1000
                        // Check whether the inputs has been spent by a unknown
1001
                        // tx.
1002
                        if t.isUnknownSpent(r, spends) {
6✔
1003
                                failedRecords[requestID] = r
3✔
1004

3✔
1005
                                // Move to the next record.
3✔
1006
                                return nil
3✔
1007
                        }
3✔
1008

1009
                        // The tx is ours, we can move it to the confirmed queue
1010
                        // and stop monitoring it.
1011
                        confirmedRecords[requestID] = r
3✔
1012

3✔
1013
                        // Move to the next record.
3✔
1014
                        return nil
3✔
1015
                }
1016

1017
                // This is the first time we see this record, so we put it in
1018
                // the initial queue.
1019
                if r.tx == nil {
6✔
1020
                        initialRecords[requestID] = r
3✔
1021

3✔
1022
                        return nil
3✔
1023
                }
3✔
1024

1025
                // We can only get here when the inputs are not spent and a
1026
                // previous sweeping tx has been attempted. In this case we will
1027
                // perform an RBF on it in the current block.
1028
                feeBumpRecords[requestID] = r
3✔
1029

3✔
1030
                // Return nil to move to the next record.
3✔
1031
                return nil
3✔
1032
        }
1033

1034
        // Iterate through all the records and divide them into four groups.
1035
        t.records.ForEach(visitor)
3✔
1036

3✔
1037
        // Handle the initial broadcast.
3✔
1038
        for _, r := range initialRecords {
6✔
1039
                t.handleInitialBroadcast(r)
3✔
1040
        }
3✔
1041

1042
        // For records that are confirmed, we'll notify the caller about this
1043
        // result.
1044
        for _, r := range confirmedRecords {
6✔
1045
                t.wg.Add(1)
3✔
1046
                go t.handleTxConfirmed(r)
3✔
1047
        }
3✔
1048

1049
        // Get the current height to be used in the following goroutines.
1050
        currentHeight := t.currentHeight.Load()
3✔
1051

3✔
1052
        // For records that are not confirmed, we perform a fee bump if needed.
3✔
1053
        for _, r := range feeBumpRecords {
6✔
1054
                t.wg.Add(1)
3✔
1055
                go t.handleFeeBumpTx(r, currentHeight)
3✔
1056
        }
3✔
1057

1058
        // For records that are failed, we'll notify the caller about this
1059
        // result.
1060
        for _, r := range failedRecords {
6✔
1061
                t.wg.Add(1)
3✔
1062
                go t.handleUnknownSpent(r)
3✔
1063
        }
3✔
1064
}
1065

1066
// handleTxConfirmed is called when a monitored tx is confirmed. It will
1067
// notify the subscriber then remove the record from the maps .
1068
//
1069
// NOTE: Must be run as a goroutine to avoid blocking on sending the result.
1070
func (t *TxPublisher) handleTxConfirmed(r *monitorRecord) {
3✔
1071
        defer t.wg.Done()
3✔
1072

3✔
1073
        log.Debugf("Record %v is spent in tx=%v", r.requestID, r.tx.TxHash())
3✔
1074

3✔
1075
        // Create a result that will be sent to the resultChan which is
3✔
1076
        // listened by the caller.
3✔
1077
        result := &BumpResult{
3✔
1078
                Event:     TxConfirmed,
3✔
1079
                Tx:        r.tx,
3✔
1080
                requestID: r.requestID,
3✔
1081
                Fee:       r.fee,
3✔
1082
                FeeRate:   r.feeFunction.FeeRate(),
3✔
1083
        }
3✔
1084

3✔
1085
        // Notify that this tx is confirmed and remove the record from the map.
3✔
1086
        t.handleResult(result)
3✔
1087
}
3✔
1088

1089
// handleInitialTxError takes the error from `initializeTx` and decides the
1090
// bump event. It will construct a BumpResult and handles it.
1091
func (t *TxPublisher) handleInitialTxError(r *monitorRecord, err error) {
3✔
1092
        // Create a bump result to be sent to the sweeper.
3✔
1093
        result := &BumpResult{
3✔
1094
                Err:       err,
3✔
1095
                requestID: r.requestID,
3✔
1096
        }
3✔
1097

3✔
1098
        // We now decide what type of event to send.
3✔
1099
        switch {
3✔
1100
        // When the error is due to a dust output, we'll send a TxFailed so
1101
        // these inputs can be retried with a different group in the next
1102
        // block.
1103
        case errors.Is(err, ErrTxNoOutput):
3✔
1104
                result.Event = TxFailed
3✔
1105

1106
        // When the error is due to zero fee rate delta, we'll send a TxFailed
1107
        // so these inputs can be retried in the next block.
1108
        case errors.Is(err, ErrZeroFeeRateDelta):
3✔
1109
                result.Event = TxFailed
3✔
1110

1111
        // When the error is due to budget being used up, we'll send a TxFailed
1112
        // so these inputs can be retried with a different group in the next
1113
        // block.
1114
        case errors.Is(err, ErrMaxPosition):
2✔
1115
                fallthrough
2✔
1116

1117
        // If the tx doesn't not have enough budget, or if the inputs amounts
1118
        // are not sufficient to cover the budget, we will return a TxFailed
1119
        // event so the sweeper can handle it by re-clustering the utxos.
1120
        case errors.Is(err, ErrNotEnoughInputs),
1121
                errors.Is(err, ErrNotEnoughBudget):
2✔
1122

2✔
1123
                result.Event = TxFailed
2✔
1124

2✔
1125
                // Calculate the starting fee rate to be used when retry
2✔
1126
                // sweeping these inputs.
2✔
1127
                feeRate, err := t.calculateRetryFeeRate(r)
2✔
1128
                if err != nil {
2✔
1129
                        result.Event = TxFatal
×
1130
                        result.Err = err
×
1131
                }
×
1132

1133
                // Attach the new fee rate.
1134
                result.FeeRate = feeRate
2✔
1135

1136
        // When there are missing inputs, we'll create a TxUnknownSpend bump
1137
        // result here so the rest of the inputs can be retried.
1138
        case errors.Is(err, ErrInputMissing):
2✔
1139
                result = t.handleMissingInputs(r)
2✔
1140

1141
        // Otherwise this is not a fee-related error and the tx cannot be
1142
        // retried. In that case we will fail ALL the inputs in this tx, which
1143
        // means they will be removed from the sweeper and never be tried
1144
        // again.
1145
        //
1146
        // TODO(yy): Find out which input is causing the failure and fail that
1147
        // one only.
UNCOV
1148
        default:
×
UNCOV
1149
                result.Event = TxFatal
×
1150
        }
1151

1152
        t.handleResult(result)
3✔
1153
}
1154

1155
// handleInitialBroadcast is called when a new request is received. It will
1156
// handle the initial tx creation and broadcast. In details,
1157
// 1. init a fee function based on the given strategy.
1158
// 2. create an RBF-compliant tx and monitor it for confirmation.
1159
// 3. notify the initial broadcast result back to the caller.
1160
func (t *TxPublisher) handleInitialBroadcast(r *monitorRecord) {
3✔
1161
        log.Debugf("Initial broadcast for requestID=%v", r.requestID)
3✔
1162

3✔
1163
        var (
3✔
1164
                result *BumpResult
3✔
1165
                err    error
3✔
1166
        )
3✔
1167

3✔
1168
        // Attempt an initial broadcast which is guaranteed to comply with the
3✔
1169
        // RBF rules.
3✔
1170
        //
3✔
1171
        // Create the initial tx to be broadcasted.
3✔
1172
        record, err := t.initializeTx(r)
3✔
1173
        if err != nil {
6✔
1174
                log.Errorf("Initial broadcast failed: %v", err)
3✔
1175

3✔
1176
                // We now handle the initialization error and exit.
3✔
1177
                t.handleInitialTxError(r, err)
3✔
1178

3✔
1179
                return
3✔
1180
        }
3✔
1181

1182
        // Successfully created the first tx, now broadcast it.
1183
        result, err = t.broadcast(record)
3✔
1184
        if err != nil {
3✔
1185
                // The broadcast failed, which can only happen if the tx record
×
1186
                // cannot be found or the aux sweeper returns an error. In
×
1187
                // either case, we will send back a TxFail event so these
×
1188
                // inputs can be retried.
×
1189
                result = &BumpResult{
×
1190
                        Event:     TxFailed,
×
1191
                        Err:       err,
×
1192
                        requestID: r.requestID,
×
1193
                }
×
1194
        }
×
1195

1196
        t.handleResult(result)
3✔
1197
}
1198

1199
// handleFeeBumpTx checks if the tx needs to be bumped, and if so, it will
1200
// attempt to bump the fee of the tx.
1201
//
1202
// NOTE: Must be run as a goroutine to avoid blocking on sending the result.
1203
func (t *TxPublisher) handleFeeBumpTx(r *monitorRecord, currentHeight int32) {
3✔
1204
        defer t.wg.Done()
3✔
1205

3✔
1206
        log.Debugf("Attempting to fee bump tx=%v in record %v", r.tx.TxHash(),
3✔
1207
                r.requestID)
3✔
1208

3✔
1209
        oldTxid := r.tx.TxHash()
3✔
1210

3✔
1211
        // Get the current conf target for this record.
3✔
1212
        confTarget := calcCurrentConfTarget(currentHeight, r.req.DeadlineHeight)
3✔
1213

3✔
1214
        // Ask the fee function whether a bump is needed. We expect the fee
3✔
1215
        // function to increase its returned fee rate after calling this
3✔
1216
        // method.
3✔
1217
        increased, err := r.feeFunction.IncreaseFeeRate(confTarget)
3✔
1218
        if err != nil {
6✔
1219
                // TODO(yy): send this error back to the sweeper so it can
3✔
1220
                // re-group the inputs?
3✔
1221
                log.Errorf("Failed to increase fee rate for tx %v at "+
3✔
1222
                        "height=%v: %v", oldTxid, t.currentHeight.Load(), err)
3✔
1223

3✔
1224
                return
3✔
1225
        }
3✔
1226

1227
        // If the fee rate was not increased, there's no need to bump the fee.
1228
        if !increased {
3✔
UNCOV
1229
                log.Tracef("Skip bumping tx %v at height=%v", oldTxid,
×
UNCOV
1230
                        t.currentHeight.Load())
×
UNCOV
1231

×
UNCOV
1232
                return
×
UNCOV
1233
        }
×
1234

1235
        // The fee function now has a new fee rate, we will use it to bump the
1236
        // fee of the tx.
1237
        resultOpt := t.createAndPublishTx(r)
3✔
1238

3✔
1239
        // If there's a result, we will notify the caller about the result.
3✔
1240
        resultOpt.WhenSome(func(result BumpResult) {
6✔
1241
                // Notify the new result.
3✔
1242
                t.handleResult(&result)
3✔
1243
        })
3✔
1244
}
1245

1246
// handleUnknownSpent is called when the inputs are spent by a unknown tx. It
1247
// will notify the subscriber then remove the record from the maps and send a
1248
// TxUnknownSpend event to the subscriber.
1249
//
1250
// NOTE: Must be run as a goroutine to avoid blocking on sending the result.
1251
func (t *TxPublisher) handleUnknownSpent(r *monitorRecord) {
3✔
1252
        defer t.wg.Done()
3✔
1253

3✔
1254
        log.Debugf("Record %v has inputs spent by a tx unknown to the fee "+
3✔
1255
                "bumper, failing it now:\n%v", r.requestID,
3✔
1256
                inputTypeSummary(r.req.Inputs))
3✔
1257

3✔
1258
        // Create a result that will be sent to the resultChan which is listened
3✔
1259
        // by the caller.
3✔
1260
        result := t.createUnknownSpentBumpResult(r)
3✔
1261

3✔
1262
        // Notify the sweeper about this result in the end.
3✔
1263
        t.handleResult(result)
3✔
1264
}
3✔
1265

1266
// createUnknownSpentBumpResult creates and returns a BumpResult given the
1267
// monitored record has unknown spends.
1268
func (t *TxPublisher) createUnknownSpentBumpResult(
1269
        r *monitorRecord) *BumpResult {
3✔
1270

3✔
1271
        // Create a result that will be sent to the resultChan which is listened
3✔
1272
        // by the caller.
3✔
1273
        result := &BumpResult{
3✔
1274
                Event:       TxUnknownSpend,
3✔
1275
                Tx:          r.tx,
3✔
1276
                requestID:   r.requestID,
3✔
1277
                Err:         ErrUnknownSpent,
3✔
1278
                SpentInputs: r.spentInputs,
3✔
1279
        }
3✔
1280

3✔
1281
        // Calculate the next fee rate for the retry.
3✔
1282
        feeRate, err := t.calculateRetryFeeRate(r)
3✔
1283
        if err != nil {
3✔
UNCOV
1284
                // Overwrite the event and error so the sweeper will
×
UNCOV
1285
                // remove this input.
×
UNCOV
1286
                result.Event = TxFatal
×
UNCOV
1287
                result.Err = err
×
UNCOV
1288
        }
×
1289

1290
        // Attach the new fee rate to be used for the next sweeping attempt.
1291
        result.FeeRate = feeRate
3✔
1292

3✔
1293
        return result
3✔
1294
}
1295

1296
// createAndPublishTx creates a new tx with a higher fee rate and publishes it
1297
// to the network. It will update the record with the new tx and fee rate if
1298
// successfully created, and return the result when published successfully.
1299
func (t *TxPublisher) createAndPublishTx(
1300
        r *monitorRecord) fn.Option[BumpResult] {
3✔
1301

3✔
1302
        // Fetch the old tx.
3✔
1303
        oldTx := r.tx
3✔
1304

3✔
1305
        // Create a new tx with the new fee rate.
3✔
1306
        //
3✔
1307
        // NOTE: The fee function is expected to have increased its returned
3✔
1308
        // fee rate after calling the SkipFeeBump method. So we can use it
3✔
1309
        // directly here.
3✔
1310
        sweepCtx, err := t.createAndCheckTx(r)
3✔
1311

3✔
1312
        // If there's an error creating the replacement tx, we need to abort the
3✔
1313
        // flow and handle it.
3✔
1314
        if err != nil {
6✔
1315
                return t.handleReplacementTxError(r, oldTx, err)
3✔
1316
        }
3✔
1317

1318
        // The tx has been created without any errors, we now register a new
1319
        // record by overwriting the same requestID.
1320
        record := t.updateRecord(r, sweepCtx)
3✔
1321

3✔
1322
        // Attempt to broadcast this new tx.
3✔
1323
        result, err := t.broadcast(record)
3✔
1324
        if err != nil {
3✔
1325
                log.Infof("Failed to broadcast replacement tx %v: %v",
×
1326
                        sweepCtx.tx.TxHash(), err)
×
1327

×
1328
                return fn.None[BumpResult]()
×
1329
        }
×
1330

1331
        // If the result error is fee related, we will return no error and let
1332
        // the fee bumper retry it at next block.
1333
        //
1334
        // NOTE: we may get this error if we've bypassed the mempool check,
1335
        // which means we are suing neutrino backend.
1336
        if errors.Is(result.Err, chain.ErrInsufficientFee) ||
3✔
1337
                errors.Is(result.Err, lnwallet.ErrMempoolFee) {
5✔
1338

2✔
1339
                log.Debugf("Failed to bump tx %v: %v", oldTx.TxHash(),
2✔
1340
                        result.Err)
2✔
1341

2✔
1342
                return fn.None[BumpResult]()
2✔
1343
        }
2✔
1344

1345
        // A successful replacement tx is created, attach the old tx.
1346
        result.ReplacedTx = oldTx
3✔
1347

3✔
1348
        // If the new tx failed to be published, we will return the result so
3✔
1349
        // the caller can handle it.
3✔
1350
        if result.Event == TxFailed {
3✔
UNCOV
1351
                return fn.Some(*result)
×
UNCOV
1352
        }
×
1353

1354
        log.Debugf("Replaced tx=%v with new tx=%v", oldTx.TxHash(),
3✔
1355
                sweepCtx.tx.TxHash())
3✔
1356

3✔
1357
        // Otherwise, it's a successful RBF, set the event and return.
3✔
1358
        result.Event = TxReplaced
3✔
1359

3✔
1360
        return fn.Some(*result)
3✔
1361
}
1362

1363
// isUnknownSpent checks whether the inputs of the tx has already been spent by
1364
// a tx not known to us. When a tx is not confirmed, yet its inputs has been
1365
// spent, then it must be spent by a different tx other than the sweeping tx
1366
// here.
1367
func (t *TxPublisher) isUnknownSpent(r *monitorRecord,
1368
        spends map[wire.OutPoint]*wire.MsgTx) bool {
3✔
1369

3✔
1370
        txid := r.tx.TxHash()
3✔
1371

3✔
1372
        // Iterate all the spending txns and check if they match the sweeping
3✔
1373
        // tx.
3✔
1374
        for op, spendingTx := range spends {
6✔
1375
                spendingTxID := spendingTx.TxHash()
3✔
1376

3✔
1377
                // If the spending tx is the same as the sweeping tx then we are
3✔
1378
                // good.
3✔
1379
                if spendingTxID == txid {
6✔
1380
                        continue
3✔
1381
                }
1382

1383
                log.Warnf("Detected unknown spend of input=%v in tx=%v", op,
3✔
1384
                        spendingTx.TxHash())
3✔
1385

3✔
1386
                return true
3✔
1387
        }
1388

1389
        return false
3✔
1390
}
1391

1392
// getSpentInputs performs a non-blocking read on the spending subscriptions to
1393
// see whether any of the monitored inputs has been spent. A map of inputs with
1394
// their spending txns are returned if found.
1395
func (t *TxPublisher) getSpentInputs(
1396
        r *monitorRecord) map[wire.OutPoint]*wire.MsgTx {
3✔
1397

3✔
1398
        // Create a slice to record the inputs spent.
3✔
1399
        spentInputs := make(map[wire.OutPoint]*wire.MsgTx, len(r.req.Inputs))
3✔
1400

3✔
1401
        // Iterate all the inputs and check if they have been spent already.
3✔
1402
        for _, inp := range r.req.Inputs {
6✔
1403
                op := inp.OutPoint()
3✔
1404

3✔
1405
                // For wallet utxos, the height hint is not set - we don't need
3✔
1406
                // to monitor them for third party spend.
3✔
1407
                //
3✔
1408
                // TODO(yy): We need to properly lock wallet utxos before
3✔
1409
                // skipping this check as the same wallet utxo can be used by
3✔
1410
                // different sweeping txns.
3✔
1411
                heightHint := inp.HeightHint()
3✔
1412
                if heightHint == 0 {
6✔
1413
                        heightHint = uint32(t.currentHeight.Load())
3✔
1414
                        log.Debugf("Checking wallet input %v using heightHint "+
3✔
1415
                                "%v", op, heightHint)
3✔
1416
                }
3✔
1417

1418
                // If the input has already been spent after the height hint, a
1419
                // spend event is sent back immediately.
1420
                spendEvent, err := t.cfg.Notifier.RegisterSpendNtfn(
3✔
1421
                        &op, inp.SignDesc().Output.PkScript, heightHint,
3✔
1422
                )
3✔
1423
                if err != nil {
3✔
1424
                        log.Criticalf("Failed to register spend ntfn for "+
×
1425
                                "input=%v: %v", op, err)
×
1426

×
1427
                        return nil
×
1428
                }
×
1429

1430
                // Remove the subscription when exit.
1431
                defer spendEvent.Cancel()
3✔
1432

3✔
1433
                // Do a non-blocking read to see if the output has been spent.
3✔
1434
                select {
3✔
1435
                case spend, ok := <-spendEvent.Spend:
3✔
1436
                        if !ok {
3✔
1437
                                log.Debugf("Spend ntfn for %v canceled", op)
×
1438

×
1439
                                continue
×
1440
                        }
1441

1442
                        spendingTx := spend.SpendingTx
3✔
1443

3✔
1444
                        log.Debugf("Detected spent of input=%v in tx=%v", op,
3✔
1445
                                spendingTx.TxHash())
3✔
1446

3✔
1447
                        spentInputs[op] = spendingTx
3✔
1448

1449
                // Move to the next input.
1450
                default:
3✔
1451
                        log.Tracef("Input %v not spent yet", op)
3✔
1452
                }
1453
        }
1454

1455
        return spentInputs
3✔
1456
}
1457

1458
// calcCurrentConfTarget calculates the current confirmation target based on
1459
// the deadline height. The conf target is capped at 0 if the deadline has
1460
// already been past.
1461
func calcCurrentConfTarget(currentHeight, deadline int32) uint32 {
3✔
1462
        var confTarget uint32
3✔
1463

3✔
1464
        // Calculate how many blocks left until the deadline.
3✔
1465
        deadlineDelta := deadline - currentHeight
3✔
1466

3✔
1467
        // If we are already past the deadline, we will set the conf target to
3✔
1468
        // be 1.
3✔
1469
        if deadlineDelta < 0 {
6✔
1470
                log.Warnf("Deadline is %d blocks behind current height %v",
3✔
1471
                        -deadlineDelta, currentHeight)
3✔
1472

3✔
1473
                confTarget = 0
3✔
1474
        } else {
6✔
1475
                confTarget = uint32(deadlineDelta)
3✔
1476
        }
3✔
1477

1478
        return confTarget
3✔
1479
}
1480

1481
// sweepTxCtx houses a sweep transaction with additional context.
1482
type sweepTxCtx struct {
1483
        tx *wire.MsgTx
1484

1485
        fee btcutil.Amount
1486

1487
        extraTxOut fn.Option[SweepOutput]
1488

1489
        // outpointToTxIndex maps the outpoint of the inputs to their index in
1490
        // the sweep transaction.
1491
        outpointToTxIndex map[wire.OutPoint]int
1492
}
1493

1494
// createSweepTx creates a sweeping tx based on the given inputs, change
1495
// address and fee rate.
1496
func (t *TxPublisher) createSweepTx(inputs []input.Input,
1497
        changePkScript lnwallet.AddrWithKey,
1498
        feeRate chainfee.SatPerKWeight) (*sweepTxCtx, error) {
3✔
1499

3✔
1500
        // Validate and calculate the fee and change amount.
3✔
1501
        txFee, changeOutputsOpt, locktimeOpt, err := prepareSweepTx(
3✔
1502
                inputs, changePkScript, feeRate, t.currentHeight.Load(),
3✔
1503
                t.cfg.AuxSweeper,
3✔
1504
        )
3✔
1505
        if err != nil {
6✔
1506
                return nil, err
3✔
1507
        }
3✔
1508

1509
        var (
3✔
1510
                // Create the sweep transaction that we will be building. We
3✔
1511
                // use version 2 as it is required for CSV.
3✔
1512
                sweepTx = wire.NewMsgTx(2)
3✔
1513

3✔
1514
                // We'll add the inputs as we go so we know the final ordering
3✔
1515
                // of inputs to sign.
3✔
1516
                idxs []input.Input
3✔
1517
        )
3✔
1518

3✔
1519
        // We start by adding all inputs that commit to an output. We do this
3✔
1520
        // since the input and output index must stay the same for the
3✔
1521
        // signatures to be valid.
3✔
1522
        outpointToTxIndex := make(map[wire.OutPoint]int)
3✔
1523
        for _, o := range inputs {
6✔
1524
                if o.RequiredTxOut() == nil {
6✔
1525
                        continue
3✔
1526
                }
1527

1528
                idxs = append(idxs, o)
3✔
1529
                sweepTx.AddTxIn(&wire.TxIn{
3✔
1530
                        PreviousOutPoint: o.OutPoint(),
3✔
1531
                        Sequence:         o.BlocksToMaturity(),
3✔
1532
                })
3✔
1533
                sweepTx.AddTxOut(o.RequiredTxOut())
3✔
1534

3✔
1535
                outpointToTxIndex[o.OutPoint()] = len(sweepTx.TxOut) - 1
3✔
1536
        }
1537

1538
        // Sum up the value contained in the remaining inputs, and add them to
1539
        // the sweep transaction.
1540
        for _, o := range inputs {
6✔
1541
                if o.RequiredTxOut() != nil {
6✔
1542
                        continue
3✔
1543
                }
1544

1545
                idxs = append(idxs, o)
3✔
1546
                sweepTx.AddTxIn(&wire.TxIn{
3✔
1547
                        PreviousOutPoint: o.OutPoint(),
3✔
1548
                        Sequence:         o.BlocksToMaturity(),
3✔
1549
                })
3✔
1550
        }
1551

1552
        // If we have change outputs to add, then add it the sweep transaction
1553
        // here.
1554
        changeOutputsOpt.WhenSome(func(changeOuts []SweepOutput) {
6✔
1555
                for i := range changeOuts {
6✔
1556
                        sweepTx.AddTxOut(&changeOuts[i].TxOut)
3✔
1557
                }
3✔
1558
        })
1559

1560
        // We'll default to using the current block height as locktime, if none
1561
        // of the inputs commits to a different locktime.
1562
        sweepTx.LockTime = uint32(locktimeOpt.UnwrapOr(t.currentHeight.Load()))
3✔
1563

3✔
1564
        prevInputFetcher, err := input.MultiPrevOutFetcher(inputs)
3✔
1565
        if err != nil {
3✔
1566
                return nil, fmt.Errorf("error creating prev input fetcher "+
×
1567
                        "for hash cache: %v", err)
×
1568
        }
×
1569
        hashCache := txscript.NewTxSigHashes(sweepTx, prevInputFetcher)
3✔
1570

3✔
1571
        // With all the inputs in place, use each output's unique input script
3✔
1572
        // function to generate the final witness required for spending.
3✔
1573
        addInputScript := func(idx int, tso input.Input) error {
6✔
1574
                inputScript, err := tso.CraftInputScript(
3✔
1575
                        t.cfg.Signer, sweepTx, hashCache, prevInputFetcher, idx,
3✔
1576
                )
3✔
1577
                if err != nil {
3✔
1578
                        return err
×
1579
                }
×
1580

1581
                sweepTx.TxIn[idx].Witness = inputScript.Witness
3✔
1582

3✔
1583
                if len(inputScript.SigScript) == 0 {
6✔
1584
                        return nil
3✔
1585
                }
3✔
1586

1587
                sweepTx.TxIn[idx].SignatureScript = inputScript.SigScript
×
1588

×
1589
                return nil
×
1590
        }
1591

1592
        for idx, inp := range idxs {
6✔
1593
                if err := addInputScript(idx, inp); err != nil {
3✔
1594
                        return nil, err
×
1595
                }
×
1596
        }
1597

1598
        log.Debugf("Created sweep tx %v for inputs:\n%v", sweepTx.TxHash(),
3✔
1599
                inputTypeSummary(inputs))
3✔
1600

3✔
1601
        // Try to locate the extra change output, though there might be None.
3✔
1602
        extraTxOut := fn.MapOption(
3✔
1603
                func(sweepOuts []SweepOutput) fn.Option[SweepOutput] {
6✔
1604
                        for _, sweepOut := range sweepOuts {
6✔
1605
                                if !sweepOut.IsExtra {
6✔
1606
                                        continue
3✔
1607
                                }
1608

1609
                                // If we sweep outputs of a custom channel, the
1610
                                // custom leaves in those outputs will be merged
1611
                                // into a single output, even if we sweep
1612
                                // multiple outputs (e.g. to_remote and breached
1613
                                // to_local of a breached channel) at the same
1614
                                // time. So there will only ever be one extra
1615
                                // output.
1616
                                log.Debugf("Sweep produced extra_sweep_out=%v",
×
1617
                                        lnutils.SpewLogClosure(sweepOut))
×
1618

×
1619
                                return fn.Some(sweepOut)
×
1620
                        }
1621

1622
                        return fn.None[SweepOutput]()
3✔
1623
                },
1624
        )(changeOutputsOpt)
1625

1626
        return &sweepTxCtx{
3✔
1627
                tx:                sweepTx,
3✔
1628
                fee:               txFee,
3✔
1629
                extraTxOut:        fn.FlattenOption(extraTxOut),
3✔
1630
                outpointToTxIndex: outpointToTxIndex,
3✔
1631
        }, nil
3✔
1632
}
1633

1634
// prepareSweepTx returns the tx fee, a set of optional change outputs and an
1635
// optional locktime after a series of validations:
1636
// 1. check the locktime has been reached.
1637
// 2. check the locktimes are the same.
1638
// 3. check the inputs cover the outputs.
1639
//
1640
// NOTE: if the change amount is below dust, it will be added to the tx fee.
1641
func prepareSweepTx(inputs []input.Input, changePkScript lnwallet.AddrWithKey,
1642
        feeRate chainfee.SatPerKWeight, currentHeight int32,
1643
        auxSweeper fn.Option[AuxSweeper]) (
1644
        btcutil.Amount, fn.Option[[]SweepOutput], fn.Option[int32], error) {
3✔
1645

3✔
1646
        noChange := fn.None[[]SweepOutput]()
3✔
1647
        noLocktime := fn.None[int32]()
3✔
1648

3✔
1649
        // Given the set of inputs we have, if we have an aux sweeper, then
3✔
1650
        // we'll attempt to see if we have any other change outputs we'll need
3✔
1651
        // to add to the sweep transaction.
3✔
1652
        changePkScripts := [][]byte{changePkScript.DeliveryAddress}
3✔
1653

3✔
1654
        var extraChangeOut fn.Option[SweepOutput]
3✔
1655
        err := fn.MapOptionZ(
3✔
1656
                auxSweeper, func(aux AuxSweeper) error {
3✔
UNCOV
1657
                        extraOut := aux.DeriveSweepAddr(inputs, changePkScript)
×
UNCOV
1658
                        if err := extraOut.Err(); err != nil {
×
1659
                                return err
×
1660
                        }
×
1661

UNCOV
1662
                        extraChangeOut = extraOut.LeftToSome()
×
UNCOV
1663

×
UNCOV
1664
                        return nil
×
1665
                },
1666
        )
1667
        if err != nil {
3✔
1668
                return 0, noChange, noLocktime, err
×
1669
        }
×
1670

1671
        // Creating a weight estimator with nil outputs and zero max fee rate.
1672
        // We don't allow adding customized outputs in the sweeping tx, and the
1673
        // fee rate is already being managed before we get here.
1674
        inputs, estimator, err := getWeightEstimate(
3✔
1675
                inputs, nil, feeRate, 0, changePkScripts,
3✔
1676
        )
3✔
1677
        if err != nil {
3✔
1678
                return 0, noChange, noLocktime, err
×
1679
        }
×
1680

1681
        txFee := estimator.fee()
3✔
1682

3✔
1683
        var (
3✔
1684
                // Track whether any of the inputs require a certain locktime.
3✔
1685
                locktime = int32(-1)
3✔
1686

3✔
1687
                // We keep track of total input amount, and required output
3✔
1688
                // amount to use for calculating the change amount below.
3✔
1689
                totalInput     btcutil.Amount
3✔
1690
                requiredOutput btcutil.Amount
3✔
1691
        )
3✔
1692

3✔
1693
        // If we have an extra change output, then we'll add it as a required
3✔
1694
        // output amt.
3✔
1695
        extraChangeOut.WhenSome(func(o SweepOutput) {
3✔
UNCOV
1696
                requiredOutput += btcutil.Amount(o.Value)
×
UNCOV
1697
        })
×
1698

1699
        // Go through each input and check if the required lock times have
1700
        // reached and are the same.
1701
        for _, o := range inputs {
6✔
1702
                // If the input has a required output, we'll add it to the
3✔
1703
                // required output amount.
3✔
1704
                if o.RequiredTxOut() != nil {
6✔
1705
                        requiredOutput += btcutil.Amount(
3✔
1706
                                o.RequiredTxOut().Value,
3✔
1707
                        )
3✔
1708
                }
3✔
1709

1710
                // Update the total input amount.
1711
                totalInput += btcutil.Amount(o.SignDesc().Output.Value)
3✔
1712

3✔
1713
                lt, ok := o.RequiredLockTime()
3✔
1714

3✔
1715
                // Skip if the input doesn't require a lock time.
3✔
1716
                if !ok {
6✔
1717
                        continue
3✔
1718
                }
1719

1720
                // Check if the lock time has reached
1721
                if lt > uint32(currentHeight) {
3✔
1722
                        return 0, noChange, noLocktime,
×
1723
                                fmt.Errorf("%w: current height is %v, "+
×
1724
                                        "locktime is %v", ErrLocktimeImmature,
×
1725
                                        currentHeight, lt)
×
1726
                }
×
1727

1728
                // If another input commits to a different locktime, they
1729
                // cannot be combined in the same transaction.
1730
                if locktime != -1 && locktime != int32(lt) {
3✔
1731
                        return 0, noChange, noLocktime, ErrLocktimeConflict
×
1732
                }
×
1733

1734
                // Update the locktime for next iteration.
1735
                locktime = int32(lt)
3✔
1736
        }
1737

1738
        // Make sure total output amount is less than total input amount.
1739
        if requiredOutput+txFee > totalInput {
6✔
1740
                log.Errorf("Insufficient input to create sweep tx: "+
3✔
1741
                        "input_sum=%v, output_sum=%v", totalInput,
3✔
1742
                        requiredOutput+txFee)
3✔
1743

3✔
1744
                return 0, noChange, noLocktime, ErrNotEnoughInputs
3✔
1745
        }
3✔
1746

1747
        // The value remaining after the required output and fees is the
1748
        // change output.
1749
        changeAmt := totalInput - requiredOutput - txFee
3✔
1750
        changeOuts := make([]SweepOutput, 0, 2)
3✔
1751

3✔
1752
        extraChangeOut.WhenSome(func(o SweepOutput) {
3✔
UNCOV
1753
                changeOuts = append(changeOuts, o)
×
UNCOV
1754
        })
×
1755

1756
        // We'll calculate the dust limit for the given changePkScript since it
1757
        // is variable.
1758
        changeFloor := lnwallet.DustLimitForSize(
3✔
1759
                len(changePkScript.DeliveryAddress),
3✔
1760
        )
3✔
1761

3✔
1762
        switch {
3✔
1763
        // If the change amount is dust, we'll move it into the fees, and
1764
        // ignore it.
1765
        case changeAmt < changeFloor:
3✔
1766
                log.Infof("Change amt %v below dustlimit %v, not adding "+
3✔
1767
                        "change output", changeAmt, changeFloor)
3✔
1768

3✔
1769
                // If there's no required output, and the change output is a
3✔
1770
                // dust, it means we are creating a tx without any outputs. In
3✔
1771
                // this case we'll return an error. This could happen when
3✔
1772
                // creating a tx that has an anchor as the only input.
3✔
1773
                if requiredOutput == 0 {
6✔
1774
                        return 0, noChange, noLocktime, ErrTxNoOutput
3✔
1775
                }
3✔
1776

1777
                // The dust amount is added to the fee.
1778
                txFee += changeAmt
×
1779

1780
        // Otherwise, we'll actually recognize it as a change output.
1781
        default:
3✔
1782
                changeOuts = append(changeOuts, SweepOutput{
3✔
1783
                        TxOut: wire.TxOut{
3✔
1784
                                Value:    int64(changeAmt),
3✔
1785
                                PkScript: changePkScript.DeliveryAddress,
3✔
1786
                        },
3✔
1787
                        IsExtra:     false,
3✔
1788
                        InternalKey: changePkScript.InternalKey,
3✔
1789
                })
3✔
1790
        }
1791

1792
        // Optionally set the locktime.
1793
        locktimeOpt := fn.Some(locktime)
3✔
1794
        if locktime == -1 {
6✔
1795
                locktimeOpt = noLocktime
3✔
1796
        }
3✔
1797

1798
        var changeOutsOpt fn.Option[[]SweepOutput]
3✔
1799
        if len(changeOuts) > 0 {
6✔
1800
                changeOutsOpt = fn.Some(changeOuts)
3✔
1801
        }
3✔
1802

1803
        log.Debugf("Creating sweep tx for %v inputs (%s) using %v, "+
3✔
1804
                "tx_weight=%v, tx_fee=%v, locktime=%v, parents_count=%v, "+
3✔
1805
                "parents_fee=%v, parents_weight=%v, current_height=%v",
3✔
1806
                len(inputs), inputTypeSummary(inputs), feeRate,
3✔
1807
                estimator.weight(), txFee, locktimeOpt, len(estimator.parents),
3✔
1808
                estimator.parentsFee, estimator.parentsWeight, currentHeight)
3✔
1809

3✔
1810
        return txFee, changeOutsOpt, locktimeOpt, nil
3✔
1811
}
1812

1813
// handleReplacementTxError handles the error returned from creating the
1814
// replacement tx. It returns a BumpResult that should be notified to the
1815
// sweeper.
1816
func (t *TxPublisher) handleReplacementTxError(r *monitorRecord,
1817
        oldTx *wire.MsgTx, err error) fn.Option[BumpResult] {
3✔
1818

3✔
1819
        // If the error is fee related, we will return no error and let the fee
3✔
1820
        // bumper retry it at next block.
3✔
1821
        //
3✔
1822
        // NOTE: we can check the RBF error here and ask the fee function to
3✔
1823
        // recalculate the fee rate. However, this would defeat the purpose of
3✔
1824
        // using a deadline based fee function:
3✔
1825
        // - if the deadline is far away, there's no rush to RBF the tx.
3✔
1826
        // - if the deadline is close, we expect the fee function to give us a
3✔
1827
        //   higher fee rate. If the fee rate cannot satisfy the RBF rules, it
3✔
1828
        //   means the budget is not enough.
3✔
1829
        if errors.Is(err, chain.ErrInsufficientFee) ||
3✔
1830
                errors.Is(err, lnwallet.ErrMempoolFee) {
5✔
1831

2✔
1832
                log.Debugf("Failed to bump tx %v: %v", oldTx.TxHash(), err)
2✔
1833
                return fn.None[BumpResult]()
2✔
1834
        }
2✔
1835

1836
        // At least one of the inputs is missing, which means it has already
1837
        // been spent by another tx and confirmed. In this case we will handle
1838
        // it by returning a TxUnknownSpend bump result.
1839
        if errors.Is(err, ErrInputMissing) {
3✔
1840
                log.Warnf("Fail to fee bump tx %v: %v", oldTx.TxHash(), err)
×
1841
                bumpResult := t.handleMissingInputs(r)
×
1842

×
1843
                return fn.Some(*bumpResult)
×
1844
        }
×
1845

1846
        // Return a failed event to retry the sweep.
1847
        event := TxFailed
3✔
1848

3✔
1849
        // Calculate the next fee rate for the retry.
3✔
1850
        feeRate, ferr := t.calculateRetryFeeRate(r)
3✔
1851
        if ferr != nil {
3✔
1852
                // If there's an error with the fee calculation, we need to
×
1853
                // abort the sweep.
×
1854
                event = TxFatal
×
1855
        }
×
1856

1857
        // If the error is not fee related, we will return a `TxFailed` event so
1858
        // this input can be retried.
1859
        result := fn.Some(BumpResult{
3✔
1860
                Event:     event,
3✔
1861
                Tx:        oldTx,
3✔
1862
                Err:       err,
3✔
1863
                requestID: r.requestID,
3✔
1864
                FeeRate:   feeRate,
3✔
1865
        })
3✔
1866

3✔
1867
        // If the tx doesn't not have enough budget, or if the inputs amounts
3✔
1868
        // are not sufficient to cover the budget, we will return a result so
3✔
1869
        // the sweeper can handle it by re-clustering the utxos.
3✔
1870
        if errors.Is(err, ErrNotEnoughBudget) ||
3✔
1871
                errors.Is(err, ErrNotEnoughInputs) {
6✔
1872

3✔
1873
                log.Warnf("Fail to fee bump tx %v: %v", oldTx.TxHash(), err)
3✔
1874
                return result
3✔
1875
        }
3✔
1876

1877
        // Otherwise, an unexpected error occurred, we will log an error and let
1878
        // the sweeper retry the whole process.
1879
        log.Errorf("Failed to bump tx %v: %v", oldTx.TxHash(), err)
×
1880

×
1881
        return result
×
1882
}
1883

1884
// calculateRetryFeeRate calculates a new fee rate to be used as the starting
1885
// fee rate for the next sweep attempt if the inputs are to be retried. When the
1886
// fee function is nil it will be created here, and an error is returned if the
1887
// fee func cannot be initialized.
1888
func (t *TxPublisher) calculateRetryFeeRate(
1889
        r *monitorRecord) (chainfee.SatPerKWeight, error) {
3✔
1890

3✔
1891
        // Get the fee function, which will be used to decided the next fee rate
3✔
1892
        // to use if the sweeper decides to retry sweeping this input.
3✔
1893
        feeFunc := r.feeFunction
3✔
1894

3✔
1895
        // When the record is failed before the initial broadcast is attempted,
3✔
1896
        // it will have a nil fee func. In this case, we'll create the fee func
3✔
1897
        // here.
3✔
1898
        //
3✔
1899
        // NOTE: Since the current record is failed and will be deleted, we
3✔
1900
        // don't need to update the record on this fee function. We only need
3✔
1901
        // the fee rate data so the sweeper can pick up where we left off.
3✔
1902
        if feeFunc == nil {
4✔
1903
                f, err := t.initializeFeeFunction(r.req)
1✔
1904

1✔
1905
                // TODO(yy): The only error we would receive here is when the
1✔
1906
                // pkScript is not recognized by the weightEstimator. What we
1✔
1907
                // should do instead is to check the pkScript immediately after
1✔
1908
                // receiving a sweep request so we don't need to check it again,
1✔
1909
                // which will also save us from error checking from several
1✔
1910
                // callsites.
1✔
1911
                if err != nil {
1✔
UNCOV
1912
                        log.Errorf("Failed to create fee func for record %v: "+
×
UNCOV
1913
                                "%v", r.requestID, err)
×
UNCOV
1914

×
UNCOV
1915
                        return 0, err
×
UNCOV
1916
                }
×
1917

1918
                feeFunc = f
1✔
1919
        }
1920

1921
        // Since we failed to sweep the inputs, either the sweeping tx has been
1922
        // replaced by another party's tx, or the current output values cannot
1923
        // cover the budget, we missed this block window to increase its fee
1924
        // rate. To make sure the fee rate stays in the initial line, we now ask
1925
        // the fee function to give us the next fee rate as if the sweeping tx
1926
        // were RBFed. This new fee rate will be used as the starting fee rate
1927
        // if the upper system decides to continue sweeping the rest of the
1928
        // inputs.
1929
        _, err := feeFunc.Increment()
3✔
1930
        if err != nil {
6✔
1931
                // The fee function has reached its max position - nothing we
3✔
1932
                // can do here other than letting the user increase the budget.
3✔
1933
                log.Errorf("Failed to calculate the next fee rate for "+
3✔
1934
                        "Record(%v): %v", r.requestID, err)
3✔
1935
        }
3✔
1936

1937
        return feeFunc.FeeRate(), nil
3✔
1938
}
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