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

lightningnetwork / lnd / 13536249039

26 Feb 2025 03:42AM UTC coverage: 57.462% (-1.4%) from 58.835%
13536249039

Pull #8453

github

Roasbeef
peer: update chooseDeliveryScript to gen script if needed

In this commit, we update `chooseDeliveryScript` to generate a new
script if needed. This allows us to fold in a few other lines that
always followed this function into this expanded function.

The tests have been updated accordingly.
Pull Request #8453: [4/4] - multi: integrate new rbf coop close FSM into the existing peer flow

275 of 1318 new or added lines in 22 files covered. (20.86%)

19521 existing lines in 257 files now uncovered.

103858 of 180741 relevant lines covered (57.46%)

24750.23 hits per line

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

77.71
/sweep/fee_bumper.go
1
package sweep
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

118
// String returns a human-readable string for the event.
UNCOV
119
func (e BumpEvent) String() string {
×
UNCOV
120
        switch e {
×
UNCOV
121
        case TxPublished:
×
UNCOV
122
                return "Published"
×
UNCOV
123
        case TxFailed:
×
UNCOV
124
                return "Failed"
×
UNCOV
125
        case TxReplaced:
×
UNCOV
126
                return "Replaced"
×
UNCOV
127
        case TxConfirmed:
×
UNCOV
128
                return "Confirmed"
×
UNCOV
129
        case TxUnknownSpend:
×
UNCOV
130
                return "UnknownSpend"
×
UNCOV
131
        case TxFatal:
×
UNCOV
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 >= sentinalEvent
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 givens the total amount that can be used as fees by these
147
        // inputs.
148
        Budget btcutil.Amount
149

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

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

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

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

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

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

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

176
// MaxFeeRateAllowed returns the maximum fee rate allowed for the given
177
// request. It calculates the feerate using the supplied budget and the weight,
178
// compares it with the specified MaxFeeRate, and returns the smaller of the
179
// two.
180
func (r *BumpRequest) MaxFeeRateAllowed() (chainfee.SatPerKWeight, error) {
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✔
UNCOV
186
                                return len(b) > 0
×
UNCOV
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) {
14✔
237

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

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

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

UNCOV
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):
2✔
569
                        // We should at least start with a feerate above the
2✔
570
                        // mempool min feerate, so if we get this error, it
2✔
571
                        // means something is wrong earlier in the pipeline.
2✔
572
                        log.Errorf("Current fee=%v, feerate=%v, %v",
2✔
573
                                sweepCtx.fee, f.FeeRate(), err)
2✔
574

2✔
575
                        fallthrough
2✔
576

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

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

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

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

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

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

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

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

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

21✔
640
        // Exit early if the tx is valid.
21✔
641
        if err == nil {
33✔
642
                return sweepCtx, nil
12✔
643
        }
12✔
644

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

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

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

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

×
UNCOV
669
                return sweepCtx, ErrInputMissing
×
UNCOV
670
        }
×
671

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

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

×
UNCOV
685
        // Attach the spending txns.
×
UNCOV
686
        r.spentInputs = spends
×
UNCOV
687

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

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

×
UNCOV
706
                return result
×
UNCOV
707
        }
×
708

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

UNCOV
719
        return t.createUnknownSpentBumpResult(r)
×
720
}
721

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5✔
844
                return
5✔
845
        }
846

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

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

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

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

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

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

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

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

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

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

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

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

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

×
UNCOV
900
        t.wg.Add(1)
×
UNCOV
901
        go t.monitor()
×
UNCOV
902

×
UNCOV
903
        log.Debugf("TxPublisher started")
×
UNCOV
904

×
UNCOV
905
        return nil
×
906
}
907

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

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

UNCOV
916
        close(t.quit)
×
UNCOV
917
        t.wg.Wait()
×
UNCOV
918

×
UNCOV
919
        log.Debug("TxPublisher stopped")
×
UNCOV
920

×
UNCOV
921
        return nil
×
922
}
923

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1✔
1022
                        return nil
1✔
1023
                }
1✔
1024

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1106
        // When the error is due to budget being used up, we'll send a TxFailed
1107
        // so these inputs can be retried with a different group in the next
1108
        // block.
UNCOV
1109
        case errors.Is(err, ErrMaxPosition):
×
UNCOV
1110
                result.Event = TxFailed
×
1111

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

1117
        // When there are missing inputs, we'll create a TxUnknownSpend bump
1118
        // result here so the rest of the inputs can be retried.
UNCOV
1119
        case errors.Is(err, ErrInputMissing):
×
UNCOV
1120
                result = t.handleMissingInputs(r)
×
1121

