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

lightningnetwork / lnd / 13986536491

21 Mar 2025 07:12AM UTC coverage: 68.805% (+9.7%) from 59.126%
13986536491

Pull #9627

github

web-flow
Merge 071ed001a into 5d921723b
Pull Request #9627: Sweep inputs even the budget cannot be covered

113 of 159 new or added lines in 6 files covered. (71.07%)

18 existing lines in 4 files now uncovered.

131503 of 191123 relevant lines covered (68.81%)

23375.23 hits per line

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

95.02
/sweep/tx_input_set.go
1
package sweep
2

3
import (
4
        "fmt"
5
        "math"
6
        "sort"
7

8
        "github.com/btcsuite/btcd/btcutil"
9
        "github.com/btcsuite/btcd/txscript"
10
        "github.com/btcsuite/btcd/wire"
11
        "github.com/lightningnetwork/lnd/fn/v2"
12
        "github.com/lightningnetwork/lnd/input"
13
        "github.com/lightningnetwork/lnd/lnwallet"
14
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
15
)
16

17
var (
18
        // ErrNotEnoughInputs is returned when there are not enough wallet
19
        // inputs to construct a non-dust change output for an input set.
20
        ErrNotEnoughInputs = fmt.Errorf("not enough inputs")
21

22
        // ErrDeadlinesMismatch is returned when the deadlines of the input
23
        // sets do not match.
24
        ErrDeadlinesMismatch = fmt.Errorf("deadlines mismatch")
25

26
        // ErrDustOutput is returned when the output value is below the dust
27
        // limit.
28
        ErrDustOutput = fmt.Errorf("dust output")
29
)
30

31
// InputSet defines an interface that's responsible for filtering a set of
32
// inputs that can be swept economically.
33
type InputSet interface {
34
        // Inputs returns the set of inputs that should be used to create a tx.
35
        Inputs() []input.Input
36

37
        // AddWalletInputs adds wallet inputs to the set until a non-dust
38
        // change output can be made. Return an error if there are not enough
39
        // wallet inputs.
40
        AddWalletInputs(wallet Wallet) error
41

42
        // NeedWalletInput returns true if the input set needs more wallet
43
        // inputs.
44
        NeedWalletInput() bool
45

46
        // DeadlineHeight returns an absolute block height to express the
47
        // time-sensitivity of the input set. The outputs from a force close tx
48
        // have different time preferences:
49
        // - to_local: no time pressure as it can only be swept by us.
50
        // - first level outgoing HTLC: must be swept before its corresponding
51
        //   incoming HTLC's CLTV is reached.
52
        // - first level incoming HTLC: must be swept before its CLTV is
53
        //   reached.
54
        // - second level HTLCs: no time pressure.
55
        // - anchor: for CPFP-purpose anchor, it must be swept before any of
56
        //   the above CLTVs is reached. For non-CPFP purpose anchor, there's
57
        //   no time pressure.
58
        DeadlineHeight() int32
59

60
        // Budget givens the total amount that can be used as fees by this
61
        // input set.
62
        Budget() btcutil.Amount
63

64
        // StartingFeeRate returns the max starting fee rate found in the
65
        // inputs.
66
        StartingFeeRate() fn.Option[chainfee.SatPerKWeight]
67

68
        // Immediate returns a boolean to indicate whether the tx made from
69
        // this input set should be published immediately.
70
        //
71
        // TODO(yy): create a new method `Params` to combine the informational
72
        // methods DeadlineHeight, Budget, StartingFeeRate and Immediate.
73
        Immediate() bool
74
}
75

