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

lightningnetwork / lnd / 18430412238

11 Oct 2025 02:05PM UTC coverage: 66.651% (-0.02%) from 66.669%
18430412238

push

github

web-flow
Merge pull request #10285 from Roasbeef/go-125-2

build: update CI+release version to Go 1.25.2

137239 of 205906 relevant lines covered (66.65%)

21327.95 hits per line

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

92.01
/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
        // sentinelEvent is used to check if an event is unknown.
115
        sentinelEvent
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 {
14✔
140
        return e >= sentinelEvent
14✔
141
}
14✔
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 gives 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) {
14✔
181
        // We'll want to know if we have any blobs, as we need to factor this
14✔
182
        // into the max fee rate for this bump request.
14✔
183
        hasBlobs := fn.Any(r.Inputs, func(i input.Input) bool {
27✔
184
                return fn.MapOptionZ(
13✔
185
                        i.ResolutionBlob(), func(b tlv.Blob) bool {
16✔
186
                                return len(b) > 0
3✔
187
                        },
3✔
188
                )
189
        })
190

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

14✔
195
        // If we have blobs, then we'll add an extra sweep addr for the size
14✔
196
        // estimate below. We know that these blobs will also always be based on
14✔
197
        // p2tr addrs.
14✔
198
        if hasBlobs {
14✔
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(
14✔
207
                r.Inputs, sweepAddrs,
14✔
208
        )
14✔
209
        if err != nil {
15✔
210
                return 0, err
1✔
211
        }
1✔
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)
13✔
219
        if maxFeeRateAllowed > r.MaxFeeRate {
19✔
220
                log.Debugf("Budget feerate %v exceeds MaxFeeRate %v, use "+
6✔
221
                        "MaxFeeRate instead, txWeight=%v", maxFeeRateAllowed,
6✔
222
                        r.MaxFeeRate, size)
6✔
223

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

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

10✔
230
        return maxFeeRateAllowed, nil
10✔
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) {
19✔
237

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

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

256
        return estimator.weight(), nil
17✔
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 {
15✔
300
        isFailureEvent := b.Event == TxFailed || b.Event == TxFatal ||
15✔
301
                b.Event == TxUnknownSpend
15✔
302

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

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

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

318
        // If it's a failed or fatal event, it must have an error.
319
        if isFailureEvent && b.Err == nil {
14✔
320
                return fmt.Errorf("%w: nil error", ErrInvalidBumpResult)
2✔
321
        }
2✔
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) {
11✔
325
                return fmt.Errorf("%w: missing fee rate or fee",
1✔
326
                        ErrInvalidBumpResult)
1✔
327
        }
1✔
328

329
        return nil
9✔
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 {
24✔
402
        tp := &TxPublisher{
24✔
403
                cfg:             &cfg,
24✔
404
                records:         lnutils.SyncMap[uint64, *monitorRecord]{},
24✔
405
                subscriberChans: lnutils.SyncMap[uint64, chan *BumpResult]{},
24✔
406
                quit:            make(chan struct{}),
24✔
407
        }
24✔
408

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

24✔
412
        return tp
24✔
413
}
24✔
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 {
8✔
427
        log.Tracef("Received broadcast request: %s",
8✔
428
                lnutils.SpewLogClosure(req))
8✔
429

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

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

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

442
        return subscriber
8✔
443
}
444

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

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

8✔
459
        return record
8✔
460
}
8✔
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 {
22✔
466

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

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

22✔
474
        return r
22✔
475
}
22✔
476

477
// NOTE: part of the `chainio.Consumer` interface.
478
func (t *TxPublisher) Name() string {
24✔
479
        return "TxPublisher"
24✔
480
}
24✔
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) {
8✔
485
        // Create a fee bumping algorithm to be used for future RBF.
8✔
486
        feeAlgo, err := t.initializeFeeFunction(r.req)
8✔
487
        if err != nil {
12✔
488
                return nil, fmt.Errorf("init fee function: %w", err)
4✔
489
        }
4✔
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
7✔
499

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

507
        return record, nil
6✔
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) {
11✔
514

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

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

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

11✔
530
        // Initialize the fee function and return it.
11✔
531
        //
11✔
532
        // TODO(yy): return based on differet req.Strategy?
11✔
533
        return NewLinearFeeFunction(
11✔
534
                maxFeeRateAllowed, confTarget, t.cfg.Estimator,
11✔
535
                req.StartingFeeRate,
11✔
536
        )
11✔
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) {
13✔
545

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

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

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

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

10✔
564
                        return record, nil
10✔
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.
568
                case errors.Is(err, lnwallet.ErrMempoolFee),
569
                        errors.Is(err, chain.ErrMinRelayFeeNotMet),
570
                        errors.Is(err, chain.ErrMempoolMinFeeNotMet):
2✔
571

2✔
572
                        // We should at least start with a feerate above the
2✔
573
                        // mempool min feerate, so if we get this error, it
2✔
574
                        // means something is wrong earlier in the pipeline.
2✔
575
                        log.Errorf("Current fee=%v, feerate=%v, %v",
2✔
576
                                sweepCtx.fee, f.FeeRate(), err)
2✔
577

2✔
578
                        fallthrough
2✔
579

580
                // We are not paying enough fees to RBF a previous tx, so we
581
                // increase it.
582
                case errors.Is(err, chain.ErrInsufficientFee):
6✔
583
                        increased := false
6✔
584

6✔
585
                        // Keep calling the fee function until the fee rate is
6✔
586
                        // increased or maxed out.
6✔
587
                        for !increased {
13✔
588
                                log.Debugf("Increasing fee for next round, "+
7✔
589
                                        "current fee=%v, feerate=%v",
7✔
590
                                        sweepCtx.fee, f.FeeRate())
7✔
591

7✔
592
                                // If the fee function tells us that we have
7✔
593
                                // used up the budget, we will return an error
7✔
594
                                // indicating this tx cannot be made. The
7✔
595
                                // sweeper should handle this error and try to
7✔
596
                                // cluster these inputs differently.
7✔
597
                                increased, err = f.Increment()
7✔
598
                                if err != nil {
10✔
599
                                        return nil, err
3✔
600
                                }
3✔
601
                        }
602

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

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

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

631
        // Sanity check the budget still covers the fee.
632
        if sweepCtx.fee > req.Budget {
28✔
633
                return sweepCtx, fmt.Errorf("%w: budget=%v, fee=%v",
2✔
634
                        ErrNotEnoughBudget, req.Budget, sweepCtx.fee)
2✔
635
        }
2✔
636

637
        // If we had an extra txOut, then we'll update the result to include
638
        // it.
639
        req.ExtraTxOut = sweepCtx.extraTxOut
24✔
640

24✔
641
        // Validate the tx's mempool acceptance.
24✔
642
        err = t.cfg.Wallet.CheckMempoolAcceptance(sweepCtx.tx)
24✔
643

24✔
644
        // Exit early if the tx is valid.
24✔
645
        if err == nil {
38✔
646
                return sweepCtx, nil
14✔
647
        }
14✔
648

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

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

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

2✔
670
                // Make sure to update the record with the latest attempt.
2✔
671
                t.updateRecord(r, sweepCtx)
2✔
672

2✔
673
                return sweepCtx, ErrInputMissing
2✔
674
        }
