• 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

79.44
/routing/unified_edges.go
1
package routing
2

3
import (
4
        "math"
5

6
        "github.com/btcsuite/btcd/btcutil"
7
        "github.com/lightningnetwork/lnd/channeldb"
8
        "github.com/lightningnetwork/lnd/channeldb/models"
9
        "github.com/lightningnetwork/lnd/lntypes"
10
        "github.com/lightningnetwork/lnd/lnwire"
11
        "github.com/lightningnetwork/lnd/routing/route"
12
)
13

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

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

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

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

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

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

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

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

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

3✔
59
        // Skip channels if there is an outgoing channel restriction.
3✔
60
        if localChan && u.outChanRestr != nil {
3✔
61
                if _, ok := u.outChanRestr[edge.ChannelID]; !ok {
×
62
                        return
×
63
                }
×
64
        }
65

66
        // Update the edgeUnifiers map.
67
        unifier, ok := u.edgeUnifiers[fromNode]
3✔
68
        if !ok {
6✔
69
                unifier = &edgeUnifier{
3✔
70
                        localChan: localChan,
3✔
71
                }
3✔
72
                u.edgeUnifiers[fromNode] = unifier
3✔
73
        }
3✔
74

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

×
82
                return
×
83
        }
×
84

85
        // Zero inbound fee for exit hops.
86
        if !u.useInboundFees {
6✔
87
                inboundFee = models.InboundFee{}
3✔
88
        }
3✔
89

90
        unifier.edges = append(unifier.edges, newUnifiedEdge(
3✔
91
                edge, capacity, inboundFee, hopPayloadSizeFn, blindedPayment,
3✔
92
        ))
3✔
93
}
94

95
// addGraphPolicies adds all policies that are known for the toNode in the
96
// graph.
97
func (u *nodeEdgeUnifier) addGraphPolicies(g routingGraph) error {
3✔
98
        cb := func(channel *channeldb.DirectedChannel) error {
6✔
99
                // If there is no edge policy for this candidate node, skip.
3✔
100
                // Note that we are searching backwards so this node would have
3✔
101
                // come prior to the pivot node in the route.
3✔
102
                if channel.InPolicy == nil {
3✔
103
                        return nil
×
104
                }
×
105

106
                // Add this policy to the corresponding edgeUnifier. We default
107
                // to the clear hop payload size function because
108
                // `addGraphPolicies` is only used for cleartext intermediate
109
                // hops in a route.
110
                inboundFee := models.NewInboundFeeFromWire(
3✔
111
                        channel.InboundFee,
3✔
112
                )
3✔
113

3✔
114
                u.addPolicy(
3✔
115
                        channel.OtherNode, channel.InPolicy, inboundFee,
3✔
116
                        channel.Capacity, defaultHopPayloadSize, nil,
3✔
117
                )
3✔
118

3✔
119
                return nil
3✔
120
        }
121

122
        // Iterate over all channels of the to node.
123
        return g.forEachNodeChannel(u.toNode, cb)
3✔
124
}
125

126
// unifiedEdge is the individual channel data that is kept inside an edgeUnifier
127
// object.
128
type unifiedEdge struct {
129
        policy      *models.CachedEdgePolicy
130
        capacity    btcutil.Amount
131
        inboundFees models.InboundFee
132

133
        // hopPayloadSize supplies an edge with the ability to calculate the
134
        // exact payload size if this edge would be included in a route. This
135
        // is needed because hops of a blinded path differ in their payload
136
        // structure compared to cleartext hops.
137
        hopPayloadSizeFn PayloadSizeFunc
138

139
        // blindedPayment if set, is the BlindedPayment that this edge was
140
        // derived from originally.
141
        blindedPayment *BlindedPayment
142
}
143

144
// newUnifiedEdge constructs a new unifiedEdge.
145
func newUnifiedEdge(policy *models.CachedEdgePolicy, capacity btcutil.Amount,
146
        inboundFees models.InboundFee, hopPayloadSizeFn PayloadSizeFunc,
147
        blindedPayment *BlindedPayment) *unifiedEdge {
3✔
148

3✔
149
        return &unifiedEdge{
3✔
150
                policy:           policy,
3✔
151
                capacity:         capacity,
3✔
152
                inboundFees:      inboundFees,
3✔
153
                hopPayloadSizeFn: hopPayloadSizeFn,
3✔
154
                blindedPayment:   blindedPayment,
3✔
155
        }
3✔
156
}
3✔
157

