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

lightningnetwork / lnd / 13586005509

28 Feb 2025 10:14AM UTC coverage: 68.629% (+9.9%) from 58.77%
13586005509

Pull #9521

github

web-flow
Merge 37d3a70a5 into 8532955b3
Pull Request #9521: unit: remove GOACC, use Go 1.20 native coverage functionality

129950 of 189351 relevant lines covered (68.63%)

23726.46 hits per line

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

95.72
/routing/unified_edges.go
1
package routing
2

3
import (
4
        "math"
5

6
        "github.com/btcsuite/btcd/btcutil"
7
        graphdb "github.com/lightningnetwork/lnd/graph/db"
8
        "github.com/lightningnetwork/lnd/graph/db/models"
9
        "github.com/lightningnetwork/lnd/lnwire"
10
        "github.com/lightningnetwork/lnd/routing/route"
11
)
12

13
// nodeEdgeUnifier holds all edge unifiers for connections towards a node.
14
type nodeEdgeUnifier struct {
15
        // edgeUnifiers contains an edge unifier for every from node.
16
        edgeUnifiers map[route.Vertex]*edgeUnifier
17

18
        // sourceNode is the sender of a payment. The rules to pick the final
19
        // policy are different for local channels.
20
        sourceNode route.Vertex
21

22
        // toNode is the node for which the edge unifiers are instantiated.
23
        toNode route.Vertex
24

25
        // useInboundFees indicates whether to take inbound fees into account.
26
        useInboundFees bool
27

28
        // outChanRestr is an optional outgoing channel restriction for the
29
        // local channel to use.
30
        outChanRestr map[uint64]struct{}
31
}
32

33
// newNodeEdgeUnifier instantiates a new nodeEdgeUnifier object. Channel
34
// policies can be added to this object.
35
func newNodeEdgeUnifier(sourceNode, toNode route.Vertex, useInboundFees bool,
36
        outChanRestr map[uint64]struct{}) *nodeEdgeUnifier {
718✔
37

718✔
38
        return &nodeEdgeUnifier{
718✔
39
                edgeUnifiers:   make(map[route.Vertex]*edgeUnifier),
718✔
40
                toNode:         toNode,
718✔
41
                useInboundFees: useInboundFees,
718✔
42
                sourceNode:     sourceNode,
718✔
43
                outChanRestr:   outChanRestr,
718✔
44
        }
718✔
45
}
718✔
46

47
// addPolicy adds a single channel policy. Capacity may be zero if unknown
48
// (light clients). We expect a non-nil payload size function and will request a
49
// graceful shutdown if it is not provided as this indicates that edges are
50
// incorrectly specified.
51
func (u *nodeEdgeUnifier) addPolicy(fromNode route.Vertex,
52
        edge *models.CachedEdgePolicy, inboundFee models.InboundFee,
53
        capacity btcutil.Amount, hopPayloadSizeFn PayloadSizeFunc,
54
        blindedPayment *BlindedPayment) {
1,678✔
55

1,678✔
56
        localChan := fromNode == u.sourceNode
1,678✔
57

1,678✔
58
        // Skip channels if there is an outgoing channel restriction.
1,678✔
59
        if localChan && u.outChanRestr != nil {
1,692✔
60
                if _, ok := u.outChanRestr[edge.ChannelID]; !ok {
22✔
61
                        log.Debugf("Skipped adding policy for restricted edge "+
8✔
62
                                "%v", edge.ChannelID)
8✔
63

8✔
64
                        return
8✔
65
                }
8✔
66
        }
67

68
        // Update the edgeUnifiers map.
69
        unifier, ok := u.edgeUnifiers[fromNode]
1,670✔
70
        if !ok {
3,323✔
71
                unifier = &edgeUnifier{
1,653✔
72
                        localChan: localChan,
1,653✔
73
                }
1,653✔
74
                u.edgeUnifiers[fromNode] = unifier
1,653✔
75
        }
1,653✔
76

77
        // In case no payload size function was provided a graceful shutdown
78
        // is requested, because this function is not used as intended.
79
        if hopPayloadSizeFn == nil {
1,670✔
80
                log.Criticalf("No payloadsize function was provided for the "+
×
81
                        "edge (chanid=%v) when adding it to the edge unifier "+
×
82
                        "of node: %v", edge.ChannelID, fromNode)
×
83

×
84
                return
×
85
        }
×
86

87
        // Zero inbound fee for exit hops.
88
        if !u.useInboundFees {
2,168✔
89
                inboundFee = models.InboundFee{}
498✔
90
        }
498✔
91

92
        unifier.edges = append(unifier.edges, newUnifiedEdge(
1,670✔
93
                edge, capacity, inboundFee, hopPayloadSizeFn, blindedPayment,
1,670✔
94
        ))
1,670✔
95
}
96