2✔
675

676
        return sweepCtx, fmt.Errorf("tx=%v failed mempool check: %w",
11✔
677
                sweepCtx.tx.TxHash(), err)
11✔
678
}
679

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

2✔
689
        // Attach the spending txns.
2✔
690
        r.spentInputs = spends
2✔
691

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

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

2✔
710
                return result
2✔
711
        }
2✔
712

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

723
        return t.createUnknownSpentBumpResult(r)
×
724
}
725

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

12✔
734
        tx := record.tx
12✔
735
        log.Debugf("Publishing sweep tx %v, num_inputs=%v, height=%v",
12✔
736
                txid, len(tx.TxIn), t.currentHeight.Load())
12✔
737

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

749
        // Set the event, and change it to TxFailed if the wallet fails to
750
        // publish it.
751
        event := TxPublished
12✔
752

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

772
        result := &BumpResult{
12✔
773
                Event:     event,
12✔
774
                Tx:        record.tx,
12✔
775
                Fee:       record.fee,
12✔
776
                FeeRate:   record.feeFunction.FeeRate(),
12✔
777
                Err:       err,
12✔
778
                requestID: record.requestID,
12✔
779
        }
12✔
780

12✔
781
        return result, nil
12✔
782
}
783

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

794
        log.Debugf("Sending result %v for requestID=%v", result, id)
17✔
795

17✔
796
        select {
17✔
797
        // Send the result to the subscriber.
798
        //
799
        // TODO(yy): Add timeout in case it's blocking?
800
        case subscriber <- result:
15✔
801
        case <-t.quit:
2✔
802
                log.Debug("Fee bumper stopped")
2✔
803
        }
804
}
805

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

17✔
812
        var txid chainhash.Hash
17✔
813
        if result.Tx != nil {
31✔
814
                txid = result.Tx.TxHash()
14✔
815
        }
14✔
816

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

828
        case TxConfirmed:
6✔
829
                // Remove the record if the tx is confirmed.
6✔
830
                log.Debugf("Removing confirmed monitor record=%v, tx=%v", id,
6✔
831
                        txid)
6✔
832

833
        case TxFatal:
4✔
834
                // Remove the record if there's an error.
4✔
835
                log.Debugf("Removing monitor record=%v due to fatal err: %v",
4✔
836
                        id, result.Err)
4✔
837

838
        case TxUnknownSpend:
5✔
839
                // Remove the record if there's an unknown spend.
5✔
840
                log.Debugf("Removing monitor record=%v due unknown spent: "+
5✔
841
                        "%v", id, result.Err)
5✔
842

843
        // Do nothing if it's neither failed or confirmed.
844
        default:
8✔
845
                log.Tracef("Skipping record removal for id=%v, event=%v", id,
8✔
846
                        result.Event)
8✔
847

8✔
848
                return
8✔
849
        }
850

851
        t.records.Delete(id)
12✔
852
        t.subscriberChans.Delete(id)
12✔
853
}
854

855
// handleResult handles the result of a tx broadcast. It will notify the
856
// subscriber and remove the record if the tx is confirmed or failed to be
857
// broadcast.
858
func (t *TxPublisher) handleResult(result *BumpResult) {
14✔
859
        // Notify the subscriber.
14✔
860
        t.notifyResult(result)
14✔
861

14✔
862
        // Remove the record if it's failed or confirmed.
14✔
863
        t.removeResult(result)
14✔
864
}
14✔
865

866
// monitorRecord is used to keep track of the tx being monitored by the
867
// publisher internally.
868
type monitorRecord struct {
869
        // requestID is the ID of the request that created this record.
870
        requestID uint64
871

872
        // tx is the tx being monitored.
873
        tx *wire.MsgTx
874

875
        // req is the original request.
876
        req *BumpRequest
877

878
        // feeFunction is the fee bumping algorithm used by the publisher.
879
        feeFunction FeeFunction
880

881
        // fee is the fee paid by the tx.
882
        fee btcutil.Amount
883

884
        // outpointToTxIndex is a map of outpoint to tx index.
885
        outpointToTxIndex map[wire.OutPoint]int
886

887
        // spentInputs are the inputs spent by another tx which caused the
888
        // current tx failed.
889
        spentInputs map[wire.OutPoint]*wire.MsgTx
890
}
891

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