158
// amtInRange checks whether an amount falls within the valid range for a
159
// channel.
160
func (u *unifiedEdge) amtInRange(amt lnwire.MilliSatoshi) bool {
3✔
161
        // If the capacity is available (non-light clients), skip channels that
3✔
162
        // are too small.
3✔
163
        if u.capacity > 0 &&
3✔
164
                amt > lnwire.NewMSatFromSatoshis(u.capacity) {
3✔
165

×
166
                log.Tracef("Not enough capacity: amt=%v, capacity=%v",
×
167
                        amt, u.capacity)
×
168
                return false
×
169
        }
×
170

171
        // Skip channels for which this htlc is too large.
172
        if u.policy.MessageFlags.HasMaxHtlc() &&
3✔
173
                amt > u.policy.MaxHTLC {
6✔
174

3✔
175
                log.Tracef("Exceeds policy's MaxHTLC: amt=%v, MaxHTLC=%v",
3✔
176
                        amt, u.policy.MaxHTLC)
3✔
177
                return false
3✔
178
        }
3✔
179

180
        // Skip channels for which this htlc is too small.
181
        if amt < u.policy.MinHTLC {
6✔
182
                log.Tracef("below policy's MinHTLC: amt=%v, MinHTLC=%v",
3✔
183
                        amt, u.policy.MinHTLC)
3✔
184
                return false
3✔
185
        }
3✔
186

187
        return true
3✔
188
}
189

190
// edgeUnifier is an object that covers all channels between a pair of nodes.
191
type edgeUnifier struct {
192
        edges     []*unifiedEdge
193
        localChan bool
194
}
195

196
// getEdge returns the optimal unified edge to use for this connection given a
197
// specific amount to send. It differentiates between local and network
198
// channels.
199
func (u *edgeUnifier) getEdge(netAmtReceived lnwire.MilliSatoshi,
200
        bandwidthHints bandwidthHints,
201
        nextOutFee lnwire.MilliSatoshi) *unifiedEdge {
3✔
202

3✔
203
        if u.localChan {
6✔
204
                return u.getEdgeLocal(
3✔
205
                        netAmtReceived, bandwidthHints, nextOutFee,
3✔
206
                )
3✔
207
        }
3✔
208

209
        return u.getEdgeNetwork(netAmtReceived, nextOutFee)
3✔
210
}
211

212
// calcCappedInboundFee calculates the inbound fee for a channel, taking into
213
// account the total node fee for the "to" node.
214
func calcCappedInboundFee(edge *unifiedEdge, amt lnwire.MilliSatoshi,
215
        nextOutFee lnwire.MilliSatoshi) int64 {
3✔
216

3✔
217
        // Calculate the inbound fee charged for the amount that passes over the
3✔
218
        // channel.
3✔
219
        inboundFee := edge.inboundFees.CalcFee(amt)
3✔
220

3✔
221
        // Take into account that the total node fee cannot be negative.
3✔
222
        if inboundFee < -int64(nextOutFee) {
3✔
223
                inboundFee = -int64(nextOutFee)
×
224
        }
×
225

226
        return inboundFee
3✔
227
}
228