1122
        // Otherwise this is not a fee-related error and the tx cannot be
1123
        // retried. In that case we will fail ALL the inputs in this tx, which
1124
        // means they will be removed from the sweeper and never be tried
1125
        // again.
1126
        //
1127
        // TODO(yy): Find out which input is causing the failure and fail that
1128
        // one only.
1129
        default:
2✔
1130
                result.Event = TxFatal
2✔
1131
        }
1132

1133
        t.handleResult(result)
2✔
1134
}
1135

1136
// handleInitialBroadcast is called when a new request is received. It will
1137
// handle the initial tx creation and broadcast. In details,
1138
// 1. init a fee function based on the given strategy.
1139
// 2. create an RBF-compliant tx and monitor it for confirmation.
1140
// 3. notify the initial broadcast result back to the caller.
1141
func (t *TxPublisher) handleInitialBroadcast(r *monitorRecord) {
5✔
1142
        log.Debugf("Initial broadcast for requestID=%v", r.requestID)
5✔
1143

5✔
1144
        var (
5✔
1145
                result *BumpResult
5✔
1146
                err    error
5✔
1147
        )
5✔
1148

5✔
1149
        // Attempt an initial broadcast which is guaranteed to comply with the
5✔
1150
        // RBF rules.
5✔
1151
        //
5✔
1152
        // Create the initial tx to be broadcasted.
5✔
1153
        record, err := t.initializeTx(r)
5✔
1154
        if err != nil {
7✔
1155
                log.Errorf("Initial broadcast failed: %v", err)
2✔
1156

2✔
1157
                // We now handle the initialization error and exit.
2✔
1158
                t.handleInitialTxError(r, err)
2✔
1159

2✔
1160
                return
2✔
1161
        }
2✔
1162

1163
        // Successfully created the first tx, now broadcast it.
1164
        result, err = t.broadcast(record)
3✔
1165
        if err != nil {
3✔
1166
                // The broadcast failed, which can only happen if the tx record
×
1167
                // cannot be found or the aux sweeper returns an error. In
×
1168
                // either case, we will send back a TxFail event so these
×
1169
                // inputs can be retried.
×
1170
                result = &BumpResult{
×
1171
                        Event:     TxFailed,
×
1172
                        Err:       err,
×
1173
                        requestID: r.requestID,
×
1174
                }
×
1175
        }
×
1176

1177
        t.handleResult(result)
3✔
1178
}
1179

1180
// handleFeeBumpTx checks if the tx needs to be bumped, and if so, it will
1181
// attempt to bump the fee of the tx.
1182
//
1183
// NOTE: Must be run as a goroutine to avoid blocking on sending the result.
1184
func (t *TxPublisher) handleFeeBumpTx(r *monitorRecord, currentHeight int32) {
4✔
1185
        defer t.wg.Done()
4✔
1186

4✔
1187
        log.Debugf("Attempting to fee bump tx=%v in record %v", r.tx.TxHash(),
4✔
1188
                r.requestID)
4✔
1189

4✔
1190
        oldTxid := r.tx.TxHash()
4✔
1191

4✔
1192
        // Get the current conf target for this record.
4✔
1193
        confTarget := calcCurrentConfTarget(currentHeight, r.req.DeadlineHeight)
4✔
1194

4✔
1195
        // Ask the fee function whether a bump is needed. We expect the fee
4✔
1196
        // function to increase its returned fee rate after calling this
4✔
1197
        // method.
4✔
1198
        increased, err := r.feeFunction.IncreaseFeeRate(confTarget)
4✔
1199
        if err != nil {
5✔
1200
                // TODO(yy): send this error back to the sweeper so it can
1✔
1201
                // re-group the inputs?
1✔
1202
                log.Errorf("Failed to increase fee rate for tx %v at "+
1✔
1203
                        "height=%v: %v", oldTxid, t.currentHeight.Load(), err)
1✔
1204

1✔
1205
                return
1✔
1206
        }
1✔
1207

1208
        // If the fee rate was not increased, there's no need to bump the fee.
1209
        if !increased {
4✔
1210
                log.Tracef("Skip bumping tx %v at height=%v", oldTxid,
1✔
1211
                        t.currentHeight.Load())
1✔
1212

1✔
1213
                return
1✔
1214
        }
1✔
1215

1216
        // The fee function now has a new fee rate, we will use it to bump the
1217
        // fee of the tx.
1218
        resultOpt := t.createAndPublishTx(r)
2✔
1219

2✔
1220
        // If there's a result, we will notify the caller about the result.
2✔
1221
        resultOpt.WhenSome(func(result BumpResult) {
4✔
1222
                // Notify the new result.
2✔
1223
                t.handleResult(&result)
2✔
1224
        })
2✔
1225
}
1226

