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

lightningnetwork / lnd / 9915780197

13 Jul 2024 12:30AM UTC coverage: 49.268% (-9.1%) from 58.413%
9915780197

push

github

web-flow
Merge pull request #8653 from ProofOfKeags/fn-prim

DynComms [0/n]: `fn` package additions

92837 of 188433 relevant lines covered (49.27%)

1.55 hits per line

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

81.74
/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/input"
9
        "github.com/lightningnetwork/lnd/lntypes"
10
        "github.com/lightningnetwork/lnd/lnwallet"
11
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
12
)
13

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

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

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

36
// Compile-time constraint to ensure BudgetAggregator implements UtxoAggregator.
37
var _ UtxoAggregator = (*BudgetAggregator)(nil)
38

39
// NewBudgetAggregator creates a new instance of a BudgetAggregator.
40
func NewBudgetAggregator(estimator chainfee.Estimator,
41
        maxInputs uint32) *BudgetAggregator {
3✔
42

3✔
43
        return &BudgetAggregator{
3✔
44
                estimator: estimator,
3✔
45
                maxInputs: maxInputs,
3✔
46
        }
3✔
47
}
3✔
48

49
// clusterGroup defines an alias for a set of inputs that are to be grouped.
50
type clusterGroup map[int32][]SweeperInput
51

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

3✔
64
        // Create clusters to group inputs based on their deadline height.
3✔
65
        clusters := make(clusterGroup, len(filteredInputs))
3✔
66

3✔
67
        // exclusiveInputs is a set of inputs that are not to be included in
3✔
68
        // any cluster. These inputs can only be swept independently as there's
3✔
69
        // no guarantee which input will be confirmed first, which means
3✔
70
        // grouping exclusive inputs may jeopardize non-exclusive inputs.
3✔
71
        exclusiveInputs := make(map[wire.OutPoint]clusterGroup)
3✔
72

3✔
73
        // Iterate all the inputs and group them based on their specified
3✔
74
        // deadline heights.
3✔
75
        for _, input := range filteredInputs {
6✔
76
                // Get deadline height, and use the specified default deadline
3✔
77
                // height if it's not set.
3✔
78
                height := input.DeadlineHeight
3✔
79

3✔
80
                // Put exclusive inputs in their own set.
3✔
81
                if input.params.ExclusiveGroup != nil {
6✔
82
                        log.Tracef("Input %v is exclusive", input.OutPoint())
3✔
83
                        exclusiveInputs[input.OutPoint()] = clusterGroup{
3✔
84
                                height: []SweeperInput{*input},
3✔
85
                        }
3✔
86

3✔
87
                        continue
3✔
88
                }
89

90
                cluster, ok := clusters[height]
3✔
91
                if !ok {
6✔
92
                        cluster = make([]SweeperInput, 0)
3✔
93
                }
3✔
94

95
                cluster = append(cluster, *input)
3✔
96
                clusters[height] = cluster
3✔
97
        }
98

99
        // Now that we have the clusters, we can create the input sets.
100
        //
101
        // NOTE: cannot pre-allocate the slice since we don't know the number
102
        // of input sets in advance.
103
        inputSets := make([]InputSet, 0)
3✔
104
        for height, cluster := range clusters {
6✔
105
                // Sort the inputs by their economical value.
3✔
106
                sortedInputs := b.sortInputs(cluster)
3✔
107

3✔
108
                // Split on locktimes if they are different.
3✔
109
                splitClusters := splitOnLocktime(sortedInputs)
3✔
110

3✔
111
                // Create input sets from the cluster.
3✔
112
                for _, cluster := range splitClusters {
6✔
113
                        sets := b.createInputSets(cluster, height)
3✔
114
                        inputSets = append(inputSets, sets...)
3✔
115
                }
3✔
116
        }
117

118
        // Create input sets from the exclusive inputs.
119
        for _, cluster := range exclusiveInputs {
6✔
120
                for height, input := range cluster {
6✔
121
                        sets := b.createInputSets(input, height)
3✔
122
                        inputSets = append(inputSets, sets...)
3✔
123
                }
3✔
124
        }
125

126
        return inputSets
3✔
127
}
128

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

3✔
141
        // sets holds the InputSets that we will return.
3✔
142
        sets := make([]InputSet, 0)
3✔
143

3✔
144
        // Copy the inputs to a new slice so we can modify it.