97
// addGraphPolicies adds all policies that are known for the toNode in the
98
// graph.
99
func (u *nodeEdgeUnifier) addGraphPolicies(g Graph) error {
712✔
100
        cb := func(channel *graphdb.DirectedChannel) error {
2,364✔
101
                // If there is no edge policy for this candidate node, skip.
1,652✔
102
                // Note that we are searching backwards so this node would have
1,652✔
103
                // come prior to the pivot node in the route.
1,652✔
104
                if channel.InPolicy == nil {
1,652✔
105
                        log.Debugf("Skipped adding edge %v due to nil policy",
×
106
                                channel.ChannelID)
×
107

×
108
                        return nil
×
109
                }
×
110

111
                // Add this policy to the corresponding edgeUnifier. We default
112
                // to the clear hop payload size function because
113
                // `addGraphPolicies` is only used for cleartext intermediate
114
                // hops in a route.
115
                inboundFee := models.NewInboundFeeFromWire(
1,652✔
116
                        channel.InboundFee,
1,652✔
117
                )
1,652✔
118

1,652✔
119
                u.addPolicy(
1,652✔
120
                        channel.OtherNode, channel.InPolicy, inboundFee,
1,652✔
121
                        channel.Capacity, defaultHopPayloadSize, nil,
1,652✔
122
                )
1,652✔
123

1,652✔
124
                return nil
1,652✔
125
        }
126

127
        // Iterate over all channels of the to node.
128
        return g.ForEachNodeDirectedChannel(u.toNode, cb)
712✔
129
}
130

131
// unifiedEdge is the individual channel data that is kept inside an edgeUnifier
132
// object.
133
type unifiedEdge struct {
134
        policy      *models.CachedEdgePolicy
135
        capacity    btcutil.Amount
136
        inboundFees models.InboundFee
137

138
        // hopPayloadSize supplies an edge with the ability to calculate the
139
        // exact payload size if this edge would be included in a route. This
140
        // is needed because hops of a blinded path differ in their payload
141
        // structure compared to cleartext hops.
142
        hopPayloadSizeFn PayloadSizeFunc
143

144
        // blindedPayment if set, is the BlindedPayment that this edge was
145
        // derived from originally.
146
        blindedPayment *BlindedPayment
147
}
148

149
// newUnifiedEdge constructs a new unifiedEdge.
150
func newUnifiedEdge(policy *models.CachedEdgePolicy, capacity btcutil.Amount,
151
        inboundFees models.InboundFee, hopPayloadSizeFn PayloadSizeFunc,
152
        blindedPayment *BlindedPayment) *unifiedEdge {
4,089✔
153

4,089✔
154
        return &unifiedEdge{
4,089✔
155
                policy:           policy,
4,089✔
156
                capacity:         capacity,
4,089✔
157
                inboundFees:      inboundFees,
4,089✔
158
                hopPayloadSizeFn: hopPayloadSizeFn,
4,089✔
159
                blindedPayment:   blindedPayment,
4,089✔
160
        }
4,089✔
161
}
4,089✔
162

163
// amtInRange checks whether an amount falls within the valid range for a
164
// channel.
165
func (u *unifiedEdge) amtInRange(amt lnwire.MilliSatoshi) bool {
1,354✔
166
        // If the capacity is available (non-light clients), skip channels that
1,354✔
167
        // are too small.
1,354✔
168
        if u.capacity > 0 &&
1,354✔
169
                amt > lnwire.NewMSatFromSatoshis(u.capacity) {
1,368✔
170

14✔
171
                log.Tracef("Not enough capacity: amt=%v, capacity=%v",
14✔
172
                        amt, u.capacity)
14✔
173
                return false
14✔
174
        }
14✔
175

176
        // Skip channels for which this htlc is too large.
177
        if u.policy.MessageFlags.HasMaxHtlc() &&
1,340✔
178
                amt > u.policy.MaxHTLC {
1,350✔
179

10✔
180
                log.Tracef("Exceeds policy's MaxHTLC: amt=%v, MaxHTLC=%v",
10✔
181
                        amt, u.policy.MaxHTLC)
10✔
182
                return false
10✔
183
        }
10✔
184

185
        // Skip channels for which this htlc is too small.
186
        if amt < u.policy.MinHTLC {
1,346✔
187
                log.Tracef("below policy's MinHTLC: amt=%v, MinHTLC=%v",
13✔
188
                        amt, u.policy.MinHTLC)
13✔
189
                return false
13✔
190
        }
13✔
191

192
        return true
1,323✔
193
}
194

