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

lightningnetwork / lnd / 17027244024

17 Aug 2025 11:32PM UTC coverage: 57.287% (-9.5%) from 66.765%
17027244024

Pull #10167

github

web-flow
Merge fcb4f4303 into fb1adfc21
Pull Request #10167: multi: bump Go to 1.24.6

3 of 18 new or added lines in 6 files covered. (16.67%)

28537 existing lines in 457 files now uncovered.

99094 of 172978 relevant lines covered (57.29%)

1.78 hits per line

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

79.41
/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 {
3✔
37

3✔
38
        return &nodeEdgeUnifier{
3✔
39
                edgeUnifiers:   make(map[route.Vertex]*edgeUnifier),
3✔
40
                toNode:         toNode,
3✔
41
                useInboundFees: useInboundFees,
3✔
42
                sourceNode:     sourceNode,
3✔
43
                outChanRestr:   outChanRestr,
3✔
44
        }
3✔
45
}
3✔
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) {
3✔
55

3✔
56
        localChan := fromNode == u.sourceNode
3✔
57

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

×
UNCOV
64
                        return
×
UNCOV
65
                }
×
66
        }
67

68
        // Update the edgeUnifiers map.
69
        unifier, ok := u.edgeUnifiers[fromNode]
3✔
70
        if !ok {
6✔
71
                unifier = &edgeUnifier{
3✔
72
                        localChan: localChan,
3✔
73
                }
3✔
74
                u.edgeUnifiers[fromNode] = unifier
3✔
75
        }