76
// createWalletTxInput converts a wallet utxo into an object that can be added
77
// to the other inputs to sweep.
78
func createWalletTxInput(utxo *lnwallet.Utxo) (input.Input, error) {
9✔
79
        signDesc := &input.SignDescriptor{
9✔
80
                Output: &wire.TxOut{
9✔
81
                        PkScript: utxo.PkScript,
9✔
82
                        Value:    int64(utxo.Value),
9✔
83
                },
9✔
84
                HashType: txscript.SigHashAll,
9✔
85
        }
9✔
86

9✔
87
        var witnessType input.WitnessType
9✔
88
        switch utxo.AddressType {
9✔
89
        case lnwallet.WitnessPubKey:
7✔
90
                witnessType = input.WitnessKeyHash
7✔
91
        case lnwallet.NestedWitnessPubKey:
×
92
                witnessType = input.NestedWitnessKeyHash
×
93
        case lnwallet.TaprootPubkey:
3✔
94
                witnessType = input.TaprootPubKeySpend
3✔
95
                signDesc.HashType = txscript.SigHashDefault
3✔
96
        default:
2✔
97
                return nil, fmt.Errorf("unknown address type %v",
2✔
98
                        utxo.AddressType)
2✔
99
        }
100

101
        // A height hint doesn't need to be set, because we don't monitor these
102
        // inputs for spend.
103
        heightHint := uint32(0)
7✔
104

7✔
105
        return input.NewBaseInput(
7✔
106
                &utxo.OutPoint, witnessType, signDesc, heightHint,
7✔
107
        ), nil
7✔
108
}
109

110
// BudgetInputSet implements the interface `InputSet`. It takes a list of
111
// pending inputs which share the same deadline height and groups them into a
112
// set conditionally based on their economical values.
113
type BudgetInputSet struct {
114
        // inputs is the set of inputs that have been added to the set after
115
        // considering their economical contribution.
116
        inputs []*SweeperInput
117

118
        // deadlineHeight is the height which the inputs in this set must be
119
        // confirmed by.
120
        deadlineHeight int32
121

122
        // extraBudget is a value that should be allocated to sweep the given
123
        // set of inputs. This can be used to add extra funds to the sweep
124
        // transaction, for example to cover fees for additional outputs of
125
        // custom channels.
126
        extraBudget btcutil.Amount
127
}
128

129
// Compile-time constraint to ensure budgetInputSet implements InputSet.
130
var _ InputSet = (*BudgetInputSet)(nil)
131

132
// errEmptyInputs is returned when the input slice is empty.
133
var errEmptyInputs = fmt.Errorf("inputs slice is empty")
134

135
// validateInputs is used when creating new BudgetInputSet to ensure there are
136
// no duplicate inputs and they all share the same deadline heights, if set.
137
func validateInputs(inputs []SweeperInput, deadlineHeight int32) error {
27✔
138
        // Sanity check the input slice to ensure it's non-empty.
27✔
139
        if len(inputs) == 0 {
29✔
140
                return errEmptyInputs
2✔
141
        }
2✔
142

143
        // inputDeadline tracks the input's deadline height. It will be updated
144
        // if the input has a different deadline than the specified
145
        // deadlineHeight.
146
        inputDeadline := deadlineHeight
25✔
147

25✔
148
        // dedupInputs is a set used to track unique outpoints of the inputs.
25✔
149
        dedupInputs := fn.NewSet(
25✔
150
                // Iterate all the inputs and map the function.
25✔
151
                fn.Map(inputs, func(inp SweeperInput) wire.OutPoint {
62✔
152
                        // If the input has a deadline height, we'll check if
37✔
153
                        // it's the same as the specified.
37✔
154
                        inp.params.DeadlineHeight.WhenSome(func(h int32) {
56✔
155
                                // Exit early if the deadlines matched.
19✔
156
                                if h == deadlineHeight {
34✔
157
                                        return
15✔
158
                                }
15✔
159

160
                                // Update the deadline height if it's
161
                                // different.
162
                                inputDeadline = h
4✔
163
                        })
164

165
                        return inp.OutPoint()
37✔
166
                })...,
167
        )
168

169
        // Make sure the inputs share the same deadline height when there is
170
        // one.
171
        if inputDeadline != deadlineHeight {
28✔
172
                return fmt.Errorf("input deadline height not matched: want "+
3✔
173
                        "%d, got %d", deadlineHeight, inputDeadline)
3✔
174
        }
3✔
175

176
        // Provide a defensive check to ensure that we don't have any duplicate
177
        // inputs within the set.
178
        if len(dedupInputs) != len(inputs) {
23✔
179
                return fmt.Errorf("duplicate inputs")
1✔
180
        }
1✔
181

182
        return nil
21✔
183
}
184