195
// edgeUnifier is an object that covers all channels between a pair of nodes.
196
type edgeUnifier struct {
197
        edges     []*unifiedEdge
198
        localChan bool
199
}
200

201
// getEdge returns the optimal unified edge to use for this connection given a
202
// specific amount to send. It differentiates between local and network
203
// channels.
204
func (u *edgeUnifier) getEdge(netAmtReceived lnwire.MilliSatoshi,
205
        bandwidthHints bandwidthHints,
206
        nextOutFee lnwire.MilliSatoshi) *unifiedEdge {
1,322✔
207

1,322✔
208
        if u.localChan {
1,497✔
209
                return u.getEdgeLocal(
175✔
210
                        netAmtReceived, bandwidthHints, nextOutFee,
175✔
211
                )
175✔
212
        }
175✔
213

214
        return u.getEdgeNetwork(netAmtReceived, nextOutFee)
1,150✔
215
}
216

217
// calcCappedInboundFee calculates the inbound fee for a channel, taking into
218
// account the total node fee for the "to" node.
219
func calcCappedInboundFee(edge *unifiedEdge, amt lnwire.MilliSatoshi,
220
        nextOutFee lnwire.MilliSatoshi) int64 {
1,347✔
221

1,347✔
222
        // Calculate the inbound fee charged for the amount that passes over the
1,347✔
223
        // channel.
1,347✔
224
        inboundFee := edge.inboundFees.CalcFee(amt)
1,347✔
225

1,347✔
226
        // Take into account that the total node fee cannot be negative.
1,347✔
227
        if inboundFee < -int64(nextOutFee) {
1,350✔
228
                inboundFee = -int64(nextOutFee)
3✔
229
        }
3✔
230

231
        return inboundFee
1,347✔
232
}
233

