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

lightningnetwork / lnd / 16683051882

01 Aug 2025 07:03PM UTC coverage: 54.949% (-12.1%) from 67.047%
16683051882

Pull #9455

github

web-flow
Merge 3f1f50be8 into 37523b6cb
Pull Request #9455: discovery+lnwire: add support for DNS host name in NodeAnnouncement msg

144 of 226 new or added lines in 7 files covered. (63.72%)

23852 existing lines in 290 files now uncovered.

108751 of 197912 relevant lines covered (54.95%)

22080.83 hits per line

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

94.46
/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 {
714✔
37

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

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

1,674✔
58
        // Skip channels if there is an outgoing channel restriction.
1,674✔
59
        if localChan && u.outChanRestr != nil {
1,688✔
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,666✔
70
        if !ok {
3,315✔
71
                unifier = &edgeUnifier{
1,649✔
72
                        localChan: localChan,
1,649✔
73
                }
1,649✔
74
                u.edgeUnifiers[fromNode] = unifier
1,649✔
75
        }
1,649✔
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,666✔
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,161✔
89
                inboundFee = models.InboundFee{}
495✔
90
        }
495✔
91

92
        unifier.edges = append(unifier.edges, newUnifiedEdge(
1,666✔
93
                edge, capacity, inboundFee, hopPayloadSizeFn, blindedPayment,
1,666✔
94
        ))
1,666✔
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 {
708✔
100
        var channels []*graphdb.DirectedChannel
708✔
101
        cb := func(channel *graphdb.DirectedChannel) error {
2,356✔
102
                // If there is no edge policy for this candidate node, skip.
1,648✔
103
                // Note that we are searching backwards so this node would have
1,648✔
104
                // come prior to the pivot node in the route.
1,648✔
105
                if channel.InPolicy == nil {
1,648✔
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)
1,648✔
113

1,648✔
114
                return nil
1,648✔
115
        }
116

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

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

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

142
        return nil
708✔
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 {
4,085✔
167

4,085✔
168
        return &unifiedEdge{
4,085✔
169
                policy:           policy,
4,085✔
170
                capacity:         capacity,
4,085✔
171
                inboundFees:      inboundFees,
4,085✔
172
                hopPayloadSizeFn: hopPayloadSizeFn,
4,085✔
173
                blindedPayment:   blindedPayment,
4,085✔
174
        }
4,085✔
175
}
4,085✔
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 {
1,351✔
180
        // If the capacity is available (non-light clients), skip channels that
1,351✔
181
        // are too small.
1,351✔
182
        if u.capacity > 0 &&
1,351✔
183
                amt > lnwire.NewMSatFromSatoshis(u.capacity) {
1,365✔
184

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

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

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

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

206
        return true
1,320✔
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 {
1,319✔
221

1,319✔
222
        if u.localChan {
1,491✔
223
                return u.getEdgeLocal(
172✔
224
                        netAmtReceived, bandwidthHints, nextOutFee,
172✔
225
                )
172✔
226
        }
172✔
227

228
        return u.getEdgeNetwork(netAmtReceived, nextOutFee)
1,147✔
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 {
1,344✔
235

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

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

245
        return inboundFee
1,344✔
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 {
172✔
253

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

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

175✔
265
                // Add inbound fee to get to the amount that is sent over the
175✔
266
                // local channel.
175✔
267
                amt := netAmtReceived + lnwire.MilliSatoshi(inboundFee)
175✔
268

175✔
269
                // Check valid amount range for the channel. We skip this test
175✔
270
                // for payments with custom HTLC data, as the amount sent on
175✔
271
                // the BTC layer may differ from the amount that is actually
175✔
272
                // forwarded in custom channels.
175✔
273
                if bandwidthHints.firstHopCustomBlob().IsNone() &&
175✔
274
                        !edge.amtInRange(amt) {
186✔
275

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

11✔
279
                        continue
11✔
280
                }
281

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

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

79✔
300
                        bandwidth = lnwire.MaxMilliSatoshi
79✔
301
                }
79✔
302

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

7✔
319
                        continue
7✔
320
                }
321

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

3✔
331
                        continue
3✔
332
                }
333
                maxBandwidth = bandwidth
154✔
334

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

342
        return bestEdge
172✔
343
}
344

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

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

1,147✔
360
        for _, edge := range u.edges {
2,305✔
361
                // Calculate the inbound fee charged at the receiving node.
1,158✔
362
                inboundFee := calcCappedInboundFee(
1,158✔
363
                        edge, netAmtReceived, nextOutFee,
1,158✔
364
                )
1,158✔
365

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

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

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

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

2✔
392
                        capMsat = edge.policy.MaxHTLC
2✔
393
                }
2✔
394
                maxCapMsat = max(capMsat, maxCapMsat)
1,137✔
395

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

1,137✔
400
                outboundFee := int64(edge.policy.ComputeFee(amt))
1,137✔
401
                fee := outboundFee + inboundFee
1,137✔
402

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

1✔
410
                        continue
1✔
411
                }
412
                maxFee = fee
1,136✔
413

1,136✔
414
                bestPolicy = newUnifiedEdge(
1,136✔
415
                        edge.policy, 0, edge.inboundFees, nil,
1,136✔
416
                        edge.blindedPayment,
1,136✔
417
                )
1,136✔
418

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

426
        // Return early if no channel matches.
427
        if bestPolicy == nil {
1,165✔
428
                return nil
18✔
429
        }
18✔
430

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

1,129✔
448
        return modifiedEdge
1,129✔
449
}
450

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

458
        return minAmount
11✔
459
}
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