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

lightningnetwork / lnd / 15951470896

29 Jun 2025 04:23AM UTC coverage: 67.594% (-0.01%) from 67.606%
15951470896

Pull #9751

github

web-flow
Merge 599d9b051 into 6290edf14
Pull Request #9751: multi: update Go to 1.23.10 and update some packages

135088 of 199851 relevant lines covered (67.59%)

21909.44 hits per line

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

96.1
/sweep/aggregator.go
1
package sweep
2

3
import (
4
        "sort"
5

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

15
// UtxoAggregator defines an interface that takes a list of inputs and
16
// aggregate them into groups. Each group is used as the inputs to create a
17
// sweeping transaction.
18
type UtxoAggregator interface {
19
        // ClusterInputs takes a list of inputs and groups them into input
20
        // sets. Each input set will be used to create a sweeping transaction.
21
        ClusterInputs(inputs InputsMap) []InputSet
22
}
23

24
// BudgetAggregator is a budget-based aggregator that creates clusters based on
25
// deadlines and budgets of inputs.
26
type BudgetAggregator struct {
27
        // estimator is used when crafting sweep transactions to estimate the
28
        // necessary fee relative to the expected size of the sweep
29
        // transaction.
30
        estimator chainfee.Estimator
31

32
        // maxInputs specifies the maximum number of inputs allowed in a single
33
        // sweep tx.
34
        maxInputs uint32
35

36
        // auxSweeper is an optional interface that can be used to modify the
37
        // way sweep transaction are generated.
38
        auxSweeper fn.Option[AuxSweeper]
39
}
40

41
// Compile-time constraint to ensure BudgetAggregator implements UtxoAggregator.
42
var _ UtxoAggregator = (*BudgetAggregator)(nil)
43

44
// NewBudgetAggregator creates a new instance of a BudgetAggregator.
45
func NewBudgetAggregator(estimator chainfee.Estimator,
46
        maxInputs uint32, auxSweeper fn.Option[AuxSweeper]) *BudgetAggregator {
7✔
47

7✔
48
        return &BudgetAggregator{
7✔
49
                estimator:  estimator,
7✔
50
                maxInputs:  maxInputs,
7✔
51
                auxSweeper: auxSweeper,
7✔
52
        }
7✔
53
}
7✔
54

55
// clusterGroup defines an alias for a set of inputs that are to be grouped.
56
type clusterGroup map[int32][]SweeperInput
57

58
// ClusterInputs creates a list of input sets from pending inputs.
59
// 1. filter out inputs whose budget cannot cover min relay fee.
60
// 2. filter a list of exclusive inputs.
61
// 3. group the inputs into clusters based on their deadline height.
62
// 4. sort the inputs in each cluster by their budget.
63
// 5. optionally split a cluster if it exceeds the max input limit.
64
// 6. create input sets from each of the clusters.
65
// 7. create input sets for each of the exclusive inputs.
66
func (b *BudgetAggregator) ClusterInputs(inputs InputsMap) []InputSet {
4✔
67
        // Filter out inputs that have a budget below min relay fee.
4✔
68
        filteredInputs := b.filterInputs(inputs)
4✔
69

4✔
70
        // Create clusters to group inputs based on their deadline height.
4✔
71
        clusters := make(clusterGroup, len(filteredInputs))
4✔
72

4✔
73
        // exclusiveInputs is a set of inputs that are not to be included in
4✔
74
        // any cluster. These inputs can only be swept independently as there's
4✔
75
        // no guarantee which input will be confirmed first, which means
4✔
76
        // grouping exclusive inputs may jeopardize non-exclusive inputs.
4✔
77
        exclusiveInputs := make(map[wire.OutPoint]clusterGroup)
4✔
78

4✔
79
        // Iterate all the inputs and group them based on their specified
4✔
80
        // deadline heights.
4✔
81
        for _, input := range filteredInputs {
14✔
82
                // Get deadline height, and use the specified default deadline
10✔
83
                // height if it's not set.
10✔
84
                height := input.DeadlineHeight
10✔
85

10✔
86
                // Put exclusive inputs in their own set.
10✔
87
                if input.params.ExclusiveGroup != nil {
14✔
88
                        log.Tracef("Input %v is exclusive", input.OutPoint())
4✔
89
                        exclusiveInputs[input.OutPoint()] = clusterGroup{
4✔
90
                                height: []SweeperInput{*input},
4✔
91
                        }
4✔
92

4✔
93
                        continue
4✔
94
                }
95

96
                cluster, ok := clusters[height]
9✔
97
                if !ok {
15✔
98
                        cluster = make([]SweeperInput, 0)
6✔
99
                }
6✔
100

101
                cluster = append(cluster, *input)
9✔
102
                clusters[height] = cluster
9✔
103
        }
104

105
        // Now that we have the clusters, we can create the input sets.
106
        //
107
        // NOTE: cannot pre-allocate the slice since we don't know the number
108
        // of input sets in advance.
109
        inputSets := make([]InputSet, 0)
4✔
110
        for height, cluster := range clusters {
10✔
111
                // Sort the inputs by their economical value.
6✔
112
                sortedInputs := b.sortInputs(cluster)
6✔
113

6✔
114
                // Split on locktimes if they are different.
6✔
115
                splitClusters := splitOnLocktime(sortedInputs)
6✔
116

6✔
117
                // Create input sets from the cluster.
6✔
118
                for _, cluster := range splitClusters {
12✔
119
                        sets := b.createInputSets(cluster, height)
6✔
120
                        inputSets = append(inputSets, sets...)
6✔
121
                }
6✔
122
        }
123

124
        // Create input sets from the exclusive inputs.
125
        for _, cluster := range exclusiveInputs {
8✔
126
                for height, input := range cluster {
8✔
127
                        sets := b.createInputSets(input, height)
4✔
128
                        inputSets = append(inputSets, sets...)
4✔
129
                }
4✔
130
        }
131

132
        return inputSets
4✔
133
}
134

135
// createInputSet takes a set of inputs which share the same deadline height
136
// and turns them into a list of `InputSet`, each set is then used to create a
137
// sweep transaction.
138
//
139
// TODO(yy): by the time we call this method, all the invalid/uneconomical
140
// inputs have been filtered out, all the inputs have been sorted based on
141
// their budgets, and we are about to create input sets. The only thing missing
142
// here is, we need to group the inputs here even further based on whether
143
// their budgets can cover the starting fee rate used for this input set.
144
func (b *BudgetAggregator) createInputSets(inputs []SweeperInput,
145
        deadlineHeight int32) []InputSet {
11✔
146

11✔
147
        // sets holds the InputSets that we will return.
11✔
148
        sets := make([]InputSet, 0)
11✔
149

11✔
150
        // Copy the inputs to a new slice so we can modify it.
11✔
151
        remainingInputs := make([]SweeperInput, len(inputs))
11✔
152
        copy(remainingInputs, inputs)
11✔
153

11✔
154
        // If the number of inputs is greater than the max inputs allowed, we
11✔
155
        // will split them into smaller clusters.
11✔
156
        for uint32(len(remainingInputs)) > b.maxInputs {
13✔
157
                log.Tracef("Cluster has %v inputs, max is %v, dividing...",
2✔
158
                        len(inputs), b.maxInputs)
2✔
159

2✔
160
                // Copy the inputs to be put into the new set, and update the
2✔
161
                // remaining inputs by removing currentInputs.
2✔
162
                currentInputs := make([]SweeperInput, b.maxInputs)
2✔
163
                copy(currentInputs, remainingInputs[:b.maxInputs])
2✔
164
                remainingInputs = remainingInputs[b.maxInputs:]
2✔
165

2✔
166
                // Create an InputSet using the max allowed number of inputs.
2✔
167
                set, err := NewBudgetInputSet(
2✔
168
                        currentInputs, deadlineHeight, b.auxSweeper,
2✔
169
                )
2✔
170
                if err != nil {
3✔
171
                        log.Errorf("unable to create input set: %v", err)
1✔
172

1✔
173
                        continue
1✔
174
                }
175

176
                sets = append(sets, set)
1✔
177
        }
178

179
        // Create an InputSet from the remaining inputs.
180
        if len(remainingInputs) > 0 {
22✔
181
                set, err := NewBudgetInputSet(
11✔
182
                        remainingInputs, deadlineHeight, b.auxSweeper,
11✔
183
                )
11✔
184
                if err != nil {
11✔
185
                        log.Errorf("unable to create input set: %v", err)
×
186
                        return nil
×
187
                }
×
188

189
                sets = append(sets, set)
11✔
190
        }
191

192
        return sets
11✔
193
}
194

195
// filterInputs filters out inputs that have,
196
// - a budget below the min relay fee.
197
// - a budget below its requested starting fee.
198
// - a required output that's below the dust.
199
func (b *BudgetAggregator) filterInputs(inputs InputsMap) InputsMap {
5✔
200
        // Get the current min relay fee for this round.
5✔
201
        minFeeRate := b.estimator.RelayFeePerKW()
5✔
202

5✔
203
        // filterInputs stores a map of inputs that has a budget that at least
5✔
204
        // can pay the minimal fee.
5✔
205
        filteredInputs := make(InputsMap, len(inputs))
5✔
206

5✔
207
        // Iterate all the inputs and filter out the ones whose budget cannot
5✔
208
        // cover the min fee.
5✔
209
        for _, pi := range inputs {
23✔
210
                op := pi.OutPoint()
18✔
211

18✔
212
                // Get the size of the witness and skip if there's an error.
18✔
213
                witnessSize, _, err := pi.WitnessType().SizeUpperBound()
18✔
214
                if err != nil {
19✔
215
                        log.Warnf("Skipped input=%v: cannot get its size: %v",
1✔
216
                                op, err)
1✔
217

1✔
218
                        continue
1✔
219
                }
220

221
                //nolint:ll
222
                // Calculate the size if the input is included in the tx.
223
                //
224
                // NOTE: When including this input, we need to account the
225
                // non-witness data which is expressed in vb.
226
                //
227
                // TODO(yy): This is not accurate for tapscript input. We need
228
                // to unify calculations used in the `TxWeightEstimator` inside
229
                // `input/size.go` and `weightEstimator` in
230
                // `weight_estimator.go`. And calculate the expected weights
231
                // similar to BOLT-3:
232
                // https://github.com/lightning/bolts/blob/master/03-transactions.md#appendix-a-expected-weights
233
                wu := lntypes.VByte(input.InputSize).ToWU() + witnessSize
17✔
234

17✔
235
                // Skip inputs that has too little budget.
17✔
236
                minFee := minFeeRate.FeeForWeight(wu)
17✔
237
                if pi.params.Budget < minFee {
24✔
238
                        log.Warnf("Skipped input=%v: has budget=%v, but the "+
7✔
239
                                "min fee requires %v (feerate=%v), size=%v", op,
7✔
240
                                pi.params.Budget, minFee,
7✔
241
                                minFeeRate.FeePerVByte(), wu.ToVB())
7✔
242

7✔
243
                        continue
7✔
244
                }
245

246
                // Skip inputs that has cannot cover its starting fees.
247
                startingFeeRate := pi.params.StartingFeeRate.UnwrapOr(
13✔
248
                        chainfee.SatPerKWeight(0),
13✔
249
                )
13✔
250
                startingFee := startingFeeRate.FeeForWeight(wu)
13✔
251
                if pi.params.Budget < startingFee {
13✔
252
                        log.Errorf("Skipped input=%v: has budget=%v, but the "+
×
253
                                "starting fee requires %v (feerate=%v), "+
×
254
                                "size=%v", op, pi.params.Budget, startingFee,
×
255
                                startingFeeRate.FeePerVByte(), wu.ToVB())
×
256

×
257
                        continue
×
258
                }
259

260
                // If the input comes with a required tx out that is below
261
                // dust, we won't add it.
262
                //
263
                // NOTE: only HtlcSecondLevelAnchorInput returns non-nil
264
                // RequiredTxOut.
265
                reqOut := pi.RequiredTxOut()
13✔
266
                if reqOut != nil {
17✔
267
                        if isDustOutput(reqOut) {
5✔
268
                                log.Errorf("Rejected input=%v due to dust "+
1✔
269
                                        "required output=%v", op, reqOut.Value)
1✔
270

1✔
271
                                continue
1✔
272
                        }
273
                }
274

275
                filteredInputs[op] = pi
12✔
276
        }
277

278
        return filteredInputs
5✔
279
}
280

281
// sortInputs sorts the inputs based on their economical value.
282
//
283
// NOTE: besides the forced inputs, the sorting won't make any difference
284
// because all the inputs are added to the same set. The exception is when the
285
// number of inputs exceeds the maxInputs limit, it requires us to split them
286
// into smaller clusters. In that case, the sorting will make a difference as
287
// the budgets of the clusters will be different.
288
func (b *BudgetAggregator) sortInputs(inputs []SweeperInput) []SweeperInput {
7✔
289
        // sortedInputs is the final list of inputs sorted by their economical
7✔
290
        // value.
7✔
291
        sortedInputs := make([]SweeperInput, 0, len(inputs))
7✔
292

7✔
293
        // Copy the inputs.
7✔
294
        sortedInputs = append(sortedInputs, inputs...)
7✔
295

7✔
296
        // Sort the inputs based on their budgets.
7✔
297
        //
7✔
298
        // NOTE: We can implement more sophisticated algorithm as the budget
7✔
299
        // left is a function f(minFeeRate, size) = b1 - s1 * r > b2 - s2 * r,
7✔
300
        // where b1 and b2 are budgets, s1 and s2 are sizes of the inputs.
7✔
301
        sort.Slice(sortedInputs, func(i, j int) bool {
18✔
302
                left := sortedInputs[i].params.Budget
11✔
303
                right := sortedInputs[j].params.Budget
11✔
304

11✔
305
                // Make sure forced inputs are always put in the front.
11✔
306
                leftForce := sortedInputs[i].params.Immediate
11✔
307
                rightForce := sortedInputs[j].params.Immediate
11✔
308

11✔
309
                // If both are forced inputs, we return the one with the higher
11✔
310
                // budget. If neither are forced inputs, we also return the one
11✔
311
                // with the higher budget.
11✔
312
                if leftForce == rightForce {
19✔
313
                        return left > right
8✔
314
                }
8✔
315

316
                // Otherwise, it's either the left or the right is forced. We
317
                // can simply return `leftForce` here as, if it's true, the
318
                // left is forced and should be put in the front. Otherwise,
319
                // the right is forced and should be put in the front.
320
                return leftForce
3✔
321
        })
322

323
        return sortedInputs
7✔
324
}
325

326
// splitOnLocktime splits the list of inputs based on their locktime.
327
//
328
// TODO(yy): this is a temporary hack as the blocks are not synced among the
329
// contractcourt and the sweeper.
330
func splitOnLocktime(inputs []SweeperInput) map[uint32][]SweeperInput {
8✔
331
        result := make(map[uint32][]SweeperInput)
8✔
332
        noLocktimeInputs := make([]SweeperInput, 0, len(inputs))
8✔
333

8✔
334
        // mergeLocktime is the locktime that we use to merge all the
8✔
335
        // nolocktime inputs into.
8✔
336
        var mergeLocktime uint32
8✔
337

8✔
338
        // Iterate all inputs and split them based on their locktimes.
8✔
339
        for _, inp := range inputs {
25✔
340
                locktime, required := inp.RequiredLockTime()
17✔
341
                if !required {
30✔
342
                        log.Tracef("No locktime required for input=%v",
13✔
343
                                inp.OutPoint())
13✔
344

13✔
345
                        noLocktimeInputs = append(noLocktimeInputs, inp)
13✔
346

13✔
347
                        continue
13✔
348
                }
349

350
                log.Tracef("Split input=%v on locktime=%v", inp.OutPoint(),
7✔
351
                        locktime)
7✔
352

7✔
353
                // Get the slice - the slice will be initialized if not found.
7✔
354
                inputList := result[locktime]
7✔
355

7✔
356
                // Add the input to the list.
7✔
357
                inputList = append(inputList, inp)
7✔
358

7✔
359
                // Update the map.
7✔
360
                result[locktime] = inputList
7✔
361

7✔
362
                // Update the merge locktime.
7✔
363
                mergeLocktime = locktime
7✔
364
        }
365

366
        // If there are locktime inputs, we will merge the no locktime inputs
367
        // to the last locktime group found.
368
        if len(result) > 0 {
12✔
369
                log.Tracef("No locktime inputs has been merged to locktime=%v",
4✔
370
                        mergeLocktime)
4✔
371
                result[mergeLocktime] = append(
4✔
372
                        result[mergeLocktime], noLocktimeInputs...,
4✔
373
                )
4✔
374
        } else {
11✔
375
                // Otherwise just return the no locktime inputs.
7✔
376
                result[mergeLocktime] = noLocktimeInputs
7✔
377
        }
7✔
378

379
        return result
8✔
380
}
381

382
// isDustOutput checks if the given output is considered as dust.
383
func isDustOutput(output *wire.TxOut) bool {
4✔
384
        // Fetch the dust limit for this output.
4✔
385
        dustLimit := lnwallet.DustLimitForSize(len(output.PkScript))
4✔
386

4✔
387
        // If the output is below the dust limit, we consider it dust.
4✔
388
        return btcutil.Amount(output.Value) < dustLimit
4✔
389
}
4✔
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