1227
// handleUnknownSpent is called when the inputs are spent by a unknown tx. It
1228
// will notify the subscriber then remove the record from the maps and send a
1229
// TxUnknownSpend event to the subscriber.
1230
//
1231
// NOTE: Must be run as a goroutine to avoid blocking on sending the result.
1232
func (t *TxPublisher) handleUnknownSpent(r *monitorRecord) {
2✔
1233
        defer t.wg.Done()
2✔
1234

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

2✔
1239
        // Create a result that will be sent to the resultChan which is listened
2✔
1240
        // by the caller.
2✔
1241
        result := t.createUnknownSpentBumpResult(r)
2✔
1242

2✔
1243
        // Notify the sweeper about this result in the end.
2✔
1244
        t.handleResult(result)
2✔
1245
}
2✔
1246

1247
// createUnknownSpentBumpResult creates and returns a BumpResult given the
1248
// monitored record has unknown spends.
1249
func (t *TxPublisher) createUnknownSpentBumpResult(
1250
        r *monitorRecord) *BumpResult {
2✔
1251

2✔
1252
        // Create a result that will be sent to the resultChan which is listened
2✔
1253
        // by the caller.
2✔
1254
        result := &BumpResult{
2✔
1255
                Event:       TxUnknownSpend,
2✔
1256
                Tx:          r.tx,
2✔
1257
                requestID:   r.requestID,
2✔
1258
                Err:         ErrUnknownSpent,
2✔
1259
                SpentInputs: r.spentInputs,
2✔
1260
        }
2✔
1261

2✔
1262
        // Get the fee function, which will be used to decided the next fee rate
2✔
1263
        // to use if the sweeper decides to retry sweeping this input.
2✔
1264
        feeFunc := r.feeFunction
2✔
1265

2✔
1266
        // When the record is failed before the initial broadcast is attempted,
2✔
1267
        // it will have a nil fee func. In this case, we'll create the fee func
2✔
1268
        // here.
2✔
1269
        //
2✔
1270
        // NOTE: Since the current record is failed and will be deleted, we
2✔
1271
        // don't need to update the record on this fee function. We only need
2✔
1272
        // the fee rate data so the sweeper can pick up where we left off.
2✔
1273
        if feeFunc == nil {
3✔
1274
                f, err := t.initializeFeeFunction(r.req)
1✔
1275
                // TODO(yy): The only error we would receive here is when the
1✔
1276
                // pkScript is not recognized by the weightEstimator. What we
1✔
1277
                // should do instead is to check the pkScript immediately after
1✔
1278
                // receiving a sweep request so we don't need to check it again,
1✔
1279
                // which will also save us from error checking from several
1✔
1280
                // callsites.
1✔
1281
                if err != nil {
1✔
1282
                        log.Errorf("Failed to create fee func for record %v: "+
×
1283
                                "%v", r.requestID, err)
×
1284

×
1285
                        // Overwrite the event and error so the sweeper will
×
1286
                        // remove this input.
×
1287
                        result.Event = TxFatal
×
1288
                        result.Err = err
×
1289

×
1290
                        return result
×
1291
                }
×
1292

1293
                feeFunc = f
1✔
1294
        }
1295

1296
        // Since the sweeping tx has been replaced by another party's tx, we
1297
        // missed this block window to increase its fee rate. To make sure the
1298
        // fee rate stays in the initial line, we now ask the fee function to
1299
        // give us the next fee rate as if the sweeping tx were RBFed. This new
1300
        // fee rate will be used as the starting fee rate if the upper system
1301
        // decides to continue sweeping the rest of the inputs.
1302
        _, err := feeFunc.Increment()
2✔
1303
        if err != nil {
3✔
1304
                // The fee function has reached its max position - nothing we
1✔
1305
                // can do here other than letting the user increase the budget.
1✔
1306
                log.Errorf("Failed to calculate the next fee rate for "+
1✔
1307
                        "Record(%v): %v", r.requestID, err)
1✔
1308
        }
1✔
1309

1310
        // Attach the new fee rate to be used for the next sweeping attempt.
1311
        result.FeeRate = feeFunc.FeeRate()
2✔
1312

2✔
1313
        return result
2✔
1314
}
1315