3✔
897
        if t.started.Swap(true) {
3✔
898
                return fmt.Errorf("TxPublisher started more than once")
×
899
        }
×
900

901
        // Set the current height.
902
        t.currentHeight.Store(beat.Height())
3✔
903

3✔
904
        t.wg.Add(1)
3✔
905
        go t.monitor()
3✔
906

3✔
907
        log.Debugf("TxPublisher started")
3✔
908

3✔
909
        return nil
3✔
910
}
911

912
// Stop stops the publisher and waits for the monitor loop to exit.
913
func (t *TxPublisher) Stop() error {
3✔
914
        log.Info("TxPublisher stopping...")
3✔
915

3✔
916
        if t.stopped.Swap(true) {
3✔
917
                return fmt.Errorf("TxPublisher stopped more than once")
×
918
        }
×
919

920
        close(t.quit)
3✔
921
        t.wg.Wait()
3✔
922

3✔
923
        log.Debug("TxPublisher stopped")
3✔
924

3✔
925
        return nil
3✔
926
}
927

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

3✔
936
        for {
6✔
937
                select {
3✔
938
                case beat := <-t.BlockbeatChan:
3✔
939
                        height := beat.Height()
3✔
940
                        log.Debugf("TxPublisher received new block: %v", height)
3✔
941

3✔
942
                        // Update the best known height for the publisher.
3✔
943
                        t.currentHeight.Store(height)
3✔
944

3✔
945
                        // Check all monitored txns to see if any of them needs
3✔
946
                        // to be bumped.
3✔
947
                        t.processRecords()
3✔
948

3✔
949
                        // Notify we've processed the block.
3✔
950
                        t.NotifyBlockProcessed(beat, nil)
3✔
951

952
                case <-t.quit:
3✔
953
                        log.Debug("Fee bumper stopped, exit monitor")
3✔
954
                        return
3✔
955
                }
956
        }
957
}
958

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

8✔
966
        // feeBumpRecords stores a map of records which need to be bumped.
8✔
967
        feeBumpRecords := make(map[uint64]*monitorRecord)
8✔
968

8✔
969
        // failedRecords stores a map of records which has inputs being spent
8✔
970
        // by a third party.
8✔
971
        failedRecords := make(map[uint64]*monitorRecord)
8✔
972

8✔
973
        // initialRecords stores a map of records which are being created and
8✔
974
        // published for the first time.
8✔
975
        initialRecords := make(map[uint64]*monitorRecord)
8✔
976

8✔
977
        // visitor is a helper closure that visits each record and divides them
8✔
978
        // into two groups.
8✔
979
        visitor := func(requestID uint64, r *monitorRecord) error {
16✔
980
                log.Tracef("Checking monitor recordID=%v", requestID)
8✔
981

8✔
982
                // Check whether the inputs have already been spent.
8✔
983
                spends := t.getSpentInputs(r)
8✔
984

8✔
985
                // If the any of the inputs has been spent, the record will be
8✔
986
                // marked as failed or confirmed.
8✔
987
                if len(spends) != 0 {
14✔
988
                        // Attach the spending txns.
6✔
989
                        r.spentInputs = spends
6✔
990

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

1004
                        // Check whether the inputs has been spent by a unknown
1005
                        // tx.
1006
                        if t.isUnknownSpent(r, spends) {
9✔
1007
                                failedRecords[requestID] = r
4✔
1008

4✔
1009
                                // Move to the next record.
4✔
1010
                                return nil
4✔
1011
                        }
4✔
1012

1013
                        // The tx is ours, we can move it to the confirmed queue
1014
                        // and stop monitoring it.
1015
                        confirmedRecords[requestID] = r
4✔
1016

4✔
1017
                        // Move to the next record.
4✔
1018
                        return nil
4✔
1019
                }
1020

1021
                // This is the first time we see this record, so we put it in
1022
                // the initial queue.
1023
                if r.tx == nil {
9✔
1024
                        initialRecords[requestID] = r
4✔
1025

4✔
1026
                        return nil
4✔
1027
                }
4✔
1028

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

4✔
1034
                // Return nil to move to the next record.
4✔
1035
                return nil
4✔
1036
        }
1037

1038
        // Iterate through all the records and divide them into four groups.
1039
        t.records.ForEach(visitor)
8✔
1040

8✔
1041
        // Handle the initial broadcast.
8✔
1042
        for _, r := range initialRecords {
12✔
1043
                t.handleInitialBroadcast(r)
4✔
1044
        }
4✔
1045

1046
        // For records that are confirmed, we'll notify the caller about this
1047
        // result.
1048
        for _, r := range confirmedRecords {
12✔
1049
                t.wg.Add(1)
4✔
1050
                go t.handleTxConfirmed(r)
4✔
1051
        }
4✔
1052

1053
        // Get the current height to be used in the following goroutines.
1054
        currentHeight := t.currentHeight.Load()
8✔
1055

8✔
1056
        // For records that are not confirmed, we perform a fee bump if needed.
8✔
1057
        for _, r := range feeBumpRecords {
12✔
1058
                t.wg.Add(1)
4✔
1059
                go t.handleFeeBumpTx(r, currentHeight)
4✔
1060
        }
4✔
1061

1062
        // For records that are failed, we'll notify the caller about this
1063
        // result.
1064
        for _, r := range failedRecords {
13✔
1065
                t.wg.Add(1)
5✔
1066
                go t.handleUnknownSpent(r)
5✔
1067
        }
5✔
1068
}
1069

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

5✔
1077
        log.Debugf("Record %v is spent in tx=%v", r.requestID, r.tx.TxHash())
5✔
1078

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

5✔
1089
        // Notify that this tx is confirmed and remove the record from the map.