3✔
145
        remainingInputs := make([]SweeperInput, len(inputs))
3✔
146
        copy(remainingInputs, inputs)
3✔
147

3✔
148
        // If the number of inputs is greater than the max inputs allowed, we
3✔
149
        // will split them into smaller clusters.
3✔
150
        for uint32(len(remainingInputs)) > b.maxInputs {
3✔
151
                log.Tracef("Cluster has %v inputs, max is %v, dividing...",
×
152
                        len(inputs), b.maxInputs)
×
153

×
154
                // Copy the inputs to be put into the new set, and update the
×
155
                // remaining inputs by removing currentInputs.
×
156
                currentInputs := make([]SweeperInput, b.maxInputs)
×
157
                copy(currentInputs, remainingInputs[:b.maxInputs])
×
158
                remainingInputs = remainingInputs[b.maxInputs:]
×
159

×
160
                // Create an InputSet using the max allowed number of inputs.
×
161
                set, err := NewBudgetInputSet(
×
162
                        currentInputs, deadlineHeight,
×
163
                )
×
164
                if err != nil {
×
165
                        log.Errorf("unable to create input set: %v", err)
×
166

×
167
                        continue
×
168
                }
169

170
                sets = append(sets, set)
×
171
        }
172

173
        // Create an InputSet from the remaining inputs.
174
        if len(remainingInputs) > 0 {
6✔
175
                set, err := NewBudgetInputSet(
3✔
176
                        remainingInputs, deadlineHeight,
3✔
177
                )
3✔
178
                if err != nil {
3✔
179
                        log.Errorf("unable to create input set: %v", err)
×
180
                        return nil
×
181
                }
×
182

183
                sets = append(sets, set)
3✔
184
        }
185

186
        return sets
3✔
187
}
188

189
// filterInputs filters out inputs that have,
190
// - a budget below the min relay fee.
191
// - a budget below its requested starting fee.
192
// - a required output that's below the dust.
193
func (b *BudgetAggregator) filterInputs(inputs InputsMap) InputsMap {
3✔
194
        // Get the current min relay fee for this round.
3✔
195
        minFeeRate := b.estimator.RelayFeePerKW()
3✔
196

3✔
197
        // filterInputs stores a map of inputs that has a budget that at least
3✔
198
        // can pay the minimal fee.
3✔
199
        filteredInputs := make(InputsMap, len(inputs))
3✔
200

3✔
201
        // Iterate all the inputs and filter out the ones whose budget cannot
3✔
202
        // cover the min fee.
3✔
203
        for _, pi := range inputs {
6✔
204
                op := pi.OutPoint()
3✔
205

3✔
206
                // Get the size of the witness and skip if there's an error.
3✔
207
                witnessSize, _, err := pi.WitnessType().SizeUpperBound()
3✔
208
                if err != nil {
3✔
209
                        log.Warnf("Skipped input=%v: cannot get its size: %v",
×
210
                                op, err)
×
211

×
212
                        continue
×
213
                }
214

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

3✔
229
                // Skip inputs that has too little budget.
3✔
230
                minFee := minFeeRate.FeeForWeight(wu)
3✔
231
                if pi.params.Budget < minFee {
3✔
232
                        log.Warnf("Skipped input=%v: has budget=%v, but the "+
×
233
                                "min fee requires %v (feerate=%v), size=%v", op,
×
234
                                pi.params.Budget, minFee,
×
235
                                minFeeRate.FeePerVByte(), wu.ToVB())
×
236

×
237
                        continue
×
238
                }
239

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

×
251
                        continue
×
252
                }
253

254
                // If the input comes with a required tx out that is below
255
                // dust, we won't add it.
256
                //
257
                // NOTE: only HtlcSecondLevelAnchorInput returns non-nil
258
                // RequiredTxOut.
259
                reqOut := pi.RequiredTxOut()
3✔
260
                if reqOut != nil {
6✔
261
                        if isDustOutput(reqOut) {
3✔
262
                                log.Errorf("Rejected input=%v due to dust "+
×
263
                                        "required output=%v", op, reqOut.Value)
×
264

×
265
                                continue
×
266
                        }
267
                }
268

269
                filteredInputs[op] = pi
3✔
270
        }
271

272
        return filteredInputs
3✔
273
}
274

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

3✔
287
        // Copy the inputs.