1316
// createAndPublishTx creates a new tx with a higher fee rate and publishes it
1317
// to the network. It will update the record with the new tx and fee rate if
1318
// successfully created, and return the result when published successfully.
1319
func (t *TxPublisher) createAndPublishTx(
1320
        r *monitorRecord) fn.Option[BumpResult] {
7✔
1321

7✔
1322
        // Fetch the old tx.
7✔
1323
        oldTx := r.tx
7✔
1324

7✔
1325
        // Create a new tx with the new fee rate.
7✔
1326
        //
7✔
1327
        // NOTE: The fee function is expected to have increased its returned
7✔
1328
        // fee rate after calling the SkipFeeBump method. So we can use it
7✔
1329
        // directly here.
7✔
1330
        sweepCtx, err := t.createAndCheckTx(r)
7✔
1331

7✔
1332
        // If there's an error creating the replacement tx, we need to abort the
7✔
1333
        // flow and handle it.
7✔
1334
        if err != nil {
10✔
1335
                return t.handleReplacementTxError(r, oldTx, err)
3✔
1336
        }
3✔
1337

1338
        // The tx has been created without any errors, we now register a new
1339
        // record by overwriting the same requestID.
1340
        record := t.updateRecord(r, sweepCtx)
4✔
1341

4✔
1342
        // Attempt to broadcast this new tx.
4✔
1343
        result, err := t.broadcast(record)
4✔
1344
        if err != nil {
4✔
1345
                log.Infof("Failed to broadcast replacement tx %v: %v",
×
1346
                        sweepCtx.tx.TxHash(), err)
×
1347

×
1348
                return fn.None[BumpResult]()
×
1349
        }
×
1350

1351
        // If the result error is fee related, we will return no error and let
1352
        // the fee bumper retry it at next block.
1353
        //
1354
        // NOTE: we may get this error if we've bypassed the mempool check,
1355
        // which means we are suing neutrino backend.
1356
        if errors.Is(result.Err, chain.ErrInsufficientFee) ||
4✔
1357
                errors.Is(result.Err, lnwallet.ErrMempoolFee) {
4✔
UNCOV
1358

×
UNCOV
1359
                log.Debugf("Failed to bump tx %v: %v", oldTx.TxHash(),
×
UNCOV
1360
                        result.Err)
×
UNCOV
1361

×
UNCOV
1362
                return fn.None[BumpResult]()
×
UNCOV
1363
        }
×
1364

1365
        // A successful replacement tx is created, attach the old tx.
1366
        result.ReplacedTx = oldTx
4✔
1367

4✔
1368
        // If the new tx failed to be published, we will return the result so
4✔
1369
        // the caller can handle it.
4✔
1370
        if result.Event == TxFailed {
5✔
1371
                return fn.Some(*result)
1✔
1372
        }
1✔
1373

1374
        log.Infof("Replaced tx=%v with new tx=%v", oldTx.TxHash(),
3✔
1375
                sweepCtx.tx.TxHash())
3✔
1376

3✔
1377
        // Otherwise, it's a successful RBF, set the event and return.
3✔
1378
        result.Event = TxReplaced
3✔
1379

3✔
1380
        return fn.Some(*result)
3✔
1381
}
1382

1383
// isUnknownSpent checks whether the inputs of the tx has already been spent by
1384
// a tx not known to us. When a tx is not confirmed, yet its inputs has been
1385
// spent, then it must be spent by a different tx other than the sweeping tx
1386
// here.
1387
func (t *TxPublisher) isUnknownSpent(r *monitorRecord,
1388
        spends map[wire.OutPoint]*wire.MsgTx) bool {
2✔
1389

2✔
1390
        txid := r.tx.TxHash()
2✔
1391

2✔
1392
        // Iterate all the spending txns and check if they match the sweeping
2✔
1393
        // tx.
2✔
1394
        for op, spendingTx := range spends {
4✔
1395
                spendingTxID := spendingTx.TxHash()
2✔
1396

2✔
1397
                // If the spending tx is the same as the sweeping tx then we are
2✔
1398
                // good.
2✔
1399
                if spendingTxID == txid {
3✔
1400
                        continue
1✔
1401
                }
1402

1403
                log.Warnf("Detected unknown spend of input=%v in tx=%v", op,
1✔
1404
                        spendingTx.TxHash())
1✔
1405

1✔
1406
                return true
1✔
1407
        }
1408

1409
        return false
1✔
1410
}
1411