5✔
1090
        t.handleResult(result)
5✔
1091
}
5✔
1092

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

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

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

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

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

2✔
1127
                result.Event = TxFailed
2✔
1128

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

1137
                // Attach the new fee rate.
1138
                result.FeeRate = feeRate
2✔
1139

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

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

1156
        t.handleResult(result)
5✔
1157
}
1158

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

8✔
1167
        var (
8✔
1168
                result *BumpResult
8✔
1169
                err    error
8✔
1170
        )
8✔
1171

8✔
1172
        // Attempt an initial broadcast which is guaranteed to comply with the
8✔
1173
        // RBF rules.
8✔
1174
        //
8✔
1175
        // Create the initial tx to be broadcasted.
8✔
1176
        record, err := t.initializeTx(r)
8✔
1177
        if err != nil {
13✔
1178
                log.Errorf("Initial broadcast failed: %v", err)
5✔
1179

5✔
1180
                // We now handle the initialization error and exit.
5✔
1181
                t.handleInitialTxError(r, err)
5✔
1182

5✔
1183
                return
5✔
1184
        }
5✔
1185

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

1200
        t.handleResult(result)
6✔
1201
}
1202

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

7✔
1210
        log.Debugf("Attempting to fee bump tx=%v in record %v", r.tx.TxHash(),
7✔
1211
                r.requestID)
7✔
1212

7✔
1213
        oldTxid := r.tx.TxHash()
7✔
1214

7✔
1215
        // Get the current conf target for this record.
7✔
1216
        confTarget := calcCurrentConfTarget(currentHeight, r.req.DeadlineHeight)
7✔
1217

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

4✔
1228
                return
4✔
1229
        }
4✔
1230

1231
        // If the fee rate was not increased, there's no need to bump the fee.
1232
        if !increased {
7✔
1233
                log.Tracef("Skip bumping tx %v at height=%v", oldTxid,
1✔
1234
                        t.currentHeight.Load())
1✔
1235

1✔
1236
                return
1✔
1237
        }
1✔
1238

1239
        // The fee function now has a new fee rate, we will use it to bump the
1240
        // fee of the tx.
1241
        resultOpt := t.createAndPublishTx(r)
5✔
1242

5✔
1243
        // If there's a result, we will notify the caller about the result.
5✔
1244
        resultOpt.WhenSome(func(result BumpResult) {
10✔
1245
                // Notify the new result.
5✔
1246
                t.handleResult(&result)
5✔
1247
        })
5✔
1248
}
1249

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

5✔
1258
        log.Debugf("Record %v has inputs spent by a tx unknown to the fee "+
5✔
1259
                "bumper, failing it now:\n%v", r.requestID,
5✔
1260
                inputTypeSummary(r.req.Inputs))
5✔
1261

5✔
1262
        // Create a result that will be sent to the resultChan which is listened
5✔
1263
        // by the caller.
5✔
1264
        result := t.createUnknownSpentBumpResult(r)
5✔
1265

5✔
1266
        // Notify the sweeper about this result in the end.
5✔
1267
        t.handleResult(result)
5✔
1268
}
5✔
1269

1270
// createUnknownSpentBumpResult creates and returns a BumpResult given the
1271
// monitored record has unknown spends.
1272
func (t *TxPublisher) createUnknownSpentBumpResult(
1273
        r *monitorRecord) *BumpResult {
5✔
1274

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

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

1294
        // Attach the new fee rate to be used for the next sweeping attempt.
1295
        result.FeeRate = feeRate
5✔
1296

5✔
1297
        return result
5✔
1298
}
1299

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

10✔
1306
        // Fetch the old tx.
10✔
1307
        oldTx := r.tx
10✔
1308

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

10✔
1316
        // If there's an error creating the replacement tx, we need to abort the
10✔
1317
        // flow and handle it.
10✔
1318
        if err != nil {
16✔
1319
                return t.handleReplacementTxError(r, oldTx, err)
6✔
1320
        }
6✔
1321

1322
        // The tx has been created without any errors, we now register a new
1323
        // record by overwriting the same requestID.
1324
        record := t.updateRecord(r, sweepCtx)
7✔
1325

7✔
1326
        // Attempt to broadcast this new tx.
7✔
1327
        result, err := t.broadcast(record)
7✔
1328
        if err != nil {
7✔
1329
                log.Infof("Failed to broadcast replacement tx %v: %v",
×
1330
                        sweepCtx.tx.TxHash(), err)
×
1331

×
1332
                return fn.None[BumpResult]()
×
1333
        }
×
1334

1335
        // If the result error is fee related, we will return no error and let
1336
        // the fee bumper retry it at next block.
1337
        //
1338
        // NOTE: we may get this error if we've bypassed the mempool check,
1339
        // which means we are using neutrino backend.
1340
        if errors.Is(result.Err, chain.ErrInsufficientFee) ||
7✔
1341
                errors.Is(result.Err, lnwallet.ErrMempoolFee) {
9✔
1342

2✔
1343
                log.Debugf("Failed to bump tx %v: %v", oldTx.TxHash(),
2✔
1344
                        result.Err)
2✔
1345

2✔
1346
                return fn.None[BumpResult]()
2✔
1347
        }
2✔
1348

1349
        // A successful replacement tx is created, attach the old tx.
1350
        result.ReplacedTx = oldTx
7✔
1351

7✔
1352
        // If the new tx failed to be published, we will return the result so
7✔
1353
        // the caller can handle it.
7✔
1354
        if result.Event == TxFailed {
8✔
1355
                return fn.Some(*result)
1✔
1356
        }
1✔
1357

1358
        log.Debugf("Replaced tx=%v with new tx=%v", oldTx.TxHash(),
6✔
1359
                sweepCtx.tx.TxHash())