185
// NewBudgetInputSet creates a new BudgetInputSet.
186
func NewBudgetInputSet(inputs []SweeperInput, deadlineHeight int32,
187
        auxSweeper fn.Option[AuxSweeper]) (*BudgetInputSet, error) {
27✔
188

27✔
189
        // Validate the supplied inputs.
27✔
190
        if err := validateInputs(inputs, deadlineHeight); err != nil {
33✔
191
                return nil, err
6✔
192
        }
6✔
193

194
        bi := &BudgetInputSet{
21✔
195
                deadlineHeight: deadlineHeight,
21✔
196
                inputs:         make([]*SweeperInput, 0, len(inputs)),
21✔
197
        }
21✔
198

21✔
199
        for _, input := range inputs {
50✔
200
                bi.addInput(input)
29✔
201
        }
29✔
202

203
        log.Tracef("Created %v", bi.String())
21✔
204

21✔
205
        // Attach an optional budget. This will be a no-op if the auxSweeper
21✔
206
        // is not set.
21✔
207
        if err := bi.attachExtraBudget(auxSweeper); err != nil {
21✔
208
                return nil, err
×
209
        }
×
210

211
        return bi, nil
21✔
212
}
213

214
// attachExtraBudget attaches an extra budget to the input set, if the passed
215
// aux sweeper is set.
216
func (b *BudgetInputSet) attachExtraBudget(s fn.Option[AuxSweeper]) error {
21✔
217
        extraBudget, err := fn.MapOptionZ(
21✔
218
                s, func(aux AuxSweeper) fn.Result[btcutil.Amount] {
27✔
219
                        return aux.ExtraBudgetForInputs(b.Inputs())
6✔
220
                },
6✔
221
        ).Unpack()
222
        if err != nil {
21✔
223
                return err
×
224
        }
×
225

226
        b.extraBudget = extraBudget
21✔
227

21✔
228
        return nil
21✔
229
}
230

231
// String returns a human-readable description of the input set.
232
func (b *BudgetInputSet) String() string {
21✔
233
        inputsDesc := ""
21✔
234
        for _, input := range b.inputs {
50✔
235
                inputsDesc += fmt.Sprintf("\n%v", input)
29✔
236
        }
29✔
237

238
        return fmt.Sprintf("BudgetInputSet(budget=%v, deadline=%v, "+
21✔
239
                "inputs=[%v])", b.Budget(), b.DeadlineHeight(), inputsDesc)
21✔
240
}
241

242
// addInput adds an input to the input set.
243
func (b *BudgetInputSet) addInput(input SweeperInput) {
34✔
244
        b.inputs = append(b.inputs, &input)
34✔
245
}
34✔
246

247
// addWalletInput takes a wallet UTXO and adds it as an input to be used as
248
// budget for the input set.
249
func (b *BudgetInputSet) addWalletInput(utxo *lnwallet.Utxo) error {
9✔
250
        input, err := createWalletTxInput(utxo)
9✔
251
        if err != nil {
11✔
252
                return err
2✔
253
        }
2✔
254

255
        pi := SweeperInput{
7✔
256
                Input: input,
7✔
257
                params: Params{
7✔
258
                        DeadlineHeight: fn.Some(b.deadlineHeight),
7✔
259
                },
7✔
260
        }
7✔
261
        b.addInput(pi)
7✔
262

7✔
263
        log.Debugf("Added wallet input to input set: op=%v, amt=%v",
7✔
264
                pi.OutPoint(), utxo.Value)
7✔
265

7✔
266
        return nil
7✔
267
}
268