3✔
288
        sortedInputs = append(sortedInputs, inputs...)
3✔
289

3✔
290
        // Sort the inputs based on their budgets.
3✔
291
        //
3✔
292
        // NOTE: We can implement more sophisticated algorithm as the budget
3✔
293
        // left is a function f(minFeeRate, size) = b1 - s1 * r > b2 - s2 * r,
3✔
294
        // where b1 and b2 are budgets, s1 and s2 are sizes of the inputs.
3✔
295
        sort.Slice(sortedInputs, func(i, j int) bool {
6✔
296
                left := sortedInputs[i].params.Budget
3✔
297
                right := sortedInputs[j].params.Budget
3✔
298

3✔
299
                // Make sure forced inputs are always put in the front.
3✔
300
                leftForce := sortedInputs[i].params.Immediate
3✔
301
                rightForce := sortedInputs[j].params.Immediate
3✔
302

3✔
303
                // If both are forced inputs, we return the one with the higher
3✔
304
                // budget. If neither are forced inputs, we also return the one
3✔
305
                // with the higher budget.
3✔
306
                if leftForce == rightForce {
6✔
307
                        return left > right
3✔
308
                }
3✔
309

310
                // Otherwise, it's either the left or the right is forced. We
311
                // can simply return `leftForce` here as, if it's true, the
312
                // left is forced and should be put in the front. Otherwise,
313
                // the right is forced and should be put in the front.
314
                return leftForce
×
315
        })
316

317
        return sortedInputs
3✔
318
}
319

320
// splitOnLocktime splits the list of inputs based on their locktime.
321
//
322
// TODO(yy): this is a temporary hack as the blocks are not synced among the
323
// contractcourt and the sweeper.
324
func splitOnLocktime(inputs []SweeperInput) map[uint32][]SweeperInput {
3✔
325
        result := make(map[uint32][]SweeperInput)
3✔
326
        noLocktimeInputs := make([]SweeperInput, 0, len(inputs))
3✔
327

3✔
328
        // mergeLocktime is the locktime that we use to merge all the
3✔
329
        // nolocktime inputs into.
3✔
330
        var mergeLocktime uint32
3✔
331

3✔
332
        // Iterate all inputs and split them based on their locktimes.
3✔
333
        for _, inp := range inputs {
6✔
334
                locktime, required := inp.RequiredLockTime()
3✔
335
                if !required {
6✔
336
                        log.Tracef("No locktime required for input=%v",
3✔
337
                                inp.OutPoint())
3✔
338

3✔
339
                        noLocktimeInputs = append(noLocktimeInputs, inp)
3✔
340

3✔
341
                        continue
3✔
342
                }
343

344
                log.Tracef("Split input=%v on locktime=%v", inp.OutPoint(),
3✔
345
                        locktime)
3✔
346

3✔
347
                // Get the slice - the slice will be initialized if not found.
3✔
348
                inputList := result[locktime]
3✔
349

3✔
350
                // Add the input to the list.
3✔
351
                inputList = append(inputList, inp)
3✔
352

3✔
353
                // Update the map.
3✔
354
                result[locktime] = inputList
3✔
355

3✔
356
                // Update the merge locktime.
3✔
357
                mergeLocktime = locktime
3✔
358
        }
359

360
        // If there are locktime inputs, we will merge the no locktime inputs
361
        // to the last locktime group found.
362
        if len(result) > 0 {
6✔
363
                log.Tracef("No locktime inputs has been merged to locktime=%v",
3✔
364
                        mergeLocktime)
3✔
365
                result[mergeLocktime] = append(
3✔
366
                        result[mergeLocktime], noLocktimeInputs...,
3✔
367
                )
3✔
368
        } else {
6✔
369
                // Otherwise just return the no locktime inputs.
3✔
370
                result[mergeLocktime] = noLocktimeInputs
3✔
371
        }
3✔
372

373
        return result
3✔
374
}
375

376
// isDustOutput checks if the given output is considered as dust.
377
func isDustOutput(output *wire.TxOut) bool {
3✔
378
        // Fetch the dust limit for this output.
3✔
379
        dustLimit := lnwallet.DustLimitForSize(len(output.PkScript))
3✔
380

3✔
381
        // If the output is below the dust limit, we consider it dust.
3✔
382
        return btcutil.Amount(output.Value) < dustLimit
3✔
383
}
3✔
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