6✔
1360

6✔
1361
        // Otherwise, it's a successful RBF, set the event and return.
6✔
1362
        result.Event = TxReplaced
6✔
1363

6✔
1364
        return fn.Some(*result)
6✔
1365
}
1366

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

5✔
1374
        txid := r.tx.TxHash()
5✔
1375

5✔
1376
        // Iterate all the spending txns and check if they match the sweeping
5✔
1377
        // tx.
5✔
1378
        for op, spendingTx := range spends {
10✔
1379
                spendingTxID := spendingTx.TxHash()
5✔
1380

5✔
1381
                // If the spending tx is the same as the sweeping tx then we are
5✔
1382
                // good.
5✔
1383
                if spendingTxID == txid {
9✔
1384
                        continue
4✔
1385
                }
1386

1387
                log.Warnf("Detected unknown spend of input=%v in tx=%v", op,
4✔
1388
                        spendingTx.TxHash())
4✔
1389

4✔
1390
                return true
4✔
1391
        }
1392

1393
        return false
4✔
1394
}
1395

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

9✔
1402
        // Create a slice to record the inputs spent.
9✔
1403
        spentInputs := make(map[wire.OutPoint]*wire.MsgTx, len(r.req.Inputs))
9✔
1404

9✔
1405
        // Iterate all the inputs and check if they have been spent already.
9✔
1406
        for _, inp := range r.req.Inputs {
20✔
1407
                op := inp.OutPoint()
11✔
1408

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

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

×
1431
                        return nil
×
1432
                }
×
1433

1434
                // Remove the subscription when exit.
1435
                defer spendEvent.Cancel()
11✔
1436

11✔
1437
                // Do a non-blocking read to see if the output has been spent.
11✔
1438
                select {
11✔
1439
                case spend, ok := <-spendEvent.Spend:
7✔
1440
                        if !ok {
7✔
1441
                                log.Debugf("Spend ntfn for %v canceled", op)
×
1442

×
1443
                                continue
×
1444
                        }
1445

1446
                        spendingTx := spend.SpendingTx
7✔
1447

7✔
1448
                        log.Debugf("Detected spent of input=%v in tx=%v", op,
7✔
1449
                                spendingTx.TxHash())
7✔
1450

7✔
1451
                        spentInputs[op] = spendingTx
7✔
1452

1453
                // Move to the next input.
1454
                default:
7✔
1455
                        log.Tracef("Input %v not spent yet", op)
7✔
1456
                }
1457
        }
1458

1459
        return spentInputs
9✔
1460
}
1461

1462
// calcCurrentConfTarget calculates the current confirmation target based on
1463
// the deadline height. The conf target is capped at 0 if the deadline has
1464
// already been past.
1465
func calcCurrentConfTarget(currentHeight, deadline int32) uint32 {
17✔
1466
        var confTarget uint32
17✔
1467

17✔
1468
        // Calculate how many blocks left until the deadline.
17✔
1469
        deadlineDelta := deadline - currentHeight
17✔
1470

17✔
1471
        // If we are already past the deadline, we will set the conf target to
17✔
1472
        // be 1.
17✔
1473
        if deadlineDelta < 0 {
24✔
1474
                log.Warnf("Deadline is %d blocks behind current height %v",
7✔
1475
                        -deadlineDelta, currentHeight)
7✔
1476

7✔
1477
                confTarget = 0
7✔
1478
        } else {
20✔
1479
                confTarget = uint32(deadlineDelta)
13✔
1480
        }
13✔
1481

1482
        return confTarget
17✔
1483
}
1484

1485
// sweepTxCtx houses a sweep transaction with additional context.
1486
type sweepTxCtx struct {
1487
        tx *wire.MsgTx
1488

1489
        fee btcutil.Amount
1490

1491
        extraTxOut fn.Option[SweepOutput]
1492

1493
        // outpointToTxIndex maps the outpoint of the inputs to their index in
1494
        // the sweep transaction.
1495
        outpointToTxIndex map[wire.OutPoint]int
1496
}
1497

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

26✔
1504
        // Validate and calculate the fee and change amount.
26✔
1505
        txFee, changeOutputsOpt, locktimeOpt, err := prepareSweepTx(
26✔
1506
                inputs, changePkScript, feeRate, t.currentHeight.Load(),
26✔
1507
                t.cfg.AuxSweeper,
26✔
1508
        )
26✔
1509
        if err != nil {
29✔
1510
                return nil, err
3✔
1511
        }
3✔
1512

1513
        var (
26✔
1514
                // Create the sweep transaction that we will be building. We
26✔
1515
                // use version 2 as it is required for CSV.
26✔
1516
                sweepTx = wire.NewMsgTx(2)
26✔
1517

26✔
1518
                // We'll add the inputs as we go so we know the final ordering
26✔
1519
                // of inputs to sign.
26✔
1520
                idxs []input.Input
26✔
1521
        )
26✔
1522

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

1532
                idxs = append(idxs, o)
3✔
1533
                sweepTx.AddTxIn(&wire.TxIn{
3✔
1534
                        PreviousOutPoint: o.OutPoint(),
3✔
1535
                        Sequence:         o.BlocksToMaturity(),
3✔
1536
                })
3✔
1537
                sweepTx.AddTxOut(o.RequiredTxOut())
3✔
1538

3✔
1539
                outpointToTxIndex[o.OutPoint()] = len(sweepTx.TxOut) - 1
3✔
1540
        }
1541

1542
        // Sum up the value contained in the remaining inputs, and add them to
1543
        // the sweep transaction.