1412
// getSpentInputs performs a non-blocking read on the spending subscriptions to
1413
// see whether any of the monitored inputs has been spent. A map of inputs with
1414
// their spending txns are returned if found.
1415
func (t *TxPublisher) getSpentInputs(
1416
        r *monitorRecord) map[wire.OutPoint]*wire.MsgTx {
6✔
1417

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

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

8✔
1425
                // For wallet utxos, the height hint is not set - we don't need
8✔
1426
                // to monitor them for third party spend.
8✔
1427
                //
8✔
1428
                // TODO(yy): We need to properly lock wallet utxos before
8✔
1429
                // skipping this check as the same wallet utxo can be used by
8✔
1430
                // different sweeping txns.
8✔
1431
                heightHint := inp.HeightHint()
8✔
1432
                if heightHint == 0 {
9✔
1433
                        heightHint = uint32(t.currentHeight.Load())
1✔
1434
                        log.Debugf("Checking wallet input %v using heightHint "+
1✔
1435
                                "%v", op, heightHint)
1✔
1436
                }
1✔
1437

1438
                // If the input has already been spent after the height hint, a
1439
                // spend event is sent back immediately.
1440
                spendEvent, err := t.cfg.Notifier.RegisterSpendNtfn(
8✔
1441
                        &op, inp.SignDesc().Output.PkScript, heightHint,
8✔
1442
                )
8✔
1443
                if err != nil {
8✔
1444
                        log.Criticalf("Failed to register spend ntfn for "+
×
1445
                                "input=%v: %v", op, err)
×
1446

×
1447
                        return nil
×
1448
                }
×
1449

1450
                // Remove the subscription when exit.
1451
                defer spendEvent.Cancel()
8✔
1452

8✔
1453
                // Do a non-blocking read to see if the output has been spent.
8✔
1454
                select {
8✔
1455
                case spend, ok := <-spendEvent.Spend:
4✔
1456
                        if !ok {
4✔
1457
                                log.Debugf("Spend ntfn for %v canceled", op)
×
1458

×
1459
                                continue
×
1460
                        }
1461

1462
                        spendingTx := spend.SpendingTx
4✔
1463

4✔
1464
                        log.Debugf("Detected spent of input=%v in tx=%v", op,
4✔
1465
                                spendingTx.TxHash())
4✔
1466

4✔
1467
                        spentInputs[op] = spendingTx
4✔
1468

1469
                // Move to the next input.
1470
                default:
4✔
1471
                        log.Tracef("Input %v not spent yet", op)
4✔
1472
                }
1473
        }
1474

1475
        return spentInputs
6✔
1476
}
1477

1478
// calcCurrentConfTarget calculates the current confirmation target based on
1479
// the deadline height. The conf target is capped at 0 if the deadline has
1480
// already been past.
1481
func calcCurrentConfTarget(currentHeight, deadline int32) uint32 {
14✔
1482
        var confTarget uint32
14✔
1483

14✔
1484
        // Calculate how many blocks left until the deadline.
14✔
1485
        deadlineDelta := deadline - currentHeight
14✔
1486

14✔
1487
        // If we are already past the deadline, we will set the conf target to
14✔
1488
        // be 1.
14✔
1489
        if deadlineDelta < 0 {
18✔
1490
                log.Warnf("Deadline is %d blocks behind current height %v",
4✔
1491
                        -deadlineDelta, currentHeight)
4✔
1492

4✔
1493
                confTarget = 0
4✔
1494
        } else {
14✔
1495
                confTarget = uint32(deadlineDelta)
10✔
1496
        }
10✔
1497

1498
        return confTarget
14✔
1499
}
1500

1501
// sweepTxCtx houses a sweep transaction with additional context.
1502
type sweepTxCtx struct {
1503
        tx *wire.MsgTx
1504

1505
        fee btcutil.Amount
1506

1507
        extraTxOut fn.Option[SweepOutput]
1508

1509
        // outpointToTxIndex maps the outpoint of the inputs to their index in
1510
        // the sweep transaction.
1511
        outpointToTxIndex map[wire.OutPoint]int
1512
}
1513