269
// NeedWalletInput returns true if the input set needs more wallet inputs.
270
//
271
// A set may need wallet inputs when it has a required output or its total
272
// value cannot cover its total budget.
273
func (b *BudgetInputSet) NeedWalletInput() bool {
12✔
274
        var (
12✔
275
                // budgetNeeded is the amount that needs to be covered from
12✔
276
                // other inputs. We start at the value of the extra budget,
12✔
277
                // which might be needed for custom channels that add extra
12✔
278
                // outputs.
12✔
279
                budgetNeeded = b.extraBudget
12✔
280

12✔
281
                // budgetBorrowable is the amount that can be borrowed from
12✔
282
                // other inputs.
12✔
283
                budgetBorrowable btcutil.Amount
12✔
284
        )
12✔
285

12✔
286
        for _, inp := range b.inputs {
30✔
287
                // If this input has a required output, we can assume it's a
18✔
288
                // second-level htlc txns input. Although this input must have
18✔
289
                // a value that can cover its budget, it cannot be used to pay
18✔
290
                // fees. Instead, we need to borrow budget from other inputs to
18✔
291
                // make the sweep happen. Once swept, the input value will be
18✔
292
                // credited to the wallet.
18✔
293
                if inp.RequiredTxOut() != nil {
27✔
294
                        budgetNeeded += inp.params.Budget
9✔
295
                        continue
9✔
296
                }
297

298
                // Get the amount left after covering the input's own budget.
299
                // This amount can then be lent to the above input. For a wallet
300
                // input, its `Budget`` is set to zero, which means the whole
301
                // input can be borrowed to cover the budget.
302
                budget := inp.params.Budget
12✔
303
                output := btcutil.Amount(inp.SignDesc().Output.Value)
12✔
304
                budgetBorrowable += output - budget
12✔
305

12✔
306
                // If the input's budget is not even covered by itself, we need
12✔
307
                // to borrow outputs from other inputs.
12✔
308
                if budgetBorrowable < 0 {
16✔
309
                        log.Tracef("Input %v specified a budget that exceeds "+
4✔
310
                                "its output value: %v > %v", inp, budget,
4✔
311
                                output)
4✔
312
                }
4✔
313
        }
314

315
        log.Debugf("NeedWalletInput: budgetNeeded=%v, budgetBorrowable=%v",
12✔
316
                budgetNeeded, budgetBorrowable)
12✔
317

12✔
318
        // If we don't have enough extra budget to borrow, we need wallet
12✔
319
        // inputs.
12✔
320
        return budgetBorrowable < budgetNeeded
12✔
321
}
322

323
// copyInputs returns a copy of the slice of the inputs in the set.
UNCOV
324
func (b *BudgetInputSet) copyInputs() []*SweeperInput {
×
UNCOV
325
        inputs := make([]*SweeperInput, len(b.inputs))
×
UNCOV
326
        copy(inputs, b.inputs)
×
UNCOV
327
        return inputs
×
UNCOV
328
}
×
329