1544
        for _, o := range inputs {
52✔
1545
                if o.RequiredTxOut() != nil {
29✔
1546
                        continue
3✔
1547
                }
1548

1549
                idxs = append(idxs, o)
26✔
1550
                sweepTx.AddTxIn(&wire.TxIn{
26✔
1551
                        PreviousOutPoint: o.OutPoint(),
26✔
1552
                        Sequence:         o.BlocksToMaturity(),
26✔
1553
                })
26✔
1554
        }
1555

1556
        // If we have change outputs to add, then add it the sweep transaction
1557
        // here.
1558
        changeOutputsOpt.WhenSome(func(changeOuts []SweepOutput) {
52✔
1559
                for i := range changeOuts {
53✔
1560
                        sweepTx.AddTxOut(&changeOuts[i].TxOut)
27✔
1561
                }
27✔
1562
        })
1563

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

26✔
1568
        prevInputFetcher, err := input.MultiPrevOutFetcher(inputs)
26✔
1569
        if err != nil {
26✔
1570
                return nil, fmt.Errorf("error creating prev input fetcher "+
×
1571
                        "for hash cache: %v", err)
×
1572
        }
×
1573
        hashCache := txscript.NewTxSigHashes(sweepTx, prevInputFetcher)
26✔
1574

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

1585
                sweepTx.TxIn[idx].Witness = inputScript.Witness
26✔
1586

26✔
1587
                if len(inputScript.SigScript) == 0 {
52✔
1588
                        return nil
26✔
1589
                }
26✔
1590

1591
                sweepTx.TxIn[idx].SignatureScript = inputScript.SigScript
×
1592

×
1593
                return nil
×
1594
        }
1595

1596
        for idx, inp := range idxs {
52✔
1597
                if err := addInputScript(idx, inp); err != nil {
26✔
1598
                        return nil, err
×
1599
                }
×
1600
        }
1601

1602
        log.Debugf("Created sweep tx %v for inputs:\n%v", sweepTx.TxHash(),
26✔
1603
                inputTypeSummary(inputs))
26✔
1604

26✔
1605
        // Try to locate the extra change output, though there might be None.
26✔
1606
        extraTxOut := fn.MapOption(
26✔
1607
                func(sweepOuts []SweepOutput) fn.Option[SweepOutput] {
52✔
1608
                        for _, sweepOut := range sweepOuts {
52✔
1609
                                if !sweepOut.IsExtra {
29✔
1610
                                        continue
3✔
1611
                                }
1612

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

23✔
1623
                                return fn.Some(sweepOut)
23✔
1624
                        }
1625

1626
                        return fn.None[SweepOutput]()
3✔
1627
                },
1628
        )(changeOutputsOpt)
1629

1630
        return &sweepTxCtx{
26✔
1631
                tx:                sweepTx,
26✔
1632
                fee:               txFee,
26✔
1633
                extraTxOut:        fn.FlattenOption(extraTxOut),
26✔
1634
                outpointToTxIndex: outpointToTxIndex,
26✔
1635
        }, nil
26✔
1636
}
1637

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

31✔
1650
        noChange := fn.None[[]SweepOutput]()
31✔
1651
        noLocktime := fn.None[int32]()
31✔
1652

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

31✔
1658
        var extraChangeOut fn.Option[SweepOutput]
31✔
1659
        err := fn.MapOptionZ(
31✔
1660
                auxSweeper, func(aux AuxSweeper) error {
55✔
1661
                        extraOut := aux.DeriveSweepAddr(inputs, changePkScript)
24✔
1662
                        if err := extraOut.Err(); err != nil {
24✔
1663
                                return err
×
1664
                        }
×
1665

1666
                        extraChangeOut = extraOut.LeftToSome()
24✔
1667

24✔
1668
                        return nil
24✔
1669
                },
1670
        )
1671
        if err != nil {
31✔
1672
                return 0, noChange, noLocktime, err
×
1673
        }
×
1674

1675
        // We also add the extra change output to the change pk scripts.
1676
        //
1677
        // NOTE: The weight estimation will not be quite accurate because the
1678
        // witness data is greater when overlay channels are used. But that
1679
        // shouldn't be a problem since we will increase the fee rate
1680
        // incrementally via the fee function.
1681
        extraChangeOut.WhenSome(func(o SweepOutput) {
55✔
1682
                changePkScripts = append(changePkScripts, o.TxOut.PkScript)
24✔
1683
        })
24✔
1684

1685
        // Creating a weight estimator with nil outputs and zero max fee rate.
1686
        // We don't allow adding customized outputs in the sweeping tx, and the
1687
        // fee rate is already being managed before we get here.
1688
        inputs, estimator, err := getWeightEstimate(
31✔
1689
                inputs, nil, feeRate, 0, changePkScripts,
31✔
1690
        )
31✔
1691
        if err != nil {
31✔
1692
                return 0, noChange, noLocktime, err
×
1693
        }
×
1694

1695
        txFee := estimator.fee()
31✔
1696

31✔
1697
        var (
31✔
1698
                // Track whether any of the inputs require a certain locktime.
31✔
1699
                locktime = int32(-1)
31✔
1700

31✔
1701
                // We keep track of total input amount, and required output
31✔
1702
                // amount to use for calculating the change amount below.
31✔
1703
                totalInput     btcutil.Amount
31✔
1704
                requiredOutput btcutil.Amount
31✔
1705
        )
31✔
1706

31✔
1707
        // If we have an extra change output, then we'll add it as a required
31✔
1708
        // output amt.
31✔
1709
        extraChangeOut.WhenSome(func(o SweepOutput) {
55✔
1710
                requiredOutput += btcutil.Amount(o.Value)
24✔
1711
        })
24✔
1712

1713
        // Go through each input and check if the required lock times have
1714
        // reached and are the same.