234
// getEdgeLocal returns the optimal unified edge to use for this local
235
// connection given a specific amount to send.
236
func (u *edgeUnifier) getEdgeLocal(netAmtReceived lnwire.MilliSatoshi,
237
        bandwidthHints bandwidthHints,
238
        nextOutFee lnwire.MilliSatoshi) *unifiedEdge {
175✔
239

175✔
240
        var (
175✔
241
                bestEdge     *unifiedEdge
175✔
242
                maxBandwidth lnwire.MilliSatoshi
175✔
243
        )
175✔
244

175✔
245
        for _, edge := range u.edges {
353✔
246
                // Calculate the inbound fee charged at the receiving node.
178✔
247
                inboundFee := calcCappedInboundFee(
178✔
248
                        edge, netAmtReceived, nextOutFee,
178✔
249
                )
178✔
250

178✔
251
                // Add inbound fee to get to the amount that is sent over the
178✔
252
                // local channel.
178✔
253
                amt := netAmtReceived + lnwire.MilliSatoshi(inboundFee)
178✔
254

178✔
255
                // Check valid amount range for the channel. We skip this test
178✔
256
                // for payments with custom HTLC data, as the amount sent on
178✔
257
                // the BTC layer may differ from the amount that is actually
178✔
258
                // forwarded in custom channels.
178✔
259
                if bandwidthHints.firstHopCustomBlob().IsNone() &&
178✔
260
                        !edge.amtInRange(amt) {
189✔
261

11✔
262
                        log.Debugf("Amount %v not in range for edge %v",
11✔
263
                                netAmtReceived, edge.policy.ChannelID)
11✔
264

11✔
265
                        continue
11✔
266
                }
267

268
                // For local channels, there is no fee to pay or an extra time
269
                // lock. We only consider the currently available bandwidth for
270
                // channel selection. The disabled flag is ignored for local
271
                // channels.
272

273
                // Retrieve bandwidth for this local channel. If not
274
                // available, assume this channel has enough bandwidth.
275
                //
276
                // TODO(joostjager): Possibly change to skipping this
277
                // channel. The bandwidth hint is expected to be
278
                // available.
279
                bandwidth, ok := bandwidthHints.availableChanBandwidth(
167✔
280
                        edge.policy.ChannelID, amt,
167✔
281
                )
167✔
282
                if !ok {
246✔
283
                        log.Debugf("Cannot get bandwidth for edge %v, use max "+
79✔
284
                                "instead", edge.policy.ChannelID)
79✔
285
                        bandwidth = lnwire.MaxMilliSatoshi
79✔
286
                }
79✔
287

288
                // TODO(yy): if the above `!ok` is chosen, we'd have
289
                // `bandwidth` to be the max value, which will end up having
290
                // the `maxBandwidth` to be have the largest value and this
291
                // edge will be the chosen one. This is wrong in two ways,
292
                // 1. we need to understand why `availableChanBandwidth` cannot
293
                // find bandwidth for this edge as something is wrong with this
294
                // channel, and,
295
                // 2. this edge is likely NOT the local channel with the
296
                // highest available bandwidth.
297
                //
298
                // Skip channels that can't carry the payment.
299
                if amt > bandwidth {
177✔
300
                        log.Debugf("Skipped edge %v: not enough bandwidth, "+
10✔
301
                                "bandwidth=%v, amt=%v", edge.policy.ChannelID,
10✔
302
                                bandwidth, amt)
10✔
303

10✔
304
                        continue
10✔
305
                }
306

307
                // We pick the local channel with the highest available
308
                // bandwidth, to maximize the success probability. It can be
309
                // that the channel state changes between querying the bandwidth
310
                // hints and sending out the htlc.
311
                if bandwidth < maxBandwidth {
163✔
312
                        log.Debugf("Skipped edge %v: not max bandwidth, "+
3✔
313
                                "bandwidth=%v, maxBandwidth=%v",
3✔
314
                                edge.policy.ChannelID, bandwidth, maxBandwidth)
3✔
315

3✔
316
                        continue
3✔
317
                }
318
                maxBandwidth = bandwidth
157✔
319

157✔
320
                // Update best edge.
157✔
321
                bestEdge = newUnifiedEdge(
157✔
322
                        edge.policy, edge.capacity, edge.inboundFees,
157✔
323
                        edge.hopPayloadSizeFn, edge.blindedPayment,
157✔
324
                )
157✔
325
        }
326

327
        return bestEdge
175✔
328
}
329