3✔
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 {
3✔
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 {
6✔
89
                inboundFee = models.InboundFee{}
3✔
90
        }
3✔
91

92
        unifier.edges = append(unifier.edges, newUnifiedEdge(
3✔
93
                edge, capacity, inboundFee, hopPayloadSizeFn, blindedPayment,
3✔
94
        ))
3✔
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 {
3✔
100
        var channels []*graphdb.DirectedChannel
3✔
101
        cb := func(channel *graphdb.DirectedChannel) error {
6✔
102
                // If there is no edge policy for this candidate node, skip.
3✔
103
                // Note that we are searching backwards so this node would have
3✔
104
                // come prior to the pivot node in the route.
3✔
105
                if channel.InPolicy == nil {
3✔
106
                        log.Debugf("Skipped adding edge %v due to nil policy",
×
107
                                channel.ChannelID)
×
108

×
109
                        return nil
×
110
                }
×
111

112
                channels = append(channels, channel)
3✔
113

3✔
114
                return nil
3✔
115
        }
116

117
        // Iterate over all channels of the to node.
118
        err := g.ForEachNodeDirectedChannel(
3✔
119
                u.toNode, cb, func() {
6✔
120
                        channels = nil
3✔
121
                },
3✔
122
        )
123
        if err != nil {
3✔
124
                return err
×
125
        }
×
126

127
        for _, channel := range channels {
6✔
128
                // Add this policy to the corresponding edgeUnifier. We default
3✔
129
                // to the clear hop payload size function because
3✔
130
                // `addGraphPolicies` is only used for cleartext intermediate
3✔
131
                // hops in a route.
3✔
132
                inboundFee := models.NewInboundFeeFromWire(
3✔
133
                        channel.InboundFee,
3✔
134
                )
3✔
135

3✔
136
                u.addPolicy(
3✔
137
                        channel.OtherNode, channel.InPolicy, inboundFee,
3✔
138
                        channel.Capacity, defaultHopPayloadSize, nil,
3✔
139
                )
3✔
140
        }
3✔
141

142
        return nil
3✔
143
}
144

145
// unifiedEdge is the individual channel data that is kept inside an edgeUnifier
146
// object.
147
type unifiedEdge struct {
148
        policy      *models.CachedEdgePolicy
149
        capacity    btcutil.Amount
150
        inboundFees models.InboundFee
151

152
        // hopPayloadSize supplies an edge with the ability to calculate the
153
        // exact payload size if this edge would be included in a route. This
154
        // is needed because hops of a blinded path differ in their payload
155
        // structure compared to cleartext hops.
156
        hopPayloadSizeFn PayloadSizeFunc
157

158
        // blindedPayment if set, is the BlindedPayment that this edge was
159
        // derived from originally.
160
        blindedPayment *BlindedPayment
161
}
162

163
// newUnifiedEdge constructs a new unifiedEdge.
164
func newUnifiedEdge(policy *models.CachedEdgePolicy, capacity btcutil.Amount,
165
        inboundFees models.InboundFee, hopPayloadSizeFn PayloadSizeFunc,
166
        blindedPayment *BlindedPayment) *unifiedEdge {
3✔
167

3✔
168
        return &unifiedEdge{
3✔
169
                policy:           policy,
3✔
170
                capacity:         capacity,
3✔
171
                inboundFees:      inboundFees,
3✔
172
                hopPayloadSizeFn: hopPayloadSizeFn,
3✔
173
                blindedPayment:   blindedPayment,
3✔
174
        }
3✔
175
}
3✔
176

177
// amtInRange checks whether an amount falls within the valid range for a
178
// channel.
179
func (u *unifiedEdge) amtInRange(amt lnwire.MilliSatoshi) bool {
3✔
180
        // If the capacity is available (non-light clients), skip channels that
3✔
181
        // are too small.
3✔
182
        if u.capacity > 0 &&
3✔
183
                amt > lnwire.NewMSatFromSatoshis(u.capacity) {
3✔
UNCOV
184

×
UNCOV
185
                log.Tracef("Not enough capacity: amt=%v, capacity=%v",
×
UNCOV
186
                        amt, u.capacity)
×
UNCOV
187
                return false
×
UNCOV
188
        }
×
189

190
        // Skip channels for which this htlc is too large.
191
        if u.policy.MessageFlags.HasMaxHtlc() &&
3✔
192
                amt > u.policy.MaxHTLC {
6✔
193

3✔
194
                log.Tracef("Exceeds policy's MaxHTLC: amt=%v, MaxHTLC=%v",
3✔
195
                        amt, u.policy.MaxHTLC)
3✔
196
                return false
3✔
197
        }
3✔
198

199
        // Skip channels for which this htlc is too small.
200
        if amt < u.policy.MinHTLC {
6✔
201
                log.Tracef("below policy's MinHTLC: amt=%v, MinHTLC=%v",
3✔
202
                        amt, u.policy.MinHTLC)
3✔
203
                return false
3✔
204
        }
3✔
205

206
        return true
3✔
207
}
208

209
// edgeUnifier is an object that covers all channels between a pair of nodes.
210
type edgeUnifier struct {
211
        edges     []*unifiedEdge
212
        localChan bool
213
}
214

215
// getEdge returns the optimal unified edge to use for this connection given a
216
// specific amount to send. It differentiates between local and network
217
// channels.
218
func (u *edgeUnifier) getEdge(netAmtReceived lnwire.MilliSatoshi,
219
        bandwidthHints bandwidthHints,
220
        nextOutFee lnwire.MilliSatoshi) *unifiedEdge {
3✔
221

3✔
222
        if u.localChan {
6✔
223
                return u.getEdgeLocal(
3✔
224
                        netAmtReceived, bandwidthHints, nextOutFee,
3✔
225
                )
3✔
226
        }
3✔
227

228
        return u.getEdgeNetwork(netAmtReceived, nextOutFee)
3✔
229
}
230

231
// calcCappedInboundFee calculates the inbound fee for a channel, taking into
232
// account the total node fee for the "to" node.
233
func calcCappedInboundFee(edge *unifiedEdge, amt lnwire.MilliSatoshi,
234
        nextOutFee lnwire.MilliSatoshi) int64 {
3✔
235

3✔
236
        // Calculate the inbound fee charged for the amount that passes over the
3✔
237
        // channel.
3✔
238
        inboundFee := edge.inboundFees.CalcFee(amt)
3✔
239

3✔
240
        // Take into account that the total node fee cannot be negative.
3✔
241
        if inboundFee < -int64(nextOutFee) {
3✔
UNCOV
242
                inboundFee = -int64(nextOutFee)
×
UNCOV
243
        }
×
244

245
        return inboundFee
3✔
246
}
247

248
// getEdgeLocal returns the optimal unified edge to use for this local
249
// connection given a specific amount to send.
250
func (u *edgeUnifier) getEdgeLocal(netAmtReceived lnwire.MilliSatoshi,
251
        bandwidthHints bandwidthHints,
252
        nextOutFee lnwire.MilliSatoshi) *unifiedEdge {
3✔
253

3✔
254
        var (
3✔
255
                bestEdge     *unifiedEdge
3✔
256
                maxBandwidth lnwire.MilliSatoshi
3✔
257
        )
3✔
258

3✔
259
        for _, edge := range u.edges {
6✔
260
                // Calculate the inbound fee charged at the receiving node.
3✔
261
                inboundFee := calcCappedInboundFee(
3✔
262
                        edge, netAmtReceived, nextOutFee,
3✔
263
                )
3✔
264

3✔
265
                // Add inbound fee to get to the amount that is sent over the
3✔
266
                // local channel.
3✔
267
                amt := netAmtReceived + lnwire.MilliSatoshi(inboundFee)
3✔
268
                // Check valid amount range for the channel. We skip this test
3✔
269

3✔
270
                // for payments with custom htlc data we skip the amount range
3✔
271
                // check because the amt of the payment does not relate to the
3✔
272
                // actual amount carried by the HTLC but instead is encoded in
3✔
273
                // the blob data.
3✔
274
                if !bandwidthHints.isCustomHTLCPayment() &&
3✔
275
                        !edge.amtInRange(amt) {
6✔
276

3✔
277
                        log.Debugf("Amount %v not in range for edge %v",
3✔
278
                                netAmtReceived, edge.policy.ChannelID)
3✔
279

3✔
280
                        continue
3✔
281
                }
282

283
                // For local channels, there is no fee to pay or an extra time
284
                // lock. We only consider the currently available bandwidth for
285
                // channel selection. The disabled flag is ignored for local
286
                // channels.
287

288
                // Retrieve bandwidth for this local channel. If not
289
                // available, assume this channel has enough bandwidth.
290
                //
291
                // TODO(joostjager): Possibly change to skipping this
292
                // channel. The bandwidth hint is expected to be
293
                // available.
294
                bandwidth, ok := bandwidthHints.availableChanBandwidth(
3✔
295
                        edge.policy.ChannelID, amt,
3✔
296
                )
3✔
297
                if !ok {
3✔
UNCOV
298
                        log.Warnf("Cannot get bandwidth for edge %v, use max "+
×
UNCOV
299
                                "instead", edge.policy.ChannelID)
×
UNCOV
300

×
UNCOV
301
                        bandwidth = lnwire.MaxMilliSatoshi
×
UNCOV
302
                }
×
303

304
                // TODO(yy): if the above `!ok` is chosen, we'd have
305
                // `bandwidth` to be the max value, which will end up having
306
                // the `maxBandwidth` to be have the largest value and this
307
                // edge will be the chosen one. This is wrong in two ways,
308
                // 1. we need to understand why `availableChanBandwidth` cannot
309
                // find bandwidth for this edge as something is wrong with this
310
                // channel, and,
311
                // 2. this edge is likely NOT the local channel with the
312
                // highest available bandwidth.
313
                //
314
                // Skip channels that can't carry the payment.
315
                if amt > bandwidth {
6✔
316
                        log.Debugf("Skipped edge %v: not enough bandwidth, "+
3✔
317
                                "bandwidth=%v, amt=%v", edge.policy.ChannelID,
3✔
318
                                bandwidth, amt)
3✔
319

3✔
320
                        continue
3✔
321
                }
322

323
                // We pick the local channel with the highest available
324
                // bandwidth, to maximize the success probability. It can be
325
                // that the channel state changes between querying the bandwidth
326
                // hints and sending out the htlc.
327
                if bandwidth < maxBandwidth {
3✔
UNCOV
328
                        log.Debugf("Skipped edge %v: not max bandwidth, "+
×
UNCOV
329
                                "bandwidth=%v, maxBandwidth=%v",
×
UNCOV
330
                                edge.policy.ChannelID, bandwidth, maxBandwidth)
×
UNCOV
331

×
UNCOV
332
                        continue
×
333
                }
334
                maxBandwidth = bandwidth
3✔
335

3✔
336
                // Update best edge.
3✔
337
                bestEdge = newUnifiedEdge(
3✔
338
                        edge.policy, edge.capacity, edge.inboundFees,
3✔
339
                        edge.hopPayloadSizeFn, edge.blindedPayment,
3✔
340
                )
3✔
341
        }
342

343
        return bestEdge
3✔
344
}
345

346
// getEdgeNetwork returns the optimal unified edge to use for this connection
347
// given a specific amount to send. The goal is to return a unified edge with a
348
// policy that maximizes the probability of a successful forward in a non-strict
349
// forwarding context.
350
func (u *edgeUnifier) getEdgeNetwork(netAmtReceived lnwire.MilliSatoshi,
351
        nextOutFee lnwire.MilliSatoshi) *unifiedEdge {
3✔
352

3✔
353
        var (
3✔
354
                bestPolicy       *unifiedEdge
3✔
355
                maxFee           int64 = math.MinInt64
3✔
356
                maxTimelock      uint16
3✔
357
                maxCapMsat       lnwire.MilliSatoshi
3✔
358
                hopPayloadSizeFn PayloadSizeFunc
3✔
359
        )
3✔
360

3✔
361
        for _, edge := range u.edges {
6✔
362
                // Calculate the inbound fee charged at the receiving node.
3✔
363
                inboundFee := calcCappedInboundFee(
3✔
364
                        edge, netAmtReceived, nextOutFee,
3✔
365
                )
3✔
366

3✔
367
                // Add inbound fee to get to the amount that is sent over the
3✔
368
                // channel.
3✔
369
                amt := netAmtReceived + lnwire.MilliSatoshi(inboundFee)
3✔
370

3✔
371
                // Check valid amount range for the channel.
3✔
372
                if !edge.amtInRange(amt) {
6✔
373
                        log.Debugf("Amount %v not in range for edge %v",
3✔
374
                                amt, edge.policy.ChannelID)
3✔
375
                        continue
3✔
376
                }
377

378
                // For network channels, skip the disabled ones.
379
                if edge.policy.IsDisabled() {
3✔
UNCOV
380
                        log.Debugf("Skipped edge %v due to it being disabled",
×
UNCOV
381
                                edge.policy.ChannelID)
×
UNCOV
382
                        continue
×
383
                }
384

385
                // Track the maximal capacity for usable channels. If we don't
386
                // know the capacity, we fall back to MaxHTLC.
387
                capMsat := lnwire.NewMSatFromSatoshis(edge.capacity)
3✔
388
                if capMsat == 0 && edge.policy.MessageFlags.HasMaxHtlc() {
3✔
UNCOV
389
                        log.Tracef("No capacity available for channel %v, "+
×
UNCOV
390
                                "using MaxHtlcMsat (%v) as a fallback.",
×
UNCOV
391
                                edge.policy.ChannelID, edge.policy.MaxHTLC)
×
UNCOV
392

×
UNCOV
393
                        capMsat = edge.policy.MaxHTLC
×
UNCOV
394
                }
×
395
                maxCapMsat = max(capMsat, maxCapMsat)
3✔
396

3✔
397
                // Track the maximum time lock of all channels that are
3✔
398
                // candidate for non-strict forwarding at the routing node.
3✔
399
                maxTimelock = max(maxTimelock, edge.policy.TimeLockDelta)
3✔
400

3✔
401
                outboundFee := int64(edge.policy.ComputeFee(amt))
3✔
402
                fee := outboundFee + inboundFee
3✔
403

3✔
404
                // Use the policy that results in the highest fee for this
3✔
405
                // specific amount.
3✔
406
                if fee < maxFee {
3✔
UNCOV
407
                        log.Debugf("Skipped edge %v due to it produces less "+
×
UNCOV
408
                                "fee: fee=%v, maxFee=%v",
×
UNCOV
409
                                edge.policy.ChannelID, fee, maxFee)
×
UNCOV
410

×
UNCOV
411
                        continue
×
412
                }
413
                maxFee = fee
3✔
414

3✔
415
                bestPolicy = newUnifiedEdge(
3✔
416
                        edge.policy, 0, edge.inboundFees, nil,
3✔
417
                        edge.blindedPayment,
3✔
418
                )
3✔
419

3✔
420
                // The payload size function for edges to a connected peer is
3✔
421
                // always the same hence there is not need to find the maximum.
3✔
422
                // This also counts for blinded edges where we only have one
3✔
423
                // edge to a blinded peer.
3✔
424
                hopPayloadSizeFn = edge.hopPayloadSizeFn
3✔
425
        }
426

427
        // Return early if no channel matches.
428
        if bestPolicy == nil {
6✔
429
                return nil
3✔
430
        }
3✔
431

432
        // We have already picked the highest fee that could be required for
433
        // non-strict forwarding. To also cover the case where a lower fee
434
        // channel requires a longer time lock, we modify the policy by setting
435
        // the maximum encountered time lock. Note that this results in a
436
        // synthetic policy that is not actually present on the routing node.
437
        //
438
        // The reason we do this, is that we try to maximize the chance that we
439
        // get forwarded. Because we penalize pair-wise, there won't be a second
440
        // chance for this node pair. But this is all only needed for nodes that
441
        // have distinct policies for channels to the same peer.
442
        policyCopy := *bestPolicy.policy
3✔
443
        policyCopy.TimeLockDelta = maxTimelock
3✔
444
        modifiedEdge := newUnifiedEdge(
3✔
445
                &policyCopy, maxCapMsat.ToSatoshis(), bestPolicy.inboundFees,
3✔
446
                hopPayloadSizeFn, bestPolicy.blindedPayment,
3✔
447
        )
3✔
448

3✔
449
        return modifiedEdge
3✔
450
}
451

452
// minAmt returns the minimum amount that can be forwarded on this connection.
UNCOV
453
func (u *edgeUnifier) minAmt() lnwire.MilliSatoshi {
×
UNCOV
454
        minAmount := lnwire.MaxMilliSatoshi
×
UNCOV
455
        for _, edge := range u.edges {
×
UNCOV
456
                minAmount = min(minAmount, edge.policy.MinHTLC)
×
UNCOV
457
        }
×
458

UNCOV
459
        return minAmount
×
460
}
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