1715
        for _, o := range inputs {
63✔
1716
                // If the input has a required output, we'll add it to the
32✔
1717
                // required output amount.
32✔
1718
                if o.RequiredTxOut() != nil {
35✔
1719
                        requiredOutput += btcutil.Amount(
3✔
1720
                                o.RequiredTxOut().Value,
3✔
1721
                        )
3✔
1722
                }
3✔
1723

1724
                // Update the total input amount.
1725
                totalInput += btcutil.Amount(o.SignDesc().Output.Value)
32✔
1726

32✔
1727
                lt, ok := o.RequiredLockTime()
32✔
1728

32✔
1729
                // Skip if the input doesn't require a lock time.
32✔
1730
                if !ok {
63✔
1731
                        continue
31✔
1732
                }
1733

1734
                // Check if the lock time has reached
1735
                if lt > uint32(currentHeight) {
5✔
1736
                        return 0, noChange, noLocktime,
1✔
1737
                                fmt.Errorf("%w: current height is %v, "+
1✔
1738
                                        "locktime is %v", ErrLocktimeImmature,
1✔
1739
                                        currentHeight, lt)
1✔
1740
                }
1✔
1741

1742
                // If another input commits to a different locktime, they
1743
                // cannot be combined in the same transaction.
1744
                if locktime != -1 && locktime != int32(lt) {
3✔
1745
                        return 0, noChange, noLocktime, ErrLocktimeConflict
×
1746
                }
×
1747

1748
                // Update the locktime for next iteration.
1749
                locktime = int32(lt)
3✔
1750
        }
1751

1752
        // Make sure total output amount is less than total input amount.
1753
        if requiredOutput+txFee > totalInput {
35✔
1754
                log.Errorf("Insufficient input to create sweep tx: "+
5✔
1755
                        "input_sum=%v, output_sum=%v", totalInput,
5✔
1756
                        requiredOutput+txFee)
5✔
1757

5✔
1758
                return 0, noChange, noLocktime, ErrNotEnoughInputs
5✔
1759
        }
5✔
1760

1761
        // The value remaining after the required output and fees is the
1762
        // change output.
1763
        changeAmt := totalInput - requiredOutput - txFee
28✔
1764
        changeOuts := make([]SweepOutput, 0, 2)
28✔
1765

28✔
1766
        extraChangeOut.WhenSome(func(o SweepOutput) {
52✔
1767
                changeOuts = append(changeOuts, o)
24✔
1768
        })
24✔
1769

1770
        // We'll calculate the dust limit for the given changePkScript since it
1771
        // is variable.
1772
        changeFloor := lnwallet.DustLimitForSize(
28✔
1773
                len(changePkScript.DeliveryAddress),
28✔
1774
        )
28✔
1775

28✔
1776
        switch {
28✔
1777
        // If the change amount is dust, we'll move it into the fees, and
1778
        // ignore it.
1779
        case changeAmt < changeFloor:
25✔
1780
                log.Infof("Change amt %v below dustlimit %v, not adding "+
25✔
1781
                        "change output", changeAmt, changeFloor)
25✔
1782

25✔
1783
                // If there's no required output, and the change output is a
25✔
1784
                // dust, it means we are creating a tx without any outputs. In
25✔
1785
                // this case we'll return an error. This could happen when
25✔
1786
                // creating a tx that has an anchor as the only input.
25✔
1787
                if requiredOutput == 0 {
28✔
1788
                        return 0, noChange, noLocktime, ErrTxNoOutput
3✔
1789
                }
3✔
1790

1791
                // The dust amount is added to the fee.
1792
                txFee += changeAmt
22✔
1793

1794
        // Otherwise, we'll actually recognize it as a change output.
1795
        default:
6✔
1796
                changeOuts = append(changeOuts, SweepOutput{
6✔
1797
                        TxOut: wire.TxOut{
6✔
1798
                                Value:    int64(changeAmt),
6✔
1799
                                PkScript: changePkScript.DeliveryAddress,
6✔
1800
                        },
6✔
1801
                        IsExtra:     false,
6✔
1802
                        InternalKey: changePkScript.InternalKey,
6✔
1803
                })
6✔
1804
        }
1805

1806
        // Optionally set the locktime.
1807
        locktimeOpt := fn.Some(locktime)
28✔
1808
        if locktime == -1 {
56✔
1809
                locktimeOpt = noLocktime
28✔
1810
        }
28✔
1811

1812
        var changeOutsOpt fn.Option[[]SweepOutput]
28✔
1813
        if len(changeOuts) > 0 {
56✔
1814
                changeOutsOpt = fn.Some(changeOuts)
28✔
1815
        }
28✔
1816

1817
        log.Debugf("Creating sweep tx for %v inputs (%s) using %v, "+
28✔
1818
                "tx_weight=%v, tx_fee=%v, locktime=%v, parents_count=%v, "+
28✔
1819
                "parents_fee=%v, parents_weight=%v, current_height=%v",
28✔
1820
                len(inputs), inputTypeSummary(inputs), feeRate,
28✔
1821
                estimator.weight(), txFee, locktimeOpt, len(estimator.parents),
28✔
1822
                estimator.parentsFee, estimator.parentsWeight, currentHeight)
28✔
1823

28✔
1824
        return txFee, changeOutsOpt, locktimeOpt, nil
28✔
1825
}
1826

