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

lightningnetwork / lnd / 17830307614

18 Sep 2025 01:29PM UTC coverage: 54.617% (-12.0%) from 66.637%
17830307614

Pull #10200

github

web-flow
Merge 181a0a7bc into b34fc964b
Pull Request #10200: github: change to form-based issue template

109249 of 200028 relevant lines covered (54.62%)

21896.43 hits per line

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

78.95
/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 {
×
120
        switch e {
×
121
        case TxPublished:
×
122
                return "Published"
×
123
        case TxFailed:
×
124
                return "Failed"
×
125
        case TxReplaced:
×
126
                return "Replaced"
×
127
        case TxConfirmed:
×
128
                return "Confirmed"
×
129
        case TxUnknownSpend:
×
130
                return "UnknownSpend"
×
131
        case TxFatal:
×
132
                return "Fatal"
×
133
        default:
×
134
                return "Unknown"
×
135
        }
136
}
137

138
// Unknown returns true if the event is unknown.
139
func (e BumpEvent) Unknown() bool {
11✔
140
        return e >= sentinelEvent
11✔
141
}
11✔
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) {
11✔
181
        // We'll want to know if we have any blobs, as we need to factor this
11✔
182
        // into the max fee rate for this bump request.
11✔
183
        hasBlobs := fn.Any(r.Inputs, func(i input.Input) bool {
21✔
184
                return fn.MapOptionZ(
10✔
185
                        i.ResolutionBlob(), func(b tlv.Blob) bool {
10✔
186
                                return len(b) > 0
×
187
                        },
×
188
                )
189
        })
190

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

11✔
195
        // If we have blobs, then we'll add an extra sweep addr for the size
11✔
196
        // estimate below. We know that these blobs will also always be based on
11✔
197
        // p2tr addrs.
11✔
198
        if hasBlobs {
11✔
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(
11✔
207
                r.Inputs, sweepAddrs,
11✔
208
        )
11✔
209
        if err != nil {
12✔
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)
10✔
219
        if maxFeeRateAllowed > r.MaxFeeRate {
13✔
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 "+
7✔
228
                "instead, txWeight=%v", maxFeeRateAllowed, r.MaxFeeRate, size)
7✔
229

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

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

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

256
        return estimator.weight(), nil
14✔
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 {
×
290
        desc := fmt.Sprintf("Event=%v", b.Event)
×
291
        if b.Tx != nil {
×
292
                desc += fmt.Sprintf(", Tx=%v", b.Tx.TxHash())
×
293
        }
×
294

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

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

12✔
303
        // Every result must have a tx except the fatal or failed case.
12✔
304
        if b.Tx == nil && !isFailureEvent {
13✔
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() {
12✔
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 {
11✔
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 {
11✔
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) {
8✔
325
                return fmt.Errorf("%w: missing fee rate or fee",
1✔
326
                        ErrInvalidBumpResult)
1✔
327
        }
1✔
328

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

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

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

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

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

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

442
        return subscriber
5✔
443
}
444

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

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

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

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

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

19✔
474
        return r
19✔
475
}
19✔
476

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

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

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

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

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

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

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

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

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

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

7✔
564
                        return record, nil
7✔
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):
4✔
583
                        increased := false
4✔
584

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

5✔
592
                                // If the fee function tells us that we have
5✔
593
                                // used up the budget, we will return an error
5✔
594
                                // indicating this tx cannot be made. The
5✔
595
                                // sweeper should handle this error and try to
5✔
596
                                // cluster these inputs differently.
5✔
597
                                increased, err = f.Increment()
5✔
598
                                if err != nil {
6✔
599
                                        return nil, err
1✔
600
                                }
1✔
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:
2✔
608
                        log.Debugf("Failed to create RBF-compliant tx: %v", err)
2✔
609
                        return nil, err
2✔
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) {
23✔
619
        req := r.req
23✔
620
        f := r.feeFunction
23✔
621

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

631
        // Sanity check the budget still covers the fee.
632
        if sweepCtx.fee > req.Budget {
25✔
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
21✔
640

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

21✔
644
        // Exit early if the tx is valid.
21✔
645
        if err == nil {
33✔
646
                return sweepCtx, nil
12✔
647
        }
12✔
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) {
9✔
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) {
9✔
660
                log.Debug("Skipped testmempoolaccept due to not implemented")
×
661
                return sweepCtx, nil
×
662
        }
×
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) {
9✔
667
                log.Debugf("Tx %v missing inputs, it's likely the input has "+
×
668
                        "been spent by others", sweepCtx.tx.TxHash())
×
669

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

×
673
                return sweepCtx, ErrInputMissing
×
674
        }
×
675

676
        return sweepCtx, fmt.Errorf("tx=%v failed mempool check: %w",
9✔
677
                sweepCtx.tx.TxHash(), err)
9✔
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 {
×
686
        // Get the spending txns.
×
687
        spends := t.getSpentInputs(r)
×
688

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

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

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

×
710
                return result
×
711
        }
×
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) {
9✔
732
        txid := record.tx.TxHash()
9✔
733

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

9✔
738
        // Before we go to broadcast, we'll notify the aux sweeper, if it's
9✔
739
        // present of this new broadcast attempt.
9✔
740
        err := fn.MapOptionZ(t.cfg.AuxSweeper, func(aux AuxSweeper) error {
18✔
741
                return aux.NotifyBroadcast(
9✔
742
                        record.req, tx, record.fee, record.outpointToTxIndex,
9✔
743
                )
9✔
744
        })
9✔
745
        if err != nil {
9✔
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
9✔
752

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

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

9✔
781
        return result, nil
9✔
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) {
14✔
787
        id := result.requestID
14✔
788
        subscriber, ok := t.subscriberChans.Load(id)
14✔
789
        if !ok {
14✔
790
                log.Errorf("Result chan for id=%v not found", id)
×
791
                return
×
792
        }
×
793

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

14✔
796
        select {
14✔
797
        // Send the result to the subscriber.
798
        //
799
        // TODO(yy): Add timeout in case it's blocking?
800
        case subscriber <- result:
13✔
801
        case <-t.quit:
1✔
802
                log.Debug("Fee bumper stopped")
1✔
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) {
14✔
810
        id := result.requestID
14✔
811

14✔
812
        var txid chainhash.Hash
14✔
813
        if result.Tx != nil {
25✔
814
                txid = result.Tx.TxHash()
11✔
815
        }
11✔
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 {
14✔
824
        case TxFailed:
2✔
825
                log.Errorf("Removing monitor record=%v, tx=%v, due to err: %v",
2✔
826
                        id, txid, result.Err)
2✔
827

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

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

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

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

5✔
848
                return
5✔
849
        }
850

851
        t.records.Delete(id)
9✔
852
        t.subscriberChans.Delete(id)
9✔
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) {
11✔
859
        // Notify the subscriber.
11✔
860
        t.notifyResult(result)
11✔
861

11✔
862
        // Remove the record if it's failed or confirmed.
11✔
863
        t.removeResult(result)
11✔
864
}
11✔
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 {
×
895
        log.Info("TxPublisher starting...")
×
896

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

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

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

×
907
        log.Debugf("TxPublisher started")
×
908

×
909
        return nil
×
910
}
911

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

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

920
        close(t.quit)
×
921
        t.wg.Wait()
×
922

×
923
        log.Debug("TxPublisher stopped")
×
924

×
925
        return nil
×
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() {
×
934
        defer t.wg.Done()
×
935

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

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

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

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

952
                case <-t.quit:
×
953
                        log.Debug("Fee bumper stopped, exit monitor")
×
954
                        return
×
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() {
5✔
962
        // confirmedRecords stores a map of the records which have been
5✔
963
        // confirmed.
5✔
964
        confirmedRecords := make(map[uint64]*monitorRecord)
5✔
965

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

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

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

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

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

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

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

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

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

1✔
1017
                        // Move to the next record.
1✔
1018
                        return nil
1✔
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 {
3✔
1024
                        initialRecords[requestID] = r
1✔
1025

1✔
1026
                        return nil
1✔
1027
                }
1✔
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
1✔
1033

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

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

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

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

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

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

1062
        // For records that are failed, we'll notify the caller about this
1063
        // result.
1064
        for _, r := range failedRecords {
7✔
1065
                t.wg.Add(1)
2✔
1066
                go t.handleUnknownSpent(r)
2✔
1067
        }
2✔
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) {
2✔
1075
        defer t.wg.Done()
2✔
1076

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

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

2✔
1089
        // Notify that this tx is confirmed and remove the record from the map.
2✔
1090
        t.handleResult(result)
2✔
1091
}
2✔
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) {
2✔
1096
        // Create a bump result to be sent to the sweeper.
2✔
1097
        result := &BumpResult{
2✔
1098
                Err:       err,
2✔
1099
                requestID: r.requestID,
2✔
1100
        }
2✔
1101

2✔
1102
        // We now decide what type of event to send.
2✔
1103
        switch {
2✔
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):
×
1108
                result.Event = TxFailed
×
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):
×
1113
                result.Event = TxFailed
×
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):
×
1119
                fallthrough
×
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):
×
1126

×
1127
                result.Event = TxFailed
×
1128

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

1137
                // Attach the new fee rate.
1138
                result.FeeRate = feeRate
×
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):
×
1143
                result = t.handleMissingInputs(r)