330
// AddWalletInputs adds wallet inputs to the set until the specified budget is
331
// met. When sweeping inputs with required outputs, although there's budget
332
// specified, it cannot be directly spent from these required outputs. Instead,
333
// we need to borrow budget from other inputs to make the sweep happen.
334
// There are two sources to borrow from: 1) other inputs, 2) wallet utxos. If
335
// we are calling this method, it means other inputs cannot cover the specified
336
// budget, so we need to borrow from wallet utxos.
337
//
338
// Return an error if there are not enough wallet inputs, and the budget set is
339
// set to its initial state by removing any wallet inputs added.
340
//
341
// NOTE: must be called with the wallet lock held via `WithCoinSelectLock`.
342
func (b *BudgetInputSet) AddWalletInputs(wallet Wallet) error {
8✔
343
        // Retrieve wallet utxos. Only consider confirmed utxos to prevent
8✔
344
        // problems around RBF rules for unconfirmed inputs. This currently
8✔
345
        // ignores the configured coin selection strategy.
8✔
346
        utxos, err := wallet.ListUnspentWitnessFromDefaultAccount(
8✔
347
                1, math.MaxInt32,
8✔
348
        )
8✔
349
        if err != nil {
9✔
350
                return fmt.Errorf("list unspent witness: %w", err)
1✔
351
        }
1✔
352

353
        // Exit early if there are no wallet UTXOs.
354
        if len(utxos) == 0 {
11✔
355
                return fmt.Errorf("%w: empty wallet", ErrNotEnoughInputs)
4✔
356
        }
4✔
357

358
        // Sort the UTXOs by putting smaller values at the start of the slice
359
        // to avoid locking large UTXO for sweeping.
360
        //
361
        // TODO(yy): add more choices to CoinSelectionStrategy and use the
362
        // configured value here.
363
        sort.Slice(utxos, func(i, j int) bool {
10✔
364
                return utxos[i].Value < utxos[j].Value
4✔
365
        })
4✔
366

367
        // Add wallet inputs to the set until the specified budget is covered.
368
        for _, utxo := range utxos {
13✔
369
                err := b.addWalletInput(utxo)
7✔
370
                if err != nil {
8✔
371
                        return err
1✔
372
                }
1✔
373

374
                // Return if we've reached the minimum output amount.
375
                if !b.NeedWalletInput() {
10✔
376
                        return nil
4✔
377
                }
4✔
378
        }
379

380
        log.Warn("Not enough wallet UTXOs to cover the budget, sweeping " +
4✔
381
                "anyway...")
4✔
382

4✔
383
        return nil
4✔
384
}
385

386
// Budget returns the total budget of the set.
387
//
388
// NOTE: part of the InputSet interface.
389
func (b *BudgetInputSet) Budget() btcutil.Amount {
26✔
390
        budget := btcutil.Amount(0)
26✔
391
        for _, input := range b.inputs {
66✔
392
                budget += input.params.Budget
40✔
393
        }
40✔
394

395
        // We'll also tack on the extra budget which will eventually be
396
        // accounted for by the wallet txns when we're broadcasting.
397
        return budget + b.extraBudget
26✔
398
}
399

400
// DeadlineHeight returns the deadline height of the set.
401
//
402
// NOTE: part of the InputSet interface.
403
func (b *BudgetInputSet) DeadlineHeight() int32 {
25✔
404
        return b.deadlineHeight
25✔
405
}
25✔
406

407
// Inputs returns the inputs that should be used to create a tx.
408
//
409
// NOTE: part of the InputSet interface.
410
func (b *BudgetInputSet) Inputs() []input.Input {
13✔
411
        inputs := make([]input.Input, 0, len(b.inputs))
13✔
412
        for _, inp := range b.inputs {
31✔
413
                inputs = append(inputs, inp.Input)
18✔
414
        }
18✔
415

416
        return inputs
13✔
417
}
418

419
// StartingFeeRate returns the max starting fee rate found in the inputs.
420
//
421
// NOTE: part of the InputSet interface.
422
func (b *BudgetInputSet) StartingFeeRate() fn.Option[chainfee.SatPerKWeight] {
3✔
423
        maxFeeRate := chainfee.SatPerKWeight(0)
3✔
424
        startingFeeRate := fn.None[chainfee.SatPerKWeight]()
3✔
425

3✔
426
        for _, inp := range b.inputs {
6✔
427
                feerate := inp.params.StartingFeeRate.UnwrapOr(0)
3✔
428
                if feerate > maxFeeRate {
6✔
429
                        maxFeeRate = feerate
3✔
430
                        startingFeeRate = fn.Some(maxFeeRate)
3✔
431
                }
3✔
432
        }
433

434
        return startingFeeRate
3✔
435
}
436

437
// Immediate returns whether the inputs should be swept immediately.
438
//
439
// NOTE: part of the InputSet interface.
440
func (b *BudgetInputSet) Immediate() bool {
3✔
441
        for _, inp := range b.inputs {
6✔
442
                // As long as one of the inputs is immediate, the whole set is
3✔
443
                // immediate.
3✔
444
                if inp.params.Immediate {
6✔
445
                        return true
3✔
446
                }
3✔
447
        }
448

449
        return false
3✔
450
}
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