1514
// createSweepTx creates a sweeping tx based on the given inputs, change
1515
// address and fee rate.
1516
func (t *TxPublisher) createSweepTx(inputs []input.Input,
1517
        changePkScript lnwallet.AddrWithKey,
1518
        feeRate chainfee.SatPerKWeight) (*sweepTxCtx, error) {
23✔
1519

23✔
1520
        // Validate and calculate the fee and change amount.
23✔
1521
        txFee, changeOutputsOpt, locktimeOpt, err := prepareSweepTx(
23✔
1522
                inputs, changePkScript, feeRate, t.currentHeight.Load(),
23✔
1523
                t.cfg.AuxSweeper,
23✔
1524
        )
23✔
1525
        if err != nil {
23✔
UNCOV
1526
                return nil, err
×
UNCOV
1527
        }
×
1528

1529
        var (
23✔
1530
                // Create the sweep transaction that we will be building. We
23✔
1531
                // use version 2 as it is required for CSV.
23✔
1532
                sweepTx = wire.NewMsgTx(2)
23✔
1533

23✔
1534
                // We'll add the inputs as we go so we know the final ordering
23✔
1535
                // of inputs to sign.
23✔
1536
                idxs []input.Input
23✔
1537
        )
23✔
1538

23✔
1539
        // We start by adding all inputs that commit to an output. We do this
23✔
1540
        // since the input and output index must stay the same for the
23✔
1541
        // signatures to be valid.
23✔
1542
        outpointToTxIndex := make(map[wire.OutPoint]int)
23✔
1543
        for _, o := range inputs {
46✔
1544
                if o.RequiredTxOut() == nil {
46✔
1545
                        continue
23✔
1546
                }
1547

UNCOV
1548
                idxs = append(idxs, o)
×
UNCOV
1549
                sweepTx.AddTxIn(&wire.TxIn{
×
UNCOV
1550
                        PreviousOutPoint: o.OutPoint(),
×
UNCOV
1551
                        Sequence:         o.BlocksToMaturity(),
×
UNCOV
1552
                })
×
UNCOV
1553
                sweepTx.AddTxOut(o.RequiredTxOut())
×
UNCOV
1554

×
UNCOV
1555
                outpointToTxIndex[o.OutPoint()] = len(sweepTx.TxOut) - 1
×
1556
        }
1557

1558
        // Sum up the value contained in the remaining inputs, and add them to
1559
        // the sweep transaction.
1560
        for _, o := range inputs {
46✔
1561
                if o.RequiredTxOut() != nil {
23✔
UNCOV
1562
                        continue
×
1563
                }
1564

1565
                idxs = append(idxs, o)
23✔
1566
                sweepTx.AddTxIn(&wire.TxIn{
23✔
1567
                        PreviousOutPoint: o.OutPoint(),
23✔
1568
                        Sequence:         o.BlocksToMaturity(),
23✔
1569
                })
23✔
1570
        }
1571

1572
        // If we have change outputs to add, then add it the sweep transaction
1573
        // here.
1574
        changeOutputsOpt.WhenSome(func(changeOuts []SweepOutput) {
46✔
1575
                for i := range changeOuts {
69✔
1576
                        sweepTx.AddTxOut(&changeOuts[i].TxOut)
46✔
1577
                }
46✔
1578
        })
1579

1580
        // We'll default to using the current block height as locktime, if none
1581
        // of the inputs commits to a different locktime.
1582
        sweepTx.LockTime = uint32(locktimeOpt.UnwrapOr(t.currentHeight.Load()))
23✔
1583

23✔
1584
        prevInputFetcher, err := input.MultiPrevOutFetcher(inputs)
23✔
1585
        if err != nil {
23✔
1586
                return nil, fmt.Errorf("error creating prev input fetcher "+
×
1587
                        "for hash cache: %v", err)
×
1588
        }
×
1589
        hashCache := txscript.NewTxSigHashes(sweepTx, prevInputFetcher)
23✔
1590

23✔
1591
        // With all the inputs in place, use each output's unique input script
23✔
1592
        // function to generate the final witness required for spending.
23✔
1593
        addInputScript := func(idx int, tso input.Input) error {
46✔
1594
                inputScript, err := tso.CraftInputScript(
23✔
1595
                        t.cfg.Signer, sweepTx, hashCache, prevInputFetcher, idx,
23✔
1596
                )
23✔
1597
                if err != nil {
23✔
1598
                        return err
×
1599
                }
×
1600

1601
                sweepTx.TxIn[idx].Witness = inputScript.Witness
23✔
1602

23✔
1603
                if len(inputScript.SigScript) == 0 {
46✔
1604
                        return nil
23✔
1605
                }
23✔
1606

1607
                sweepTx.TxIn[idx].SignatureScript = inputScript.SigScript
×
1608

×
1609
                return nil
×
1610
        }
1611

1612
        for idx, inp := range idxs {
46✔
1613
                if err := addInputScript(idx, inp); err != nil {
23✔
1614
                        return nil, err
×
1615
                }
×
1616
        }
1617

1618
        log.Debugf("Created sweep tx %v for inputs:\n%v", sweepTx.TxHash(),
23✔
1619
                inputTypeSummary(inputs))
23✔
1620

23✔
1621
        // Try to locate the extra change output, though there might be None.
23✔
1622
        extraTxOut := fn.MapOption(
23✔
1623
                func(sweepOuts []SweepOutput) fn.Option[SweepOutput] {
46✔
1624
                        for _, sweepOut := range sweepOuts {
69✔
1625
                                if !sweepOut.IsExtra {
92✔
1626
                                        continue
46✔
1627
                                }
1628

1629
                                // If we sweep outputs of a custom channel, the
1630
                                // custom leaves in those outputs will be merged
1631
                                // into a single output, even if we sweep
1632
                                // multiple outputs (e.g. to_remote and breached
1633
                                // to_local of a breached channel) at the same
1634
                                // time. So there will only ever be one extra
1635
                                // output.
1636
                                log.Debugf("Sweep produced extra_sweep_out=%v",
×
1637
                                        lnutils.SpewLogClosure(sweepOut))
×
1638

×
1639
                                return fn.Some(sweepOut)
×
1640
                        }
1641

1642
                        return fn.None[SweepOutput]()
23✔
1643
                },
1644
        )(changeOutputsOpt)
1645

1646
        return &sweepTxCtx{
23✔
1647
                tx:                sweepTx,
23✔
1648
                fee:               txFee,
23✔
1649
                extraTxOut:        fn.FlattenOption(extraTxOut),
23✔
1650
                outpointToTxIndex: outpointToTxIndex,
23✔
1651
        }, nil
23✔
1652
}
1653