229
// getEdgeLocal returns the optimal unified edge to use for this local
230
// connection given a specific amount to send.
231
func (u *edgeUnifier) getEdgeLocal(netAmtReceived lnwire.MilliSatoshi,
232
        bandwidthHints bandwidthHints,
233
        nextOutFee lnwire.MilliSatoshi) *unifiedEdge {
3✔
234

3✔
235
        var (
3✔
236
                bestEdge     *unifiedEdge
3✔
237
                maxBandwidth lnwire.MilliSatoshi
3✔
238
        )
3✔
239

3✔
240
        for _, edge := range u.edges {
6✔
241
                // Calculate the inbound fee charged at the receiving node.
3✔
242
                inboundFee := calcCappedInboundFee(
3✔
243
                        edge, netAmtReceived, nextOutFee,
3✔
244
                )
3✔
245

3✔
246
                // Add inbound fee to get to the amount that is sent over the
3✔
247
                // local channel.
3✔
248
                amt := netAmtReceived + lnwire.MilliSatoshi(inboundFee)
3✔
249

3✔
250
                // Check valid amount range for the channel.
3✔
251
                if !edge.amtInRange(amt) {
3✔
252
                        log.Debugf("Amount %v not in range for edge %v",
×
253
                                netAmtReceived, edge.policy.ChannelID)
×
254

×
255
                        continue
×
256
                }
257

258
                // For local channels, there is no fee to pay or an extra time
259
                // lock. We only consider the currently available bandwidth for
260
                // channel selection. The disabled flag is ignored for local
261
                // channels.
262

263
                // Retrieve bandwidth for this local channel. If not
264
                // available, assume this channel has enough bandwidth.
265
                //
266
                // TODO(joostjager): Possibly change to skipping this
267
                // channel. The bandwidth hint is expected to be
268
                // available.
269
                bandwidth, ok := bandwidthHints.availableChanBandwidth(
3✔
270
                        edge.policy.ChannelID, amt,
3✔
271
                )
3✔
272
                if !ok {
3✔
273
                        log.Debugf("Cannot get bandwidth for edge %v, use max "+
×
274
                                "instead", edge.policy.ChannelID)
×
275
                        bandwidth = lnwire.MaxMilliSatoshi
×
276
                }
×
277

278
                // TODO(yy): if the above `!ok` is chosen, we'd have
279
                // `bandwidth` to be the max value, which will end up having
280
                // the `maxBandwidth` to be have the largest value and this
281
                // edge will be the chosen one. This is wrong in two ways,
282
                // 1. we need to understand why `availableChanBandwidth` cannot
283
                // find bandwidth for this edge as something is wrong with this
284
                // channel, and,
285
                // 2. this edge is likely NOT the local channel with the
286
                // highest available bandwidth.
287
                //
288
                // Skip channels that can't carry the payment.
289
                if amt > bandwidth {
6✔
290
                        log.Debugf("Skipped edge %v: not enough bandwidth, "+
3✔
291
                                "bandwidth=%v, amt=%v", edge.policy.ChannelID,
3✔
292
                                bandwidth, amt)
3✔
293

3✔
294
                        continue
3✔
295
                }
296

297
                // We pick the local channel with the highest available
298
                // bandwidth, to maximize the success probability. It can be
299
                // that the channel state changes between querying the bandwidth
300
                // hints and sending out the htlc.
301
                if bandwidth < maxBandwidth {
3✔
302
                        log.Debugf("Skipped edge %v: not max bandwidth, "+
×
303
                                "bandwidth=%v, maxBandwidth=%v",
×
304
                                edge.policy.ChannelID, bandwidth, maxBandwidth)
×
305

×
306
                        continue
×
307
                }
308
                maxBandwidth = bandwidth
3✔
309

3✔
310
                // Update best edge.
3✔
311
                bestEdge = newUnifiedEdge(
3✔
312
                        edge.policy, edge.capacity, edge.inboundFees,
3✔
313
                        edge.hopPayloadSizeFn, edge.blindedPayment,
3✔
314
                )
3✔
315
        }
316

317
        return bestEdge
3✔
318
}
319