×
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)
2✔
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) {
5✔
1165
        log.Debugf("Initial broadcast for requestID=%v", r.requestID)
5✔
1166

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

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

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

2✔
1183
                return
2✔
1184
        }
2✔
1185

1186
        // Successfully created the first tx, now broadcast it.
1187
        result, err = t.broadcast(record)
3✔
1188
        if err != nil {
3✔
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)
3✔
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) {
4✔
1208
        defer t.wg.Done()
4✔
1209

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

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

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

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

1✔
1228
                return
1✔
1229
        }
1✔
1230

1231
        // If the fee rate was not increased, there's no need to bump the fee.
1232
        if !increased {
4✔
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)
2✔
1242

2✔
1243
        // If there's a result, we will notify the caller about the result.
2✔
1244
        resultOpt.WhenSome(func(result BumpResult) {
4✔
1245
                // Notify the new result.
2✔
1246
                t.handleResult(&result)
2✔
1247
        })
2✔
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) {
2✔
1256
        defer t.wg.Done()
2✔
1257

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

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

2✔
1266
        // Notify the sweeper about this result in the end.
2✔
1267
        t.handleResult(result)
2✔
1268
}
2✔
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 {
2✔
1274

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

2✔
1285
        // Calculate the next fee rate for the retry.
2✔
1286
        feeRate, err := t.calculateRetryFeeRate(r)
2✔
1287
        if err != nil {
2✔
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
2✔
1296

2✔
1297
        return result
2✔
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] {
7✔
1305

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

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

7✔
1316
        // If there's an error creating the replacement tx, we need to abort the
7✔
1317
        // flow and handle it.
7✔
1318
        if err != nil {
10✔
1319
                return t.handleReplacementTxError(r, oldTx, err)
3✔
1320
        }
3✔
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)
4✔
1325

4✔
1326
        // Attempt to broadcast this new tx.
4✔
1327
        result, err := t.broadcast(record)
4✔
1328
        if err != nil {
4✔
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) ||
4✔
1341
                errors.Is(result.Err, lnwallet.ErrMempoolFee) {
4✔
1342

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

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

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

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

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

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

3✔
1364
        return fn.Some(*result)
3✔
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 {
2✔
1373

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

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

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

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

1✔
1390
                return true
1✔
1391
        }
1392

1393
        return false
1✔
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 {
6✔
1401

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

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

8✔
1409
                // For wallet utxos, the height hint is not set - we don't need
8✔
1410
                // to monitor them for third party spend.
8✔
1411
                //
8✔
1412
                // TODO(yy): We need to properly lock wallet utxos before
8✔
1413
                // skipping this check as the same wallet utxo can be used by
8✔
1414
                // different sweeping txns.
8✔
1415
                heightHint := inp.HeightHint()
8✔
1416
                if heightHint == 0 {
9✔
1417
                        heightHint = uint32(t.currentHeight.Load())
1✔
1418
                        log.Debugf("Checking wallet input %v using heightHint "+
1✔
1419
                                "%v", op, heightHint)
1✔
1420
                }
1✔
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(
8✔
1425
                        &op, inp.SignDesc().Output.PkScript, heightHint,
8✔
1426
                )
8✔
1427
                if err != nil {
8✔
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()
8✔
1436

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

×
1443
                                continue
×
1444
                        }
1445

1446
                        spendingTx := spend.SpendingTx
4✔
1447

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

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

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

1459
        return spentInputs
6✔
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 {
14✔
1466
        var confTarget uint32
14✔
1467

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

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

4✔
1477
                confTarget = 0
4✔
1478
        } else {
14✔
1479
                confTarget = uint32(deadlineDelta)
10✔
1480
        }
10✔
1481

1482
        return confTarget
14✔
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) {
23✔
1503

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

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

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

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

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

×
1539
                outpointToTxIndex[o.OutPoint()] = len(sweepTx.TxOut) - 1
×
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 {
46✔
1545
                if o.RequiredTxOut() != nil {
23✔
1546
                        continue
×
1547
                }
1548

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

1556
        // If we have change outputs to add, then add it the sweep transaction
1557
        // here.
1558
        changeOutputsOpt.WhenSome(func(changeOuts []SweepOutput) {
46✔
1559
                for i := range changeOuts {
47✔
1560
                        sweepTx.AddTxOut(&changeOuts[i].TxOut)
24✔
1561
                }
24✔
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()))
23✔
1567

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

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

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

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

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

×
1593
                return nil
×
1594
        }
1595

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

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

23✔
1605
        // Try to locate the extra change output, though there might be None.
23✔
1606
        extraTxOut := fn.MapOption(
23✔
1607
                func(sweepOuts []SweepOutput) fn.Option[SweepOutput] {
46✔
1608
                        for _, sweepOut := range sweepOuts {
46✔
1609
                                if !sweepOut.IsExtra {
23✔
1610
                                        continue
×
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]()
×
1627
                },
1628
        )(changeOutputsOpt)
1629

1630
        return &sweepTxCtx{
23✔
1631
                tx:                sweepTx,
23✔
1632
                fee:               txFee,
23✔
1633
                extraTxOut:        fn.FlattenOption(extraTxOut),
23✔
1634
                outpointToTxIndex: outpointToTxIndex,
23✔
1635
        }, nil
23✔
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) {
28✔
1649

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

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

28✔
1658
        var extraChangeOut fn.Option[SweepOutput]
28✔
1659
        err := fn.MapOptionZ(
28✔
1660
                auxSweeper, func(aux AuxSweeper) error {
52✔
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 {
28✔
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) {
52✔
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(
28✔
1689
                inputs, nil, feeRate, 0, changePkScripts,
28✔
1690
        )
28✔
1691
        if err != nil {
28✔
1692
                return 0, noChange, noLocktime, err
×
1693
        }
×
1694

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

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

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

28✔
1707
        // If we have an extra change output, then we'll add it as a required
28✔
1708
        // output amt.
28✔
1709
        extraChangeOut.WhenSome(func(o SweepOutput) {
52✔
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 {
57✔
1716
                // If the input has a required output, we'll add it to the
29✔
1717
                // required output amount.
29✔
1718
                if o.RequiredTxOut() != nil {
29✔
1719
                        requiredOutput += btcutil.Amount(
×
1720
                                o.RequiredTxOut().Value,
×
1721
                        )
×
1722
                }
×
1723

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

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

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

1734
                // Check if the lock time has reached
1735
                if lt > uint32(currentHeight) {
2✔
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) {
×
1745
                        return 0, noChange, noLocktime, ErrLocktimeConflict
×
1746
                }
×
1747

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

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

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

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

25✔
1766
        extraChangeOut.WhenSome(func(o SweepOutput) {
49✔
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(
25✔
1773
                len(changePkScript.DeliveryAddress),
25✔
1774
        )
25✔
1775

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

22✔
1783
                // If there's no required output, and the change output is a
22✔
1784
                // dust, it means we are creating a tx without any outputs. In
22✔
1785
                // this case we'll return an error. This could happen when
22✔
1786
                // creating a tx that has an anchor as the only input.
22✔
1787
                if requiredOutput == 0 {
22✔
1788
                        return 0, noChange, noLocktime, ErrTxNoOutput
×
1789
                }
×
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:
3✔
1796
                changeOuts = append(changeOuts, SweepOutput{
3✔
1797
                        TxOut: wire.TxOut{
3✔
1798
                                Value:    int64(changeAmt),
3✔
1799
                                PkScript: changePkScript.DeliveryAddress,
3✔
1800
                        },
3✔
1801
                        IsExtra:     false,
3✔
1802
                        InternalKey: changePkScript.InternalKey,
3✔
1803
                })
3✔
1804
        }
1805

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

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

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

25✔
1824
        return txFee, changeOutsOpt, locktimeOpt, nil
25✔
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] {
3✔
1832

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

2✔
1846
                log.Debugf("Failed to bump tx %v: %v", oldTx.TxHash(), err)
2✔
1847
                return fn.None[BumpResult]()
2✔
1848
        }
2✔
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) {
1✔
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
1✔
1862

1✔
1863
        // Calculate the next fee rate for the retry.
1✔
1864
        feeRate, ferr := t.calculateRetryFeeRate(r)
1✔
1865
        if ferr != nil {
1✔
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{
1✔
1874
                Event:     event,
1✔
1875
                Tx:        oldTx,
1✔
1876
                Err:       err,
1✔
1877
                requestID: r.requestID,
1✔
1878
                FeeRate:   feeRate,
1✔
1879
        })
1✔
1880

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

1✔
1887
                log.Warnf("Fail to fee bump tx %v: %v", oldTx.TxHash(), err)
1✔
1888
                return result
1✔
1889
        }
1✔
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) {
3✔
1904

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

3✔
1909
        // When the record is failed before the initial broadcast is attempted,
3✔
1910
        // it will have a nil fee func. In this case, we'll create the fee func
3✔
1911
        // here.
3✔
1912
        //
3✔
1913
        // NOTE: Since the current record is failed and will be deleted, we
3✔
1914
        // don't need to update the record on this fee function. We only need
3✔
1915
        // the fee rate data so the sweeper can pick up where we left off.
3✔
1916
        if feeFunc == nil {
4✔
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()
3✔
1944
        if err != nil {
4✔
1945
                // The fee function has reached its max position - nothing we
1✔
1946
                // can do here other than letting the user increase the budget.
1✔
1947
                log.Errorf("Failed to calculate the next fee rate for "+
1✔
1948
                        "Record(%v): %v", r.requestID, err)
1✔
1949
        }
1✔
1950

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