1654
// prepareSweepTx returns the tx fee, a set of optional change outputs and an
1655
// optional locktime after a series of validations:
1656
// 1. check the locktime has been reached.
1657
// 2. check the locktimes are the same.
1658
// 3. check the inputs cover the outputs.
1659
//
1660
// NOTE: if the change amount is below dust, it will be added to the tx fee.
1661
func prepareSweepTx(inputs []input.Input, changePkScript lnwallet.AddrWithKey,
1662
        feeRate chainfee.SatPerKWeight, currentHeight int32,
1663
        auxSweeper fn.Option[AuxSweeper]) (
1664
        btcutil.Amount, fn.Option[[]SweepOutput], fn.Option[int32], error) {
23✔
1665

23✔
1666
        noChange := fn.None[[]SweepOutput]()
23✔
1667
        noLocktime := fn.None[int32]()
23✔
1668

23✔
1669
        // Given the set of inputs we have, if we have an aux sweeper, then
23✔
1670
        // we'll attempt to see if we have any other change outputs we'll need
23✔
1671
        // to add to the sweep transaction.
23✔
1672
        changePkScripts := [][]byte{changePkScript.DeliveryAddress}
23✔
1673

23✔
1674
        var extraChangeOut fn.Option[SweepOutput]
23✔
1675
        err := fn.MapOptionZ(
23✔
1676
                auxSweeper, func(aux AuxSweeper) error {
46✔
1677
                        extraOut := aux.DeriveSweepAddr(inputs, changePkScript)
23✔
1678
                        if err := extraOut.Err(); err != nil {
23✔
1679
                                return err
×
1680
                        }
×
1681

1682
                        extraChangeOut = extraOut.LeftToSome()
23✔
1683

23✔
1684
                        return nil
23✔
1685
                },
1686
        )
1687
        if err != nil {
23✔
1688
                return 0, noChange, noLocktime, err
×
1689
        }
×
1690

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

1701
        txFee := estimator.fee()
23✔
1702

23✔
1703
        var (
23✔
1704
                // Track whether any of the inputs require a certain locktime.
23✔
1705
                locktime = int32(-1)
23✔
1706

23✔
1707
                // We keep track of total input amount, and required output
23✔
1708
                // amount to use for calculating the change amount below.
23✔
1709
                totalInput     btcutil.Amount
23✔
1710
                requiredOutput btcutil.Amount
23✔
1711
        )
23✔
1712

23✔
1713
        // If we have an extra change output, then we'll add it as a required
23✔
1714
        // output amt.
23✔
1715
        extraChangeOut.WhenSome(func(o SweepOutput) {
46✔
1716
                requiredOutput += btcutil.Amount(o.Value)
23✔
1717
        })
23✔
1718

1719
        // Go through each input and check if the required lock times have
1720
        // reached and are the same.
1721
        for _, o := range inputs {
46✔
1722
                // If the input has a required output, we'll add it to the
23✔
1723
                // required output amount.
23✔
1724
                if o.RequiredTxOut() != nil {
23✔
UNCOV
1725
                        requiredOutput += btcutil.Amount(
×
UNCOV
1726
                                o.RequiredTxOut().Value,
×
UNCOV
1727
                        )
×
UNCOV
1728
                }
×
1729

1730
                // Update the total input amount.
1731
                totalInput += btcutil.Amount(o.SignDesc().Output.Value)
23✔
1732

23✔
1733
                lt, ok := o.RequiredLockTime()
23✔
1734

23✔
1735
                // Skip if the input doesn't require a lock time.
23✔
1736
                if !ok {
46✔
1737
                        continue
23✔
1738
                }
1739

1740
                // Check if the lock time has reached
UNCOV
1741
                if lt > uint32(currentHeight) {
×
1742
                        return 0, noChange, noLocktime,
×
1743
                                fmt.Errorf("%w: current height is %v, "+
×
1744
                                        "locktime is %v", ErrLocktimeImmature,
×
1745
                                        currentHeight, lt)
×
1746
                }
×
1747

1748
                // If another input commits to a different locktime, they
1749
                // cannot be combined in the same transaction.
UNCOV
1750
                if locktime != -1 && locktime != int32(lt) {
×
1751
                        return 0, noChange, noLocktime, ErrLocktimeConflict
×
1752
                }
×
1753

1754
                // Update the locktime for next iteration.
UNCOV
1755
                locktime = int32(lt)
×
1756
        }
1757

1758
        // Make sure total output amount is less than total input amount.
1759
        if requiredOutput+txFee > totalInput {
23✔
UNCOV
1760
                return 0, noChange, noLocktime, fmt.Errorf("insufficient "+
×
UNCOV
1761
                        "input to create sweep tx: input_sum=%v, "+
×
UNCOV
1762
                        "output_sum=%v", totalInput, requiredOutput+txFee)
×
UNCOV
1763
        }
×
1764

1765
        // The value remaining after the required output and fees is the
1766
        // change output.
1767
        changeAmt := totalInput - requiredOutput - txFee
23✔
1768
        changeOuts := make([]SweepOutput, 0, 2)
23✔
1769

23✔
1770
        extraChangeOut.WhenSome(func(o SweepOutput) {
46✔
1771
                changeOuts = append(changeOuts, o)
23✔
1772
        })
23✔
1773

1774
        // We'll calculate the dust limit for the given changePkScript since it
1775
        // is variable.
1776
        changeFloor := lnwallet.DustLimitForSize(
23✔
1777
                len(changePkScript.DeliveryAddress),
23✔
1778
        )
23✔
1779

23✔
1780
        switch {
23✔
1781
        // If the change amount is dust, we'll move it into the fees, and
1782
        // ignore it.
UNCOV
1783
        case changeAmt < changeFloor:
×
UNCOV
1784
                log.Infof("Change amt %v below dustlimit %v, not adding "+
×
UNCOV
1785
                        "change output", changeAmt, changeFloor)
×
UNCOV
1786

×
UNCOV
1787
                // If there's no required output, and the change output is a
×
UNCOV
1788
                // dust, it means we are creating a tx without any outputs. In
×
UNCOV
1789
                // this case we'll return an error. This could happen when
×
UNCOV
1790
                // creating a tx that has an anchor as the only input.
×
UNCOV
1791
                if requiredOutput == 0 {
×
UNCOV
1792
                        return 0, noChange, noLocktime, ErrTxNoOutput
×
UNCOV
1793
                }
×
1794

1795
                // The dust amount is added to the fee.
1796
                txFee += changeAmt
×
1797

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

1810
        // Optionally set the locktime.
1811
        locktimeOpt := fn.Some(locktime)
23✔
1812
        if locktime == -1 {
46✔
1813
                locktimeOpt = noLocktime
23✔
1814
        }
23✔
1815

1816
        var changeOutsOpt fn.Option[[]SweepOutput]
23✔
1817
        if len(changeOuts) > 0 {
46✔
1818
                changeOutsOpt = fn.Some(changeOuts)
23✔
1819
        }
23✔
1820

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

23✔
1828
        return txFee, changeOutsOpt, locktimeOpt, nil
23✔
1829
}
1830

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

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

2✔
1850
                log.Debugf("Failed to bump tx %v: %v", oldTx.TxHash(), err)
2✔
1851
                return fn.None[BumpResult]()
2✔
1852
        }
2✔
1853

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

×
1861
                return fn.Some(*bumpResult)
×
1862
        }
×
1863

1864
        // If the error is not fee related, we will return a `TxFailed` event
1865
        // so this input can be retried.
1866
        result := fn.Some(BumpResult{
1✔
1867
                Event:     TxFailed,
1✔
1868
                Tx:        oldTx,
1✔
1869
                Err:       err,
1✔
1870
                requestID: r.requestID,
1✔
1871
        })
1✔
1872

1✔
1873
        // If the tx doesn't not have enought budget, we will return a result so
1✔
1874
        // the sweeper can handle it by re-clustering the utxos.
1✔
1875
        if errors.Is(err, ErrNotEnoughBudget) {
2✔
1876
                log.Warnf("Fail to fee bump tx %v: %v", oldTx.TxHash(), err)
1✔
1877
                return result
1✔
1878
        }
1✔
1879

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

×
1884
        return result
×
1885
}
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