320
// getEdgeNetwork returns the optimal unified edge to use for this connection
321
// given a specific amount to send. The goal is to return a unified edge with a
322
// policy that maximizes the probability of a successful forward in a non-strict
323
// forwarding context.
324
func (u *edgeUnifier) getEdgeNetwork(netAmtReceived lnwire.MilliSatoshi,
325
        nextOutFee lnwire.MilliSatoshi) *unifiedEdge {
3✔
326

3✔
327
        var (
3✔
328
                bestPolicy       *unifiedEdge
3✔
329
                maxFee           int64 = math.MinInt64
3✔
330
                maxTimelock      uint16
3✔
331
                maxCapMsat       lnwire.MilliSatoshi
3✔
332
                hopPayloadSizeFn PayloadSizeFunc
3✔
333
        )
3✔
334

3✔
335
        for _, edge := range u.edges {
6✔
336
                // Calculate the inbound fee charged at the receiving node.
3✔
337
                inboundFee := calcCappedInboundFee(
3✔
338
                        edge, netAmtReceived, nextOutFee,
3✔
339
                )
3✔
340

3✔
341
                // Add inbound fee to get to the amount that is sent over the
3✔
342
                // channel.
3✔
343
                amt := netAmtReceived + lnwire.MilliSatoshi(inboundFee)
3✔
344

3✔
345
                // Check valid amount range for the channel.
3✔
346
                if !edge.amtInRange(amt) {
6✔
347
                        log.Debugf("Amount %v not in range for edge %v",
3✔
348
                                amt, edge.policy.ChannelID)
3✔
349
                        continue
3✔
350
                }
351

352
                // For network channels, skip the disabled ones.
353
                edgeFlags := edge.policy.ChannelFlags
3✔
354
                isDisabled := edgeFlags&lnwire.ChanUpdateDisabled != 0
3✔
355
                if isDisabled {
3✔
356
                        log.Debugf("Skipped edge %v due to it being disabled",
×
357
                                edge.policy.ChannelID)
×
358
                        continue
×
359
                }
360

361
                // Track the maximal capacity for usable channels. If we don't
362
                // know the capacity, we fall back to MaxHTLC.
363
                capMsat := lnwire.NewMSatFromSatoshis(edge.capacity)
3✔
364
                if capMsat == 0 && edge.policy.MessageFlags.HasMaxHtlc() {
3✔
365
                        log.Tracef("No capacity available for channel %v, "+
×
366
                                "using MaxHtlcMsat (%v) as a fallback.",
×
367
                                edge.policy.ChannelID, edge.policy.MaxHTLC)
×
368

×
369
                        capMsat = edge.policy.MaxHTLC
×
370
                }
×
371
                maxCapMsat = lntypes.Max(capMsat, maxCapMsat)
3✔
372

3✔
373
                // Track the maximum time lock of all channels that are
3✔
374
                // candidate for non-strict forwarding at the routing node.
3✔
375
                maxTimelock = lntypes.Max(
3✔
376
                        maxTimelock, edge.policy.TimeLockDelta,
3✔
377
                )
3✔
378

3✔
379
                outboundFee := int64(edge.policy.ComputeFee(amt))
3✔
380
                fee := outboundFee + inboundFee
3✔
381

3✔
382
                // Use the policy that results in the highest fee for this
3✔
383
                // specific amount.
3✔
384
                if fee < maxFee {
3✔
385
                        log.Debugf("Skipped edge %v due to it produces less "+
×
386
                                "fee: fee=%v, maxFee=%v",
×
387
                                edge.policy.ChannelID, fee, maxFee)
×
388

×
389
                        continue
×
390
                }
391
                maxFee = fee
3✔
392

3✔
393
                bestPolicy = newUnifiedEdge(
3✔
394
                        edge.policy, 0, edge.inboundFees, nil,
3✔
395
                        edge.blindedPayment,
3✔
396
                )
3✔
397

3✔
398
                // The payload size function for edges to a connected peer is
3✔
399
                // always the same hence there is not need to find the maximum.
3✔
400
                // This also counts for blinded edges where we only have one
3✔
401
                // edge to a blinded peer.
3✔
402
                hopPayloadSizeFn = edge.hopPayloadSizeFn
3✔
403
        }
404

405
        // Return early if no channel matches.
406
        if bestPolicy == nil {
6✔
407
                return nil
3✔
408
        }
3✔
409

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

3✔
427
        return modifiedEdge
3✔
428
}
429

430
// minAmt returns the minimum amount that can be forwarded on this connection.
431
func (u *edgeUnifier) minAmt() lnwire.MilliSatoshi {
×
432
        min := lnwire.MaxMilliSatoshi
×
433
        for _, edge := range u.edges {
×
434
                min = lntypes.Min(min, edge.policy.MinHTLC)
×
435
        }
×
436

437
        return min
×
438
}
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