330
// getEdgeNetwork returns the optimal unified edge to use for this connection
331
// given a specific amount to send. The goal is to return a unified edge with a
332
// policy that maximizes the probability of a successful forward in a non-strict
333
// forwarding context.
334
func (u *edgeUnifier) getEdgeNetwork(netAmtReceived lnwire.MilliSatoshi,
335
        nextOutFee lnwire.MilliSatoshi) *unifiedEdge {
1,150✔
336

1,150✔
337
        var (
1,150✔
338
                bestPolicy       *unifiedEdge
1,150✔
339
                maxFee           int64 = math.MinInt64
1,150✔
340
                maxTimelock      uint16
1,150✔
341
                maxCapMsat       lnwire.MilliSatoshi
1,150✔
342
                hopPayloadSizeFn PayloadSizeFunc
1,150✔
343
        )
1,150✔
344

1,150✔
345
        for _, edge := range u.edges {
2,311✔
346
                // Calculate the inbound fee charged at the receiving node.
1,161✔
347
                inboundFee := calcCappedInboundFee(
1,161✔
348
                        edge, netAmtReceived, nextOutFee,
1,161✔
349
                )
1,161✔
350

1,161✔
351
                // Add inbound fee to get to the amount that is sent over the
1,161✔
352
                // channel.
1,161✔
353
                amt := netAmtReceived + lnwire.MilliSatoshi(inboundFee)
1,161✔
354

1,161✔
355
                // Check valid amount range for the channel.
1,161✔
356
                if !edge.amtInRange(amt) {
1,183✔
357
                        log.Debugf("Amount %v not in range for edge %v",
22✔
358
                                amt, edge.policy.ChannelID)
22✔
359
                        continue
22✔
360
                }
361

362
                // For network channels, skip the disabled ones.
363
                edgeFlags := edge.policy.ChannelFlags
1,142✔
364
                isDisabled := edgeFlags&lnwire.ChanUpdateDisabled != 0
1,142✔
365
                if isDisabled {
1,144✔
366
                        log.Debugf("Skipped edge %v due to it being disabled",
2✔
367
                                edge.policy.ChannelID)
2✔
368
                        continue
2✔
369
                }
370

371
                // Track the maximal capacity for usable channels. If we don't
372
                // know the capacity, we fall back to MaxHTLC.
373
                capMsat := lnwire.NewMSatFromSatoshis(edge.capacity)
1,140✔
374
                if capMsat == 0 && edge.policy.MessageFlags.HasMaxHtlc() {
1,142✔
375
                        log.Tracef("No capacity available for channel %v, "+
2✔
376
                                "using MaxHtlcMsat (%v) as a fallback.",
2✔
377
                                edge.policy.ChannelID, edge.policy.MaxHTLC)
2✔
378

2✔
379
                        capMsat = edge.policy.MaxHTLC
2✔
380
                }
2✔
381
                maxCapMsat = max(capMsat, maxCapMsat)
1,140✔
382

1,140✔
383
                // Track the maximum time lock of all channels that are
1,140✔
384
                // candidate for non-strict forwarding at the routing node.
1,140✔
385
                maxTimelock = max(maxTimelock, edge.policy.TimeLockDelta)
1,140✔
386

1,140✔
387
                outboundFee := int64(edge.policy.ComputeFee(amt))
1,140✔
388
                fee := outboundFee + inboundFee
1,140✔
389

1,140✔
390
                // Use the policy that results in the highest fee for this
1,140✔
391
                // specific amount.
1,140✔
392
                if fee < maxFee {
1,141✔
393
                        log.Debugf("Skipped edge %v due to it produces less "+
1✔
394
                                "fee: fee=%v, maxFee=%v",
1✔
395
                                edge.policy.ChannelID, fee, maxFee)
1✔
396

1✔
397
                        continue
1✔
398
                }
399
                maxFee = fee
1,139✔
400

1,139✔
401
                bestPolicy = newUnifiedEdge(
1,139✔
402
                        edge.policy, 0, edge.inboundFees, nil,
1,139✔
403
                        edge.blindedPayment,
1,139✔
404
                )
1,139✔
405

1,139✔
406
                // The payload size function for edges to a connected peer is
1,139✔
407
                // always the same hence there is not need to find the maximum.
1,139✔
408
                // This also counts for blinded edges where we only have one
1,139✔
409
                // edge to a blinded peer.
1,139✔
410
                hopPayloadSizeFn = edge.hopPayloadSizeFn
1,139✔
411
        }
412

413
        // Return early if no channel matches.
414
        if bestPolicy == nil {
1,171✔
415
                return nil
21✔
416
        }
21✔
417

418
        // We have already picked the highest fee that could be required for
419
        // non-strict forwarding. To also cover the case where a lower fee
420
        // channel requires a longer time lock, we modify the policy by setting
421
        // the maximum encountered time lock. Note that this results in a
422
        // synthetic policy that is not actually present on the routing node.
423
        //
424
        // The reason we do this, is that we try to maximize the chance that we
425
        // get forwarded. Because we penalize pair-wise, there won't be a second
426
        // chance for this node pair. But this is all only needed for nodes that
427
        // have distinct policies for channels to the same peer.
428
        policyCopy := *bestPolicy.policy
1,132✔
429
        policyCopy.TimeLockDelta = maxTimelock
1,132✔
430
        modifiedEdge := newUnifiedEdge(
1,132✔
431
                &policyCopy, maxCapMsat.ToSatoshis(), bestPolicy.inboundFees,
1,132✔
432
                hopPayloadSizeFn, bestPolicy.blindedPayment,
1,132✔
433
        )
1,132✔
434

1,132✔
435
        return modifiedEdge
1,132✔
436
}
437

438
// minAmt returns the minimum amount that can be forwarded on this connection.
439
func (u *edgeUnifier) minAmt() lnwire.MilliSatoshi {
11✔
440
        minAmount := lnwire.MaxMilliSatoshi
11✔
441
        for _, edge := range u.edges {
26✔
442
                minAmount = min(minAmount, edge.policy.MinHTLC)
15✔
443
        }
15✔
444

445
        return minAmount
11✔
446
}
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