1827
// handleReplacementTxError handles the error returned from creating the
1828
// replacement tx. It returns a BumpResult that should be notified to the
1829
// sweeper.
1830
func (t *TxPublisher) handleReplacementTxError(r *monitorRecord,
1831
        oldTx *wire.MsgTx, err error) fn.Option[BumpResult] {
6✔
1832

6✔
1833
        // If the error is fee related, we will return no error and let the fee
6✔
1834
        // bumper retry it at next block.
6✔
1835
        //
6✔
1836
        // NOTE: we can check the RBF error here and ask the fee function to
6✔
1837
        // recalculate the fee rate. However, this would defeat the purpose of
6✔
1838
        // using a deadline based fee function:
6✔
1839
        // - if the deadline is far away, there's no rush to RBF the tx.
6✔
1840
        // - if the deadline is close, we expect the fee function to give us a
6✔
1841
        //   higher fee rate. If the fee rate cannot satisfy the RBF rules, it
6✔
1842
        //   means the budget is not enough.
6✔
1843
        if errors.Is(err, chain.ErrInsufficientFee) ||
6✔
1844
                errors.Is(err, lnwallet.ErrMempoolFee) {
10✔
1845

4✔
1846
                log.Debugf("Failed to bump tx %v: %v", oldTx.TxHash(), err)
4✔
1847
                return fn.None[BumpResult]()
4✔
1848
        }
4✔
1849

1850
        // At least one of the inputs is missing, which means it has already
1851
        // been spent by another tx and confirmed. In this case we will handle
1852
        // it by returning a TxUnknownSpend bump result.
1853
        if errors.Is(err, ErrInputMissing) {
4✔
1854
                log.Warnf("Fail to fee bump tx %v: %v", oldTx.TxHash(), err)
×
1855
                bumpResult := t.handleMissingInputs(r)
×
1856

×
1857
                return fn.Some(*bumpResult)
×
1858
        }
×
1859

1860
        // Return a failed event to retry the sweep.
1861
        event := TxFailed
4✔
1862

4✔
1863
        // Calculate the next fee rate for the retry.
4✔
1864
        feeRate, ferr := t.calculateRetryFeeRate(r)
4✔
1865
        if ferr != nil {
4✔
1866
                // If there's an error with the fee calculation, we need to
×
1867
                // abort the sweep.
×
1868
                event = TxFatal
×
1869
        }
×
1870

1871
        // If the error is not fee related, we will return a `TxFailed` event so
1872
        // this input can be retried.
1873
        result := fn.Some(BumpResult{
4✔
1874
                Event:     event,
4✔
1875
                Tx:        oldTx,
4✔
1876
                Err:       err,
4✔
1877
                requestID: r.requestID,
4✔
1878
                FeeRate:   feeRate,
4✔
1879
        })
4✔
1880

4✔
1881
        // If the tx doesn't not have enough budget, or if the inputs amounts
4✔
1882
        // are not sufficient to cover the budget, we will return a result so
4✔
1883
        // the sweeper can handle it by re-clustering the utxos.
4✔
1884
        if errors.Is(err, ErrNotEnoughBudget) ||
4✔
1885
                errors.Is(err, ErrNotEnoughInputs) {
8✔
1886

4✔
1887
                log.Warnf("Fail to fee bump tx %v: %v", oldTx.TxHash(), err)
4✔
1888
                return result
4✔
1889
        }
4✔
1890

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

×
1895
        return result
×
1896
}
1897

1898
// calculateRetryFeeRate calculates a new fee rate to be used as the starting
1899
// fee rate for the next sweep attempt if the inputs are to be retried. When the
1900
// fee function is nil it will be created here, and an error is returned if the
1901
// fee func cannot be initialized.
1902
func (t *TxPublisher) calculateRetryFeeRate(
1903
        r *monitorRecord) (chainfee.SatPerKWeight, error) {
6✔
1904

6✔
1905
        // Get the fee function, which will be used to decided the next fee rate
6✔
1906
        // to use if the sweeper decides to retry sweeping this input.
6✔
1907
        feeFunc := r.feeFunction
6✔
1908

6✔
1909
        // When the record is failed before the initial broadcast is attempted,
6✔
1910
        // it will have a nil fee func. In this case, we'll create the fee func
6✔
1911
        // here.
6✔
1912
        //
6✔
1913
        // NOTE: Since the current record is failed and will be deleted, we
6✔
1914
        // don't need to update the record on this fee function. We only need
6✔
1915
        // the fee rate data so the sweeper can pick up where we left off.
6✔
1916
        if feeFunc == nil {
7✔
1917
                f, err := t.initializeFeeFunction(r.req)
1✔
1918

1✔
1919
                // TODO(yy): The only error we would receive here is when the
1✔
1920
                // pkScript is not recognized by the weightEstimator. What we
1✔
1921
                // should do instead is to check the pkScript immediately after
1✔
1922
                // receiving a sweep request so we don't need to check it again,
1✔
1923
                // which will also save us from error checking from several
1✔
1924
                // callsites.
1✔
1925
                if err != nil {
1✔
1926
                        log.Errorf("Failed to create fee func for record %v: "+
×
1927
                                "%v", r.requestID, err)
×
1928

×
1929
                        return 0, err
×
1930
                }
×
1931

1932
                feeFunc = f
1✔
1933
        }
1934

1935
        // Since we failed to sweep the inputs, either the sweeping tx has been
1936
        // replaced by another party's tx, or the current output values cannot
1937
        // cover the budget, we missed this block window to increase its fee
1938
        // rate. To make sure the fee rate stays in the initial line, we now ask
1939
        // the fee function to give us the next fee rate as if the sweeping tx
1940
        // were RBFed. This new fee rate will be used as the starting fee rate
1941
        // if the upper system decides to continue sweeping the rest of the
1942
        // inputs.
1943
        _, err := feeFunc.Increment()
6✔
1944
        if err != nil {
10✔
1945
                // The fee function has reached its max position - nothing we
4✔
1946
                // can do here other than letting the user increase the budget.
4✔
1947
                log.Errorf("Failed to calculate the next fee rate for "+
4✔
1948
                        "Record(%v): %v", r.requestID, err)
4✔
1949
        }
4✔
1950

1951
        return feeFunc.FeeRate(), nil
6✔
1952
}
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