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

lightningnetwork / lnd / 18016273007

25 Sep 2025 05:55PM UTC coverage: 54.653% (-12.0%) from 66.622%
18016273007

Pull #10248

github

web-flow
Merge 128443298 into b09b20c69
Pull Request #10248: Enforce TLV when creating a Route

25 of 30 new or added lines in 4 files covered. (83.33%)

23906 existing lines in 281 files now uncovered.

109536 of 200421 relevant lines covered (54.65%)

21816.97 hits per line

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

88.43
/routing/pathfind.go
1
package routing
2

3
import (
4
        "bytes"
5
        "container/heap"
6
        "errors"
7
        "fmt"
8
        "math"
9
        "sort"
10
        "time"
11

12
        "github.com/btcsuite/btcd/btcutil"
13
        sphinx "github.com/lightningnetwork/lightning-onion"
14
        "github.com/lightningnetwork/lnd/feature"
15
        "github.com/lightningnetwork/lnd/fn/v2"
16
        graphdb "github.com/lightningnetwork/lnd/graph/db"
17
        "github.com/lightningnetwork/lnd/graph/db/models"
18
        "github.com/lightningnetwork/lnd/lnutils"
19
        "github.com/lightningnetwork/lnd/lnwire"
20
        "github.com/lightningnetwork/lnd/record"
21
        "github.com/lightningnetwork/lnd/routing/route"
22
)
23

24
const (
25
        // infinity is used as a starting distance in our shortest path search.
26
        infinity = math.MaxInt64
27

28
        // RiskFactorBillionths controls the influence of time lock delta
29
        // of a channel on route selection. It is expressed as billionths
30
        // of msat per msat sent through the channel per time lock delta
31
        // block. See edgeWeight function below for more details.
32
        // The chosen value is based on the previous incorrect weight function
33
        // 1 + timelock + fee * fee. In this function, the fee penalty
34
        // diminishes the time lock penalty for all but the smallest amounts.
35
        // To not change the behaviour of path finding too drastically, a
36
        // relatively small value is chosen which is still big enough to give
37
        // some effect with smaller time lock values. The value may need
38
        // tweaking and/or be made configurable in the future.
39
        RiskFactorBillionths = 15
40

41
        // estimatedNodeCount is used to preallocate the path finding structures
42
        // to avoid resizing and copies. It should be number on the same order as
43
        // the number of active nodes in the network.
44
        estimatedNodeCount = 10000
45

46
        // fakeHopHintCapacity is the capacity we assume for hop hint channels.
47
        // This is a high number, which expresses that a hop hint channel should
48
        // be able to route payments.
49
        fakeHopHintCapacity = btcutil.Amount(10 * btcutil.SatoshiPerBitcoin)
50
)
51

52
// pathFinder defines the interface of a path finding algorithm.
53
type pathFinder = func(g *graphParams, r *RestrictParams,
54
        cfg *PathFindingConfig, self, source, target route.Vertex,
55
        amt lnwire.MilliSatoshi, timePref float64, finalHtlcExpiry int32) (
56
        []*unifiedEdge, float64, error)
57

58
var (
59
        // DefaultEstimator is the default estimator used for computing
60
        // probabilities in pathfinding.
61
        DefaultEstimator = AprioriEstimatorName
62

63
        // DefaultAttemptCost is the default fixed virtual cost in path finding
64
        // of a failed payment attempt. It is used to trade off potentially
65
        // better routes against their probability of succeeding.
66
        DefaultAttemptCost = lnwire.NewMSatFromSatoshis(100)
67

68
        // DefaultAttemptCostPPM is the default proportional virtual cost in
69
        // path finding weight units of executing a payment attempt that fails.
70
        // It is used to trade off potentially better routes against their
71
        // probability of succeeding. This parameter is expressed in parts per
72
        // million of the payment amount.
73
        //
74
        // It is impossible to pick a perfect default value. The current value
75
        // of 0.1% is based on the idea that a transaction fee of 1% is within
76
        // reasonable territory and that a payment shouldn't need more than 10
77
        // attempts.
78
        DefaultAttemptCostPPM = int64(1000)
79

80
        // DefaultMinRouteProbability is the default minimum probability for routes
81
        // returned from findPath.
82
        DefaultMinRouteProbability = float64(0.01)
83

84
        // DefaultAprioriHopProbability is the default a priori probability for
85
        // a hop.
86
        DefaultAprioriHopProbability = float64(0.6)
87
)
88

89
// edgePolicyWithSource is a helper struct to keep track of the source node
90
// of a channel edge. ChannelEdgePolicy only contains to destination node
91
// of the edge.
92
type edgePolicyWithSource struct {
93
        sourceNode route.Vertex
94
        edge       AdditionalEdge
95
}
96

97
// finalHopParams encapsulates various parameters for route construction that
98
// apply to the final hop in a route. These features include basic payment data
99
// such as amounts and cltvs, as well as more complex features like destination
100
// custom records and payment address.
101
type finalHopParams struct {
102
        amt      lnwire.MilliSatoshi
103
        totalAmt lnwire.MilliSatoshi
104

105
        // cltvDelta is the final hop's minimum CLTV expiry delta.
106
        //
107
        // NOTE that in the case of paying to a blinded path, this value will
108
        // be set to a duplicate of the blinded path's accumulated CLTV value.
109
        // We would then only need to use this value in the case where the
110
        // introduction node of the path is also the destination node.
111
        cltvDelta uint16
112

113
        records     record.CustomSet
114
        paymentAddr fn.Option[[32]byte]
115

116
        // metadata is additional data that is sent along with the payment to
117
        // the payee.
118
        metadata []byte
119
}
120

121
// newRoute constructs a route using the provided path and final hop constraints.
122
// Any destination specific fields from the final hop params  will be attached
123
// assuming the destination's feature vector signals support, otherwise this
124
// method will fail.  If the route is too long, or the selected path cannot
125
// support the fully payment including fees, then a non-nil error is returned.
126
// If the route is to a blinded path, the blindedPath parameter is used to
127
// back fill additional fields that are required for a blinded payment. This is
128
// done in a separate pass to keep our route construction simple, as blinded
129
// paths require zero expiry and amount values for intermediate hops (which
130
// makes calculating the totals during route construction difficult if we
131
// include blinded paths on the first pass).
132
//
133
// NOTE: The passed slice of unified edges MUST be sorted in forward order: from
134
// the source to the target node of the path finding attempt. It is assumed that
135
// any feature vectors on all hops have been validated for transitive
136
// dependencies.
137
// NOTE: If a non-nil blinded path is provided it is assumed to have been
138
// validated by the caller.
139
func newRoute(sourceVertex route.Vertex,
140
        pathEdges []*unifiedEdge, currentHeight uint32, finalHop finalHopParams,
141
        blindedPathSet *BlindedPaymentPathSet) (*route.Route, error) {
93✔
142

93✔
143
        var (
93✔
144
                hops []*route.Hop
93✔
145

93✔
146
                // totalTimeLock will accumulate the cumulative time lock
93✔
147
                // across the entire route. This value represents how long the
93✔
148
                // sender will need to wait in the *worst* case.
93✔
149
                totalTimeLock = currentHeight
93✔
150

93✔
151
                // nextIncomingAmount is the amount that will need to flow into
93✔
152
                // the *next* hop. Since we're going to be walking the route
93✔
153
                // backwards below, this next hop gets closer and closer to the
93✔
154
                // sender of the payment.
93✔
155
                nextIncomingAmount lnwire.MilliSatoshi
93✔
156

93✔
157
                blindedPayment *BlindedPayment
93✔
158
        )
93✔
159

93✔
160
        pathLength := len(pathEdges)
93✔
161

93✔
162
        // When paying to a blinded route we might have appended a dummy hop at
93✔
163
        // the end to make MPP payments possible via all paths of the blinded
93✔
164
        // route set. We always append a dummy hop when the internal pathfiner
93✔
165
        // looks for a route to a blinded path which is at least one hop long
93✔
166
        // (excluding the introduction point). We add this dummy hop so that
93✔
167
        // we search for a universal target but also respect potential mc
93✔
168
        // entries which might already be present for a particular blinded path.
93✔
169
        // However when constructing the Sphinx packet we need to remove this
93✔
170
        // dummy hop again which we do here.
93✔
171
        //
93✔
172
        // NOTE: The path length is always at least 1 because there must be one
93✔
173
        // edge from the source to the destination. However we check for > 0
93✔
174
        // just for robustness here.
93✔
175
        if blindedPathSet != nil && pathLength > 0 {
94✔
176
                finalBlindedPubKey := pathEdges[pathLength-1].policy.
1✔
177
                        ToNodePubKey()
1✔
178

1✔
179
                if IsBlindedRouteNUMSTargetKey(finalBlindedPubKey[:]) {
1✔
UNCOV
180
                        // If the last hop is the NUMS key for blinded paths, we
×
UNCOV
181
                        // remove the dummy hop from the route.
×
UNCOV
182
                        pathEdges = pathEdges[:pathLength-1]
×
UNCOV
183
                        pathLength--
×
UNCOV
184
                }
×
185
        }
186

187
        for i := pathLength - 1; i >= 0; i-- {
309✔
188
                // Now we'll start to calculate the items within the per-hop
216✔
189
                // payload for the hop this edge is leading to.
216✔
190
                edge := pathEdges[i].policy
216✔
191

216✔
192
                // If this is an edge from a blinded path and the
216✔
193
                // blindedPayment variable has not been set yet, then set it now
216✔
194
                // by extracting the corresponding blinded payment from the
216✔
195
                // edge.
216✔
196
                isBlindedEdge := pathEdges[i].blindedPayment != nil
216✔
197
                if isBlindedEdge && blindedPayment == nil {
217✔
198
                        blindedPayment = pathEdges[i].blindedPayment
1✔
199
                }
1✔
200

201
                // We'll calculate the amounts, timelocks, and fees for each hop
202
                // in the route. The base case is the final hop which includes
203
                // their amount and timelocks. These values will accumulate
204
                // contributions from the preceding hops back to the sender as
205
                // we compute the route in reverse.
206
                var (
216✔
207
                        amtToForward        lnwire.MilliSatoshi
216✔
208
                        fee                 int64
216✔
209
                        totalAmtMsatBlinded lnwire.MilliSatoshi
216✔
210
                        outgoingTimeLock    uint32
216✔
211
                        customRecords       record.CustomSet
216✔
212
                        mpp                 *record.MPP
216✔
213
                        metadata            []byte
216✔
214
                )
216✔
215

216✔
216
                // Define a helper function that checks this edge's feature
216✔
217
                // vector for support for a given feature. We assume at this
216✔
218
                // point that the feature vectors transitive dependencies have
216✔
219
                // been validated.
216✔
220
                supports := func(feature lnwire.FeatureBit) bool {
525✔
221
                        // If this edge comes from router hints, the features
309✔
222
                        // could be nil.
309✔
223
                        if edge.ToNodeFeatures == nil {
309✔
224
                                return false
×
225
                        }
×
226
                        return edge.ToNodeFeatures.HasFeature(feature)
309✔
227
                }
228

229
                // We pack payloads always in TLV format, therefore it will fail
230
                // anyways at the forwarding/receiving node in case it doesn't
231
                // support it.
232
                tlvPayloadSupport := supports(lnwire.TLVOnionPayloadOptional)
216✔
233
                if !tlvPayloadSupport {
216✔
NEW
234
                        return nil, errors.New("cannot use a route with hops " +
×
NEW
235
                                "that don't support TLV payloads")
×
NEW
236
                }
×
237

238
                if i == len(pathEdges)-1 {
309✔
239
                        // If this is the last hop, then the hop payload will
93✔
240
                        // contain the exact amount. In BOLT #4: Onion Routing
93✔
241
                        // Protocol / "Payload for the Last Node", this is
93✔
242
                        // detailed.
93✔
243
                        amtToForward = finalHop.amt
93✔
244

93✔
245
                        // Fee is not part of the hop payload, but only used for
93✔
246
                        // reporting through RPC. Set to zero for the final hop.
93✔
247
                        fee = 0
93✔
248

93✔
249
                        if blindedPathSet == nil {
185✔
250
                                totalTimeLock += uint32(finalHop.cltvDelta)
92✔
251
                        } else {
93✔
252
                                totalTimeLock += uint32(
1✔
253
                                        blindedPathSet.FinalCLTVDelta(),
1✔
254
                                )
1✔
255
                        }
1✔
256
                        outgoingTimeLock = totalTimeLock
93✔
257

93✔
258
                        // Attach any custom records to the final hop.
93✔
259
                        customRecords = finalHop.records
93✔
260

93✔
261
                        // If we're attaching a payment addr but the receiver
93✔
262
                        // doesn't support both TLV and payment addrs, fail.
93✔
263
                        payAddr := supports(lnwire.PaymentAddrOptional)
93✔
264
                        if !payAddr && finalHop.paymentAddr.IsSome() {
93✔
265
                                return nil, errors.New("cannot attach " +
×
266
                                        "payment addr")
×
267
                        }
×
268

269
                        // Otherwise attach the mpp record if it exists.
270
                        // TODO(halseth): move this to payment life cycle,
271
                        // where AMP options are set.
272
                        finalHop.paymentAddr.WhenSome(func(addr [32]byte) {
135✔
273
                                mpp = record.NewMPP(finalHop.totalAmt, addr)
42✔
274
                        })
42✔
275

276
                        metadata = finalHop.metadata
93✔
277

93✔
278
                        if blindedPathSet != nil {
94✔
279
                                totalAmtMsatBlinded = finalHop.totalAmt
1✔
280
                        }
1✔
281
                } else {
123✔
282
                        // The amount that the current hop needs to forward is
123✔
283
                        // equal to the incoming amount of the next hop.
123✔
284
                        amtToForward = nextIncomingAmount
123✔
285

123✔
286
                        // The fee that needs to be paid to the current hop is
123✔
287
                        // based on the amount that this hop needs to forward
123✔
288
                        // and its policy for the outgoing channel. This policy
123✔
289
                        // is stored as part of the incoming channel of
123✔
290
                        // the next hop.
123✔
291
                        outboundFee := pathEdges[i+1].policy.ComputeFee(
123✔
292
                                amtToForward,
123✔
293
                        )
123✔
294

123✔
295
                        inboundFee := pathEdges[i].inboundFees.CalcFee(
123✔
296
                                amtToForward + outboundFee,
123✔
297
                        )
123✔
298

123✔
299
                        fee = int64(outboundFee) + inboundFee
123✔
300
                        if fee < 0 {
125✔
301
                                fee = 0
2✔
302
                        }
2✔
303

304
                        // We'll take the total timelock of the preceding hop as
305
                        // the outgoing timelock or this hop. Then we'll
306
                        // increment the total timelock incurred by this hop.
307
                        outgoingTimeLock = totalTimeLock
123✔
308
                        totalTimeLock += uint32(
123✔
309
                                pathEdges[i+1].policy.TimeLockDelta,
123✔
310
                        )
123✔
311
                }
312

313
                // Since we're traversing the path backwards atm, we prepend
314
                // each new hop such that, the final slice of hops will be in
315
                // the forwards order.
316
                currentHop := &route.Hop{
216✔
317
                        PubKeyBytes:      edge.ToNodePubKey(),
216✔
318
                        ChannelID:        edge.ChannelID,
216✔
319
                        AmtToForward:     amtToForward,
216✔
320
                        OutgoingTimeLock: outgoingTimeLock,
216✔
321
                        CustomRecords:    customRecords,
216✔
322
                        MPP:              mpp,
216✔
323
                        Metadata:         metadata,
216✔
324
                        TotalAmtMsat:     totalAmtMsatBlinded,
216✔
325
                }
216✔
326

216✔
327
                hops = append([]*route.Hop{currentHop}, hops...)
216✔
328

216✔
329
                // Finally, we update the amount that needs to flow into the
216✔
330
                // *next* hop, which is the amount this hop needs to forward,
216✔
331
                // accounting for the fee that it takes.
216✔
332
                nextIncomingAmount = amtToForward + lnwire.MilliSatoshi(fee)
216✔
333
        }
334

335
        // If we are creating a route to a blinded path, we need to add some
336
        // additional data to the route that is required for blinded forwarding.
337
        // We do another pass on our edges to append this data.
338
        if blindedPathSet != nil {
94✔
339
                // If the passed in BlindedPaymentPathSet is non-nil but no
1✔
340
                // edge had a BlindedPayment attached, it means that the path
1✔
341
                // chosen was an introduction-node-only path. So in this case,
1✔
342
                // we can assume the relevant payment is the only one in the
1✔
343
                // payment set.
1✔
344
                if blindedPayment == nil {
1✔
UNCOV
345
                        var err error
×
UNCOV
346
                        blindedPayment, err = blindedPathSet.IntroNodeOnlyPath()
×
UNCOV
347
                        if err != nil {
×
348
                                return nil, err
×
349
                        }
×
350
                }
351

352
                var (
1✔
353
                        inBlindedRoute bool
1✔
354
                        dataIndex      = 0
1✔
355

1✔
356
                        blindedPath = blindedPayment.BlindedPath
1✔
357
                        introVertex = route.NewVertex(
1✔
358
                                blindedPath.IntroductionPoint,
1✔
359
                        )
1✔
360
                )
1✔
361

1✔
362
                for i, hop := range hops {
5✔
363
                        // Once we locate our introduction node, we know that
4✔
364
                        // every hop after this is part of the blinded route.
4✔
365
                        if bytes.Equal(hop.PubKeyBytes[:], introVertex[:]) {
5✔
366
                                inBlindedRoute = true
1✔
367
                                hop.BlindingPoint = blindedPath.BlindingPoint
1✔
368
                        }
1✔
369

370
                        // We don't need to modify edges outside of our blinded
371
                        // route.
372
                        if !inBlindedRoute {
5✔
373
                                continue
1✔
374
                        }
375

376
                        payload := blindedPath.BlindedHops[dataIndex].CipherText
3✔
377
                        hop.EncryptedData = payload
3✔
378

3✔
379
                        // All of the hops in a blinded route *except* the
3✔
380
                        // final hop should have zero amounts / time locks.
3✔
381
                        if i != len(hops)-1 {
5✔
382
                                hop.AmtToForward = 0
2✔
383
                                hop.OutgoingTimeLock = 0
2✔
384
                        }
2✔
385

386
                        dataIndex++
3✔
387
                }
388
        }
389

390
        // With the base routing data expressed as hops, build the full route
391
        newRoute, err := route.NewRouteFromHops(
93✔
392
                nextIncomingAmount, totalTimeLock, route.Vertex(sourceVertex),
93✔
393
                hops,
93✔
394
        )
93✔
395
        if err != nil {
93✔
396
                return nil, err
×
397
        }
×
398

399
        return newRoute, nil
93✔
400
}
401

402
// edgeWeight computes the weight of an edge. This value is used when searching
403
// for the shortest path within the channel graph between two nodes. Weight is
404
// is the fee itself plus a time lock penalty added to it. This benefits
405
// channels with shorter time lock deltas and shorter (hops) routes in general.
406
// RiskFactor controls the influence of time lock on route selection. This is
407
// currently a fixed value, but might be configurable in the future.
408
func edgeWeight(lockedAmt lnwire.MilliSatoshi, fee lnwire.MilliSatoshi,
409
        timeLockDelta uint16) int64 {
1,135✔
410
        // timeLockPenalty is the penalty for the time lock delta of this channel.
1,135✔
411
        // It is controlled by RiskFactorBillionths and scales proportional
1,135✔
412
        // to the amount that will pass through channel. Rationale is that it if
1,135✔
413
        // a twice as large amount gets locked up, it is twice as bad.
1,135✔
414
        timeLockPenalty := int64(lockedAmt) * int64(timeLockDelta) *
1,135✔
415
                RiskFactorBillionths / 1000000000
1,135✔
416

1,135✔
417
        return int64(fee) + timeLockPenalty
1,135✔
418
}
1,135✔
419

420
// graphParams wraps the set of graph parameters passed to findPath.
421
type graphParams struct {
422
        // graph is the ChannelGraph to be used during path finding.
423
        graph Graph
424

425
        // additionalEdges is an optional set of edges that should be
426
        // considered during path finding, that is not already found in the
427
        // channel graph. These can either be private edges for bolt 11 invoices
428
        // or blinded edges when a payment to a blinded path is made.
429
        additionalEdges map[route.Vertex][]AdditionalEdge
430

431
        // bandwidthHints is an interface that provides bandwidth hints that
432
        // can provide a better estimate of the current channel bandwidth than
433
        // what is found in the graph. It will override the capacities and
434
        // disabled flags found in the graph for local channels when doing
435
        // path finding if it has updated values for that channel. In
436
        // particular, it should be set to the current available sending
437
        // bandwidth for active local channels, and 0 for inactive channels.
438
        bandwidthHints bandwidthHints
439
}
440

441
// RestrictParams wraps the set of restrictions passed to findPath that the
442
// found path must adhere to.
443
type RestrictParams struct {
444
        // ProbabilitySource is a callback that is expected to return the
445
        // success probability of traversing the channel from the node.
446
        ProbabilitySource func(route.Vertex, route.Vertex,
447
                lnwire.MilliSatoshi, btcutil.Amount) float64
448

449
        // FeeLimit is a maximum fee amount allowed to be used on the path from
450
        // the source to the target.
451
        FeeLimit lnwire.MilliSatoshi
452

453
        // OutgoingChannelIDs is the list of channels that are allowed for the
454
        // first hop. If nil, any channel may be used.
455
        OutgoingChannelIDs []uint64
456

457
        // LastHop is the pubkey of the last node before the final destination
458
        // is reached. If nil, any node may be used.
459
        LastHop *route.Vertex
460

461
        // CltvLimit is the maximum time lock of the route excluding the final
462
        // ctlv. After path finding is complete, the caller needs to increase
463
        // all cltv expiry heights with the required final cltv delta.
464
        CltvLimit uint32
465

466
        // DestCustomRecords contains the custom records to drop off at the
467
        // final hop, if any.
468
        DestCustomRecords record.CustomSet
469

470
        // DestFeatures is a feature vector describing what the final hop
471
        // supports. If none are provided, pathfinding will try to inspect any
472
        // features on the node announcement instead.
473
        DestFeatures *lnwire.FeatureVector
474

475
        // PaymentAddr is a random 32-byte value generated by the receiver to
476
        // mitigate probing vectors and payment sniping attacks on overpaid
477
        // invoices.
478
        PaymentAddr fn.Option[[32]byte]
479

480
        // Amp signals to the pathfinder that this payment is an AMP payment
481
        // and therefore it needs to account for additional AMP data in the
482
        // final hop payload size calculation.
483
        Amp *AMPOptions
484

485
        // Metadata is additional data that is sent along with the payment to
486
        // the payee.
487
        Metadata []byte
488

489
        // BlindedPaymentPathSet is necessary to determine the hop size of the
490
        // last/exit hop.
491
        BlindedPaymentPathSet *BlindedPaymentPathSet
492

493
        // FirstHopCustomRecords includes any records that should be included in
494
        // the update_add_htlc message towards our peer.
495
        FirstHopCustomRecords lnwire.CustomRecords
496
}
497

498
// PathFindingConfig defines global parameters that control the trade-off in
499
// path finding between fees and probability.
500
type PathFindingConfig struct {
501
        // AttemptCost is the fixed virtual cost in path finding of a failed
502
        // payment attempt. It is used to trade off potentially better routes
503
        // against their probability of succeeding.
504
        AttemptCost lnwire.MilliSatoshi
505

506
        // AttemptCostPPM is the proportional virtual cost in path finding of a
507
        // failed payment attempt. It is used to trade off potentially better
508
        // routes against their probability of succeeding. This parameter is
509
        // expressed in parts per million of the total payment amount.
510
        AttemptCostPPM int64
511

512
        // MinProbability defines the minimum success probability of the
513
        // returned route.
514
        MinProbability float64
515
}
516

517
// getOutgoingBalance returns the maximum available balance in any of the
518
// channels of the given node. The second return parameters is the total
519
// available balance.
520
func getOutgoingBalance(node route.Vertex, outgoingChans map[uint64]struct{},
521
        bandwidthHints bandwidthHints,
522
        g Graph) (lnwire.MilliSatoshi, lnwire.MilliSatoshi, error) {
180✔
523

180✔
524
        var max, total lnwire.MilliSatoshi
180✔
525
        cb := func(channel *graphdb.DirectedChannel) error {
625✔
526
                shortID := lnwire.NewShortChanIDFromInt(channel.ChannelID)
445✔
527

445✔
528
                // This log line is needed to debug issues in case we do not
445✔
529
                // have a channel in our graph for some reason when evaluating
445✔
530
                // the local balance. Otherwise we could not tell whether all
445✔
531
                // channels are being evaluated.
445✔
532
                log.Tracef("Evaluating channel %v for local balance", shortID)
445✔
533

445✔
534
                if !channel.OutPolicySet {
445✔
535
                        log.Debugf("ShortChannelID=%v: has no out policy set, "+
×
536
                                "skipping", shortID)
×
537

×
538
                        return nil
×
539
                }
×
540

541
                chanID := channel.ChannelID
445✔
542

445✔
543
                // Enforce outgoing channel restriction.
445✔
544
                if outgoingChans != nil {
465✔
545
                        if _, ok := outgoingChans[chanID]; !ok {
32✔
546
                                return nil
12✔
547
                        }
12✔
548
                }
549

550
                bandwidth, ok := bandwidthHints.availableChanBandwidth(
433✔
551
                        chanID, 0,
433✔
552
                )
433✔
553

433✔
554
                // If the bandwidth is not available, use the channel capacity.
433✔
555
                // This can happen when a channel is added to the graph after
433✔
556
                // we've already queried the bandwidth hints.
433✔
557
                if !ok {
675✔
558
                        bandwidth = lnwire.NewMSatFromSatoshis(channel.Capacity)
242✔
559

242✔
560
                        log.Warnf("ShortChannelID=%v: not found in the local "+
242✔
561
                                "channels map of the bandwidth manager, "+
242✔
562
                                "using channel capacity=%v as bandwidth for "+
242✔
563
                                "this channel", shortID, bandwidth)
242✔
564
                }
242✔
565

566
                if bandwidth > max {
660✔
567
                        max = bandwidth
227✔
568
                }
227✔
569

570
                var overflow bool
433✔
571
                total, overflow = overflowSafeAdd(total, bandwidth)
433✔
572
                if overflow {
433✔
573
                        log.Warnf("ShortChannelID=%v: overflow detected, "+
×
574
                                "setting total to max value", shortID)
×
575

×
576
                        // If the current total and the bandwidth would
×
577
                        // overflow the maximum value, we set the total to the
×
578
                        // maximum value. Which is more milli-satoshis than are
×
579
                        // in existence anyway, so the actual value is
×
580
                        // irrelevant.
×
581
                        total = lnwire.MilliSatoshi(math.MaxUint64)
×
582
                }
×
583

584
                return nil
433✔
585
        }
586

587
        // Iterate over all channels of the to node.
588
        err := g.ForEachNodeDirectedChannel(
180✔
589
                node, cb, func() {
180✔
UNCOV
590
                        max = 0
×
UNCOV
591
                        total = 0
×
UNCOV
592
                },
×
593
        )
594
        if err != nil {
180✔
595
                return 0, 0, err
×
596
        }
×
597
        return max, total, err
180✔
598
}
599

600
// findPath attempts to find a path from the source node within the ChannelGraph
601
// to the target node that's capable of supporting a payment of `amt` value. The
602
// current approach implemented is modified version of Dijkstra's algorithm to
603
// find a single shortest path between the source node and the destination. The
604
// distance metric used for edges is related to the time-lock+fee costs along a
605
// particular edge. If a path is found, this function returns a slice of
606
// ChannelHop structs which encoded the chosen path from the target to the
607
// source. The search is performed backwards from destination node back to
608
// source. This is to properly accumulate fees that need to be paid along the
609
// path and accurately check the amount to forward at every node against the
610
// available bandwidth.
611
func findPath(g *graphParams, r *RestrictParams, cfg *PathFindingConfig,
612
        self, source, target route.Vertex, amt lnwire.MilliSatoshi,
613
        timePref float64, finalHtlcExpiry int32) ([]*unifiedEdge, float64,
614
        error) {
186✔
615

186✔
616
        // Pathfinding can be a significant portion of the total payment
186✔
617
        // latency, especially on low-powered devices. Log several metrics to
186✔
618
        // aid in the analysis performance problems in this area.
186✔
619
        start := time.Now()
186✔
620
        nodesVisited := 0
186✔
621
        edgesExpanded := 0
186✔
622
        defer func() {
372✔
623
                timeElapsed := time.Since(start)
186✔
624
                log.Debugf("Pathfinding perf metrics: nodes=%v, edges=%v, "+
186✔
625
                        "time=%v", nodesVisited, edgesExpanded, timeElapsed)
186✔
626
        }()
186✔
627

628
        // If no destination features are provided, we will load what features
629
        // we have for the target node from our graph.
630
        features := r.DestFeatures
186✔
631
        if features == nil {
304✔
632
                var err error
118✔
633
                features, err = g.graph.FetchNodeFeatures(target)
118✔
634
                if err != nil {
118✔
635
                        return nil, 0, err
×
636
                }
×
637

638
                // If we cannot find the node in the graph we assume it
639
                // supports the common tlv payload encoding. Otherwise we might
640
                // break some APIs which currently not set the destination
641
                // features.
642
                if features.IsEmpty() {
127✔
643
                        features.Set(lnwire.TLVOnionPayloadOptional)
9✔
644
                }
9✔
645
        }
646

647
        // Ensure that the destination's features don't include unknown
648
        // required features.
649
        err := feature.ValidateRequired(features)
186✔
650
        if err != nil {
188✔
651
                log.Warnf("Pathfinding destination node features: %v", err)
2✔
652
                return nil, 0, errUnknownRequiredFeature
2✔
653
        }
2✔
654

655
        // Ensure that all transitive dependencies are set.
656
        err = feature.ValidateDeps(features)
184✔
657
        if err != nil {
186✔
658
                log.Warnf("Pathfinding destination node features: %v", err)
2✔
659
                return nil, 0, errMissingDependentFeature
2✔
660
        }
2✔
661

662
        // Now that we know the feature vector is well-formed, we'll proceed in
663
        // checking that it supports the features we need. If the caller has a
664
        // payment address to attach, check that our destination feature vector
665
        // supports them.
666
        if r.PaymentAddr.IsSome() &&
182✔
667
                !features.HasFeature(lnwire.PaymentAddrOptional) {
184✔
668

2✔
669
                return nil, 0, errNoPaymentAddr
2✔
670
        }
2✔
671

672
        // Set up outgoing channel map for quicker access.
673
        var outgoingChanMap map[uint64]struct{}
180✔
674
        if len(r.OutgoingChannelIDs) > 0 {
186✔
675
                outgoingChanMap = make(map[uint64]struct{})
6✔
676
                for _, outChan := range r.OutgoingChannelIDs {
14✔
677
                        outgoingChanMap[outChan] = struct{}{}
8✔
678
                }
8✔
679
        }
680

681
        // If we are routing from ourselves, check that we have enough local
682
        // balance available.
683
        if source == self {
360✔
684
                max, total, err := getOutgoingBalance(
180✔
685
                        self, outgoingChanMap, g.bandwidthHints, g.graph,
180✔
686
                )
180✔
687
                if err != nil {
180✔
688
                        return nil, 0, err
×
689
                }
×
690

691
                // If the total outgoing balance isn't sufficient, it will be
692
                // impossible to complete the payment.
693
                if total < amt {
183✔
694
                        log.Warnf("Not enough outbound balance to send "+
3✔
695
                                "htlc of amount: %v, only have local "+
3✔
696
                                "balance: %v", amt, total)
3✔
697

3✔
698
                        return nil, 0, errInsufficientBalance
3✔
699
                }
3✔
700

701
                // If there is only not enough capacity on a single route, it
702
                // may still be possible to complete the payment by splitting.
703
                if max < amt {
178✔
704
                        return nil, 0, errNoPathFound
1✔
705
                }
1✔
706
        }
707

708
        // First we'll initialize an empty heap which'll help us to quickly
709
        // locate the next edge we should visit next during our graph
710
        // traversal.
711
        nodeHeap := newDistanceHeap(estimatedNodeCount)
176✔
712

176✔
713
        // Holds the current best distance for a given node.
176✔
714
        distance := make(map[route.Vertex]*nodeWithDist, estimatedNodeCount)
176✔
715

176✔
716
        additionalEdgesWithSrc := make(map[route.Vertex][]*edgePolicyWithSource)
176✔
717
        for vertex, additionalEdges := range g.additionalEdges {
196✔
718
                // Edges connected to self are always included in the graph,
20✔
719
                // therefore can be skipped. This prevents us from trying
20✔
720
                // routes to malformed hop hints.
20✔
721
                if vertex == self {
24✔
722
                        continue
4✔
723
                }
724

725
                // Build reverse lookup to find incoming edges. Needed because
726
                // search is taken place from target to source.
727
                for _, additionalEdge := range additionalEdges {
32✔
728
                        outgoingEdgePolicy := additionalEdge.EdgePolicy()
16✔
729
                        toVertex := outgoingEdgePolicy.ToNodePubKey()
16✔
730

16✔
731
                        incomingEdgePolicy := &edgePolicyWithSource{
16✔
732
                                sourceNode: vertex,
16✔
733
                                edge:       additionalEdge,
16✔
734
                        }
16✔
735

16✔
736
                        additionalEdgesWithSrc[toVertex] =
16✔
737
                                append(additionalEdgesWithSrc[toVertex],
16✔
738
                                        incomingEdgePolicy)
16✔
739
                }
16✔
740
        }
741

742
        // The payload size of the final hop differ from intermediate hops
743
        // and depends on whether the destination is blinded or not.
744
        lastHopPayloadSize, err := lastHopPayloadSize(r, finalHtlcExpiry, amt)
176✔
745
        if err != nil {
176✔
746
                return nil, 0, err
×
747
        }
×
748

749
        // We can't always assume that the end destination is publicly
750
        // advertised to the network so we'll manually include the target node.
751
        // The target node charges no fee. Distance is set to 0, because this is
752
        // the starting point of the graph traversal. We are searching backwards
753
        // to get the fees first time right and correctly match channel
754
        // bandwidth.
755
        //
756
        // Don't record the initial partial path in the distance map and reserve
757
        // that key for the source key in the case we route to ourselves.
758
        partialPath := &nodeWithDist{
176✔
759
                dist:              0,
176✔
760
                weight:            0,
176✔
761
                node:              target,
176✔
762
                netAmountReceived: amt,
176✔
763
                incomingCltv:      finalHtlcExpiry,
176✔
764
                probability:       1,
176✔
765
                routingInfoSize:   lastHopPayloadSize,
176✔
766
        }
176✔
767

176✔
768
        // Calculate the absolute cltv limit. Use uint64 to prevent an overflow
176✔
769
        // if the cltv limit is MaxUint32.
176✔
770
        absoluteCltvLimit := uint64(r.CltvLimit) + uint64(finalHtlcExpiry)
176✔
771

176✔
772
        // Calculate the default attempt cost as configured globally.
176✔
773
        defaultAttemptCost := float64(
176✔
774
                cfg.AttemptCost +
176✔
775
                        amt*lnwire.MilliSatoshi(cfg.AttemptCostPPM)/1000000,
176✔
776
        )
176✔
777

176✔
778
        // Validate time preference value.
176✔
779
        if math.Abs(timePref) > 1 {
176✔
780
                return nil, 0, fmt.Errorf("time preference %v out of range "+
×
781
                        "[-1, 1]", timePref)
×
782
        }
×
783

784
        // Scale to avoid the extremes -1 and 1 which run into infinity issues.
785
        timePref *= 0.9
176✔
786

176✔
787
        // Apply time preference. At 0, the default attempt cost will
176✔
788
        // be used.
176✔
789
        absoluteAttemptCost := defaultAttemptCost * (1/(0.5-timePref/2) - 1)
176✔
790

176✔
791
        log.Debugf("Pathfinding absolute attempt cost: %v sats",
176✔
792
                absoluteAttemptCost/1000)
176✔
793

176✔
794
        // processEdge is a helper closure that will be used to make sure edges
176✔
795
        // satisfy our specific requirements.
176✔
796
        processEdge := func(fromVertex route.Vertex,
176✔
797
                edge *unifiedEdge, toNodeDist *nodeWithDist) {
1,428✔
798

1,252✔
799
                edgesExpanded++
1,252✔
800

1,252✔
801
                // Calculate inbound fee charged by "to" node. The exit hop
1,252✔
802
                // doesn't charge inbound fees. If the "to" node is the exit
1,252✔
803
                // hop, its inbound fees have already been set to zero by
1,252✔
804
                // nodeEdgeUnifier.
1,252✔
805
                inboundFee := edge.inboundFees.CalcFee(
1,252✔
806
                        toNodeDist.netAmountReceived,
1,252✔
807
                )
1,252✔
808

1,252✔
809
                // Make sure that the node total fee is never negative.
1,252✔
810
                // Routing nodes treat a total fee that turns out
1,252✔
811
                // negative as a zero fee and pathfinding should do the
1,252✔
812
                // same.
1,252✔
813
                minInboundFee := -int64(toNodeDist.outboundFee)
1,252✔
814
                if inboundFee < minInboundFee {
1,254✔
815
                        inboundFee = minInboundFee
2✔
816
                }
2✔
817

818
                // Calculate amount that the candidate node would have to send
819
                // out.
820
                amountToSend := toNodeDist.netAmountReceived +
1,252✔
821
                        lnwire.MilliSatoshi(inboundFee)
1,252✔
822

1,252✔
823
                // Check if accumulated fees would exceed fee limit when this
1,252✔
824
                // node would be added to the path.
1,252✔
825
                totalFee := int64(amountToSend) - int64(amt)
1,252✔
826

1,252✔
827
                log.Trace(lnutils.NewLogClosure(func() string {
1,252✔
828
                        return fmt.Sprintf(
×
829
                                "Checking fromVertex (%v) with "+
×
830
                                        "minInboundFee=%v, inboundFee=%v, "+
×
831
                                        "amountToSend=%v, amt=%v, totalFee=%v",
×
832
                                fromVertex, minInboundFee, inboundFee,
×
833
                                amountToSend, amt, totalFee,
×
834
                        )
×
835
                }))
×
836

837
                if totalFee > 0 && lnwire.MilliSatoshi(totalFee) > r.FeeLimit {
1,256✔
838
                        return
4✔
839
                }
4✔
840

841
                // Request the success probability for this edge.
842
                edgeProbability := r.ProbabilitySource(
1,248✔
843
                        fromVertex, toNodeDist.node, amountToSend,
1,248✔
844
                        edge.capacity,
1,248✔
845
                )
1,248✔
846

1,248✔
847
                log.Trace(lnutils.NewLogClosure(func() string {
1,248✔
848
                        return fmt.Sprintf("path finding probability: fromnode=%v,"+
×
849
                                " tonode=%v, amt=%v, cap=%v, probability=%v",
×
850
                                fromVertex, toNodeDist.node, amountToSend,
×
851
                                edge.capacity, edgeProbability)
×
852
                }))
×
853

854
                // If the probability is zero, there is no point in trying.
855
                if edgeProbability == 0 {
1,248✔
856
                        return
×
857
                }
×
858

859
                // Compute fee that fromVertex is charging. It is based on the
860
                // amount that needs to be sent to the next node in the route.
861
                //
862
                // Source node has no predecessor to pay a fee. Therefore set
863
                // fee to zero, because it should not be included in the fee
864
                // limit check and edge weight.
865
                //
866
                // Also determine the time lock delta that will be added to the
867
                // route if fromVertex is selected. If fromVertex is the source
868
                // node, no additional timelock is required.
869
                var (
1,248✔
870
                        timeLockDelta uint16
1,248✔
871
                        outboundFee   int64
1,248✔
872
                )
1,248✔
873

1,248✔
874
                if fromVertex != source {
2,352✔
875
                        outboundFee = int64(
1,104✔
876
                                edge.policy.ComputeFee(amountToSend),
1,104✔
877
                        )
1,104✔
878
                        timeLockDelta = edge.policy.TimeLockDelta
1,104✔
879
                }
1,104✔
880

881
                incomingCltv := toNodeDist.incomingCltv + int32(timeLockDelta)
1,248✔
882

1,248✔
883
                // Check that we are within our CLTV limit.
1,248✔
884
                if uint64(incomingCltv) > absoluteCltvLimit {
1,260✔
885
                        return
12✔
886
                }
12✔
887

888
                // netAmountToReceive is the amount that the node that is added
889
                // to the distance map needs to receive from a (to be found)
890
                // previous node in the route. The inbound fee of the receiving
891
                // node is already subtracted from this value. The previous node
892
                // will need to pay the amount that this node forwards plus the
893
                // fee it charges plus this node's inbound fee.
894
                netAmountToReceive := amountToSend +
1,236✔
895
                        lnwire.MilliSatoshi(outboundFee)
1,236✔
896

1,236✔
897
                // Calculate total probability of successfully reaching target
1,236✔
898
                // by multiplying the probabilities. Both this edge and the rest
1,236✔
899
                // of the route must succeed.
1,236✔
900
                probability := toNodeDist.probability * edgeProbability
1,236✔
901

1,236✔
902
                // If the probability is below the specified lower bound, we can
1,236✔
903
                // abandon this direction. Adding further nodes can only lower
1,236✔
904
                // the probability more.
1,236✔
905
                if probability < cfg.MinProbability {
1,337✔
906
                        return
101✔
907
                }
101✔
908

909
                // Calculate the combined fee for this edge. Dijkstra does not
910
                // support negative edge weights. Because this fee feeds into
911
                // the edge weight calculation, we don't allow it to be
912
                // negative.
913
                signedFee := inboundFee + outboundFee
1,135✔
914
                fee := lnwire.MilliSatoshi(0)
1,135✔
915
                if signedFee > 0 {
1,693✔
916
                        fee = lnwire.MilliSatoshi(signedFee)
558✔
917
                }
558✔
918

919
                // By adding fromVertex in the route, there will be an extra
920
                // weight composed of the fee that this node will charge and
921
                // the amount that will be locked for timeLockDelta blocks in
922
                // the HTLC that is handed out to fromVertex.
923
                weight := edgeWeight(amountToSend, fee, timeLockDelta)
1,135✔
924

1,135✔
925
                // Compute the tentative weight to this new channel/edge
1,135✔
926
                // which is the weight from our toNode to the target node
1,135✔
927
                // plus the weight of this edge.
1,135✔
928
                tempWeight := toNodeDist.weight + weight
1,135✔
929

1,135✔
930
                // Add an extra factor to the weight to take into account the
1,135✔
931
                // probability. Another reason why we rounded the fee up to zero
1,135✔
932
                // is to prevent a highly negative fee from cancelling out the
1,135✔
933
                // extra factor. We don't want an always-failing node to attract
1,135✔
934
                // traffic using a highly negative fee and escape penalization.
1,135✔
935
                tempDist := getProbabilityBasedDist(
1,135✔
936
                        tempWeight, probability,
1,135✔
937
                        absoluteAttemptCost,
1,135✔
938
                )
1,135✔
939

1,135✔
940
                // If there is already a best route stored, compare this
1,135✔
941
                // candidate route with the best route so far.
1,135✔
942
                current, ok := distance[fromVertex]
1,135✔
943
                if ok {
1,530✔
944
                        // If this route is worse than what we already found,
395✔
945
                        // skip this route.
395✔
946
                        if tempDist > current.dist {
700✔
947
                                return
305✔
948
                        }
305✔
949

950
                        // If the route is equally good and the probability
951
                        // isn't better, skip this route. It is important to
952
                        // also return if both cost and probability are equal,
953
                        // because otherwise the algorithm could run into an
954
                        // endless loop.
955
                        probNotBetter := probability <= current.probability
90✔
956
                        if tempDist == current.dist && probNotBetter {
149✔
957
                                return
59✔
958
                        }
59✔
959
                }
960

961
                // Calculate the total routing info size if this hop were to be
962
                // included. If we are coming from the source hop, the payload
963
                // size is zero, because the original htlc isn't in the onion
964
                // blob.
965
                //
966
                // NOTE: For blinded paths with the NUMS key as the last hop,
967
                // the payload size accounts for this dummy hop which is of
968
                // the same size as the real last hop. So we account for a
969
                // bigger size than the route is however we accept this
970
                // little inaccuracy here because we are over estimating by
971
                // 1 hop.
972
                var payloadSize uint64
771✔
973
                if fromVertex != source {
1,402✔
974
                        // In case the unifiedEdge does not have a payload size
631✔
975
                        // function supplied we request a graceful shutdown
631✔
976
                        // because this should never happen.
631✔
977
                        if edge.hopPayloadSizeFn == nil {
631✔
978
                                log.Criticalf("No payload size function "+
×
979
                                        "available for edge=%v unable to "+
×
980
                                        "determine payload size: %v", edge,
×
981
                                        ErrNoPayLoadSizeFunc)
×
982

×
983
                                return
×
984
                        }
×
985

986
                        payloadSize = edge.hopPayloadSizeFn(
631✔
987
                                amountToSend,
631✔
988
                                uint32(toNodeDist.incomingCltv),
631✔
989
                                edge.policy.ChannelID,
631✔
990
                        )
631✔
991
                }
992

993
                routingInfoSize := toNodeDist.routingInfoSize + payloadSize
771✔
994
                // Skip paths that would exceed the maximum routing info size.
771✔
995
                if routingInfoSize > sphinx.MaxPayloadSize {
777✔
996
                        return
6✔
997
                }
6✔
998

999
                // All conditions are met and this new tentative distance is
1000
                // better than the current best known distance to this node.
1001
                // The new better distance is recorded, and also our "next hop"
1002
                // map is populated with this edge.
1003
                withDist := &nodeWithDist{
765✔
1004
                        dist:              tempDist,
765✔
1005
                        weight:            tempWeight,
765✔
1006
                        node:              fromVertex,
765✔
1007
                        netAmountReceived: netAmountToReceive,
765✔
1008
                        outboundFee:       lnwire.MilliSatoshi(outboundFee),
765✔
1009
                        incomingCltv:      incomingCltv,
765✔
1010
                        probability:       probability,
765✔
1011
                        nextHop:           edge,
765✔
1012
                        routingInfoSize:   routingInfoSize,
765✔
1013
                }
765✔
1014
                distance[fromVertex] = withDist
765✔
1015

765✔
1016
                // Either push withDist onto the heap if the node
765✔
1017
                // represented by fromVertex is not already on the heap OR adjust
765✔
1018
                // its position within the heap via heap.Fix.
765✔
1019
                nodeHeap.PushOrFix(withDist)
765✔
1020
        }
1021

1022
        // TODO(roasbeef): also add path caching
1023
        //  * similar to route caching, but doesn't factor in the amount
1024

1025
        // Cache features because we visit nodes multiple times.
1026
        featureCache := make(map[route.Vertex]*lnwire.FeatureVector)
176✔
1027

176✔
1028
        // getGraphFeatures returns (cached) node features from the graph.
176✔
1029
        getGraphFeatures := func(node route.Vertex) (*lnwire.FeatureVector,
176✔
1030
                error) {
1,432✔
1031

1,256✔
1032
                // Check cache for features of the fromNode.
1,256✔
1033
                fromFeatures, ok := featureCache[node]
1,256✔
1034
                if ok {
1,719✔
1035
                        return fromFeatures, nil
463✔
1036
                }
463✔
1037

1038
                // Fetch node features fresh from the graph.
1039
                fromFeatures, err := g.graph.FetchNodeFeatures(node)
793✔
1040
                if err != nil {
793✔
1041
                        return nil, err
×
1042
                }
×
1043

1044
                // Don't route through nodes that contain unknown required
1045
                // features and mark as nil in the cache.
1046
                err = feature.ValidateRequired(fromFeatures)
793✔
1047
                if err != nil {
795✔
1048
                        featureCache[node] = nil
2✔
1049
                        return nil, nil
2✔
1050
                }
2✔
1051

1052
                // Don't route through nodes that don't properly set all
1053
                // transitive feature dependencies and mark as nil in the cache.
1054
                err = feature.ValidateDeps(fromFeatures)
791✔
1055
                if err != nil {
793✔
1056
                        featureCache[node] = nil
2✔
1057
                        return nil, nil
2✔
1058
                }
2✔
1059

1060
                // Update cache.
1061
                featureCache[node] = fromFeatures
789✔
1062

789✔
1063
                return fromFeatures, nil
789✔
1064
        }
1065

1066
        routeToSelf := source == target
176✔
1067
        for {
872✔
1068
                nodesVisited++
696✔
1069

696✔
1070
                pivot := partialPath.node
696✔
1071
                isExitHop := partialPath.nextHop == nil
696✔
1072

696✔
1073
                // Create unified policies for all incoming connections. Don't
696✔
1074
                // use inbound fees for the exit hop.
696✔
1075
                u := newNodeEdgeUnifier(
696✔
1076
                        self, pivot, !isExitHop, outgoingChanMap,
696✔
1077
                )
696✔
1078

696✔
1079
                err := u.addGraphPolicies(g.graph)
696✔
1080
                if err != nil {
696✔
1081
                        return nil, 0, err
×
1082
                }
×
1083

1084
                // We add hop hints that were supplied externally.
1085
                for _, reverseEdge := range additionalEdgesWithSrc[pivot] {
712✔
1086
                        // Assume zero inbound fees for route hints. If inbound
16✔
1087
                        // fees would apply, they couldn't be communicated in
16✔
1088
                        // bolt11 invoices currently.
16✔
1089
                        inboundFee := models.InboundFee{}
16✔
1090

16✔
1091
                        // Hop hints don't contain a capacity. We set one here,
16✔
1092
                        // since a capacity is needed for probability
16✔
1093
                        // calculations. We set a high capacity to act as if
16✔
1094
                        // there is enough liquidity, otherwise the hint would
16✔
1095
                        // not have been added by a wallet.
16✔
1096
                        // We also pass the payload size function to the
16✔
1097
                        // graph data so that we calculate the exact payload
16✔
1098
                        // size when evaluating this hop for a route.
16✔
1099
                        u.addPolicy(
16✔
1100
                                reverseEdge.sourceNode,
16✔
1101
                                reverseEdge.edge.EdgePolicy(),
16✔
1102
                                inboundFee,
16✔
1103
                                fakeHopHintCapacity,
16✔
1104
                                reverseEdge.edge.IntermediatePayloadSize,
16✔
1105
                                reverseEdge.edge.BlindedPayment(),
16✔
1106
                        )
16✔
1107
                }
16✔
1108

1109
                netAmountReceived := partialPath.netAmountReceived
696✔
1110

696✔
1111
                // Expand all connections using the optimal policy for each
696✔
1112
                // connection.
696✔
1113
                for fromNode, edgeUnifier := range u.edgeUnifiers {
2,316✔
1114
                        // The target node is not recorded in the distance map.
1,620✔
1115
                        // Therefore we need to have this check to prevent
1,620✔
1116
                        // creating a cycle. Only when we intend to route to
1,620✔
1117
                        // self, we allow this cycle to form. In that case we'll
1,620✔
1118
                        // also break out of the search loop below.
1,620✔
1119
                        if !routeToSelf && fromNode == target {
1,950✔
1120
                                continue
330✔
1121
                        }
1122

1123
                        // Apply last hop restriction if set.
1124
                        if r.LastHop != nil &&
1,290✔
1125
                                pivot == target && fromNode != *r.LastHop {
1,294✔
1126

4✔
1127
                                continue
4✔
1128
                        }
1129

1130
                        edge := edgeUnifier.getEdge(
1,286✔
1131
                                netAmountReceived, g.bandwidthHints,
1,286✔
1132
                                partialPath.outboundFee,
1,286✔
1133
                        )
1,286✔
1134

1,286✔
1135
                        if edge == nil {
1,316✔
1136
                                continue
30✔
1137
                        }
1138

1139
                        // Get feature vector for fromNode.
1140
                        fromFeatures, err := getGraphFeatures(fromNode)
1,256✔
1141
                        if err != nil {
1,256✔
1142
                                return nil, 0, err
×
1143
                        }
×
1144

1145
                        // If there are no valid features, skip this node.
1146
                        if fromFeatures == nil {
1,260✔
1147
                                continue
4✔
1148
                        }
1149

1150
                        // Check if this candidate node is better than what we
1151
                        // already have.
1152
                        processEdge(fromNode, edge, partialPath)
1,252✔
1153
                }
1154

1155
                if nodeHeap.Len() == 0 {
736✔
1156
                        break
40✔
1157
                }
1158

1159
                // Fetch the node within the smallest distance from our source
1160
                // from the heap.
1161
                partialPath = heap.Pop(&nodeHeap).(*nodeWithDist)
656✔
1162

656✔
1163
                // If we've reached our source (or we don't have any incoming
656✔
1164
                // edges), then we're done here and can exit the graph
656✔
1165
                // traversal early.
656✔
1166
                if partialPath.node == source {
792✔
1167
                        break
136✔
1168
                }
1169
        }
1170

1171
        // Use the distance map to unravel the forward path from source to
1172
        // target.
1173
        var pathEdges []*unifiedEdge
176✔
1174
        currentNode := source
176✔
1175
        for {
556✔
1176
                // Determine the next hop forward using the next map.
380✔
1177
                currentNodeWithDist, ok := distance[currentNode]
380✔
1178
                if !ok {
420✔
1179
                        // If the node doesn't have a next hop it means we
40✔
1180
                        // didn't find a path.
40✔
1181
                        return nil, 0, errNoPathFound
40✔
1182
                }
40✔
1183

1184
                // Add the next hop to the list of path edges.
1185
                pathEdges = append(pathEdges, currentNodeWithDist.nextHop)
340✔
1186

340✔
1187
                // Advance current node.
340✔
1188
                currentNode = currentNodeWithDist.nextHop.policy.ToNodePubKey()
340✔
1189

340✔
1190
                // Check stop condition at the end of this loop. This prevents
340✔
1191
                // breaking out too soon for self-payments that have target set
340✔
1192
                // to source.
340✔
1193
                if currentNode == target {
476✔
1194
                        break
136✔
1195
                }
1196
        }
1197

1198
        // For the final hop, we'll set the node features to those determined
1199
        // above. These are either taken from the destination features, e.g.
1200
        // virtual or invoice features, or loaded as a fallback from the graph.
1201
        // The transitive dependencies were already validated above, so no need
1202
        // to do so now.
1203
        //
1204
        // NOTE: This may overwrite features loaded from the graph if
1205
        // destination features were provided. This is fine though, since our
1206
        // route construction does not care where the features are actually
1207
        // taken from. In the future we may wish to do route construction within
1208
        // findPath, and avoid using ChannelEdgePolicy altogether.
1209
        pathEdges[len(pathEdges)-1].policy.ToNodeFeatures = features
136✔
1210

136✔
1211
        log.Debugf("Found route: probability=%v, hops=%v, fee=%v",
136✔
1212
                distance[source].probability, len(pathEdges),
136✔
1213
                distance[source].netAmountReceived-amt)
136✔
1214

136✔
1215
        return pathEdges, distance[source].probability, nil
136✔
1216
}
1217

1218
// blindedPathRestrictions are a set of constraints to adhere to when
1219
// choosing a set of blinded paths to this node.
1220
type blindedPathRestrictions struct {
1221
        // minNumHops is the minimum number of hops to include in a blinded
1222
        // path. This doesn't include our node, so if the minimum is 1, then
1223
        // the path will contain at minimum our node along with an introduction
1224
        // node hop. A minimum of 0 will include paths where this node is the
1225
        // introduction node and so should be used with caution.
1226
        minNumHops uint8
1227

1228
        // maxNumHops is the maximum number of hops to include in a blinded
1229
        // path. This doesn't include our node, so if the maximum is 1, then
1230
        // the path will contain our node along with an introduction node hop.
1231
        maxNumHops uint8
1232

1233
        // nodeOmissionSet holds a set of node IDs of nodes that we should
1234
        // ignore during blinded path selection.
1235
        nodeOmissionSet fn.Set[route.Vertex]
1236

1237
        // incomingChainedChannels holds the chained channels list specified
1238
        // via scid (short channel id) starting from a channel which points to
1239
        // the receiver node.
1240
        incomingChainedChannels []uint64
1241
}
1242

1243
// blindedHop holds the information about a hop we have selected for a blinded
1244
// path.
1245
type blindedHop struct {
1246
        vertex       route.Vertex
1247
        channelID    uint64
1248
        edgeCapacity btcutil.Amount
1249
}
1250

1251
// findBlindedPaths does a depth first search from the target node to find a set
1252
// of blinded paths to the target node given the set of restrictions. This
1253
// function will select and return any candidate path. A candidate path is a
1254
// path to the target node with a size determined by the given hop number
1255
// constraints where all the nodes on the path signal the route blinding feature
1256
// _and_ the introduction node for the path has more than one public channel.
1257
// Any filtering of paths based on payment value or success probabilities is
1258
// left to the caller.
1259
func findBlindedPaths(g Graph, target route.Vertex,
1260
        restrictions *blindedPathRestrictions) ([][]blindedHop, error) {
19✔
1261

19✔
1262
        // Sanity check the restrictions.
19✔
1263
        if restrictions.minNumHops > restrictions.maxNumHops {
19✔
1264
                return nil, fmt.Errorf("maximum number of blinded path hops "+
×
1265
                        "(%d) must be greater than or equal to the minimum "+
×
1266
                        "number of hops (%d)", restrictions.maxNumHops,
×
1267
                        restrictions.minNumHops)
×
1268
        }
×
1269

1270
        var (
19✔
1271
                // The target node is always the last hop in the path, and so
19✔
1272
                // we add it to the incoming path from the get-go. Any additions
19✔
1273
                // to the slice should be prepended.
19✔
1274
                incomingPath = []blindedHop{{
19✔
1275
                        vertex: target,
19✔
1276
                }}
19✔
1277

19✔
1278
                // supportsRouteBlinding is a list of nodes that we can assume
19✔
1279
                // support route blinding without needing to rely on the feature
19✔
1280
                // bits announced in their node announcement. Since we are
19✔
1281
                // finding a path to the target node, we can assume it supports
19✔
1282
                // route blinding.
19✔
1283
                supportsRouteBlinding = map[route.Vertex]bool{
19✔
1284
                        target: true,
19✔
1285
                }
19✔
1286

19✔
1287
                visited          = make(map[route.Vertex]bool)
19✔
1288
                nextTarget       = target
19✔
1289
                haveIncomingPath = len(restrictions.incomingChainedChannels) > 0
19✔
1290

19✔
1291
                // errChanFound is an error variable we return from the DB
19✔
1292
                // iteration call below when we have found the channel we are
19✔
1293
                // looking for. This lets us exit the iteration early.
19✔
1294
                errChanFound = errors.New("found incoming channel")
19✔
1295
        )
19✔
1296
        for _, chanID := range restrictions.incomingChainedChannels {
30✔
1297
                // Mark that we have visited this node so that we don't revisit
11✔
1298
                // it later on when we call "processNodeForBlindedPath".
11✔
1299
                visited[nextTarget] = true
11✔
1300

11✔
1301
                var (
11✔
1302
                        incomingPathReset []blindedHop
11✔
1303
                        nextTargetReset   = nextTarget
11✔
1304
                )
11✔
1305
                err := g.ForEachNodeDirectedChannel(
11✔
1306
                        nextTarget,
11✔
1307
                        func(channel *graphdb.DirectedChannel) error {
31✔
1308
                                // This is not the right channel, continue to
20✔
1309
                                // the node's other channels.
20✔
1310
                                if channel.ChannelID != chanID {
29✔
1311
                                        return nil
9✔
1312
                                }
9✔
1313

1314
                                // We found the channel in question. Prepend it
1315
                                // to the incoming path.
1316
                                incomingPathReset = append([]blindedHop{
11✔
1317
                                        {
11✔
1318
                                                vertex:       channel.OtherNode,
11✔
1319
                                                channelID:    channel.ChannelID,
11✔
1320
                                                edgeCapacity: channel.Capacity,
11✔
1321
                                        },
11✔
1322
                                }, incomingPathReset...)
11✔
1323

11✔
1324
                                // Update the target node.
11✔
1325
                                nextTargetReset = channel.OtherNode
11✔
1326

11✔
1327
                                return errChanFound
11✔
1328
                        }, func() {
×
1329
                                incomingPathReset = nil
×
1330
                                nextTargetReset = nextTarget
×
1331
                        },
×
1332
                )
1333
                // We expect errChanFound to be returned if the channel in
1334
                // question was found.
1335
                if !errors.Is(err, errChanFound) && err != nil {
11✔
1336
                        return nil, err
×
1337
                } else if err == nil {
11✔
UNCOV
1338
                        return nil, fmt.Errorf("incoming channel %d is not "+
×
UNCOV
1339
                                "seen as owned by node %v", chanID, nextTarget)
×
UNCOV
1340
                }
×
1341
                nextTarget = nextTargetReset
11✔
1342
                incomingPath = append(incomingPathReset, incomingPath...)
11✔
1343

11✔
1344
                // Check that the user didn't accidentally add a channel that
11✔
1345
                // is owned by a node in the node omission set.
11✔
1346
                if restrictions.nodeOmissionSet.Contains(nextTarget) {
12✔
1347
                        return nil, fmt.Errorf("node %v cannot simultaneously "+
1✔
1348
                                "be included in the omission set and in the "+
1✔
1349
                                "partially specified path", nextTarget)
1✔
1350
                }
1✔
1351

1352
                // Check that we have not already visited the next target node
1353
                // since this would mean a circular incoming path.
1354
                if visited[nextTarget] {
11✔
1355
                        return nil, fmt.Errorf("a circular route cannot be " +
1✔
1356
                                "specified for the incoming blinded path")
1✔
1357
                }
1✔
1358

1359
                supportsRouteBlinding[nextTarget] = true
9✔
1360
        }
1361

1362
        // A helper closure which checks if the node in question has advertised
1363
        // that it supports route blinding.
1364
        nodeSupportsRouteBlinding := func(node route.Vertex) (bool, error) {
103✔
1365
                if supportsRouteBlinding[node] {
103✔
1366
                        return true, nil
17✔
1367
                }
17✔
1368

1369
                features, err := g.FetchNodeFeatures(node)
69✔
1370
                if err != nil {
69✔
1371
                        return false, err
×
1372
                }
×
1373

1374
                return features.HasFeature(lnwire.RouteBlindingOptional), nil
69✔
1375
        }
1376

1377
        // This function will have some recursion. We will spin out from the
1378
        // target node & append edges to the paths until we reach various exit
1379
        // conditions such as: The maxHops number being reached or reaching
1380
        // a node that doesn't have any other edges - in that final case, the
1381
        // whole path should be ignored.
1382
        //
1383
        // NOTE: any paths returned will end at the "nextTarget" node meaning
1384
        // that if we have a fixed list of incoming chained channels, then this
1385
        // fixed list must be appended to any of the returned paths.
1386
        paths, _, err := processNodeForBlindedPath(
17✔
1387
                g, nextTarget, nodeSupportsRouteBlinding, visited, restrictions,
17✔
1388
        )
17✔
1389
        if err != nil {
17✔
1390
                return nil, err
×
1391
        }
×
1392

1393
        // Reverse each path so that the order is correct (from introduction
1394
        // node to last hop node) and then append the incoming path (if any was
1395
        // specified) to the end of the path.
1396
        orderedPaths := make([][]blindedHop, 0, len(paths))
17✔
1397
        for _, path := range paths {
56✔
1398
                sort.Slice(path, func(i, j int) bool {
75✔
1399
                        return j < i
36✔
1400
                })
36✔
1401

1402
                orderedPaths = append(
39✔
1403
                        orderedPaths, append(path, incomingPath...),
39✔
1404
                )
39✔
1405
        }
1406

1407
        // There is a chance we have an incoming path that by itself satisfies
1408
        // the minimum hop restriction. In that case, we add it as its own path.
1409
        if haveIncomingPath &&
17✔
1410
                len(incomingPath) > int(restrictions.minNumHops) {
22✔
1411

5✔
1412
                orderedPaths = append(orderedPaths, incomingPath)
5✔
1413
        }
5✔
1414

1415
        // Handle the special case that allows a blinded path with the
1416
        // introduction node as the destination node. This only applies if no
1417
        // incoming path was specified since in that case, by definition, the
1418
        // caller wants a non-zero length blinded path.
1419
        if restrictions.minNumHops == 0 && !haveIncomingPath {
19✔
1420
                singleHopPath := [][]blindedHop{{{vertex: target}}}
2✔
1421

2✔
1422
                orderedPaths = append(
2✔
1423
                        orderedPaths, singleHopPath...,
2✔
1424
                )
2✔
1425
        }
2✔
1426

1427
        return orderedPaths, err
17✔
1428
}
1429

1430
// processNodeForBlindedPath is a recursive function that traverses the graph
1431
// in a depth first manner searching for a set of blinded paths to the given
1432
// node.
1433
func processNodeForBlindedPath(g Graph, node route.Vertex,
1434
        supportsRouteBlinding func(vertex route.Vertex) (bool, error),
1435
        alreadyVisited map[route.Vertex]bool,
1436
        restrictions *blindedPathRestrictions) ([][]blindedHop, bool, error) {
234✔
1437

234✔
1438
        // If we have already visited the maximum number of hops, then this path
234✔
1439
        // is complete and we can exit now.
234✔
1440
        if len(alreadyVisited) > int(restrictions.maxNumHops) {
339✔
1441
                return nil, false, nil
105✔
1442
        }
105✔
1443

1444
        // If we have already visited this peer on this path, then we skip
1445
        // processing it again.
1446
        if alreadyVisited[node] {
168✔
1447
                return nil, false, nil
39✔
1448
        }
39✔
1449

1450
        // If we have explicitly been told to ignore this node for blinded paths
1451
        // then we skip it too.
1452
        if restrictions.nodeOmissionSet.Contains(node) {
94✔
1453
                return nil, false, nil
4✔
1454
        }
4✔
1455

1456
        supports, err := supportsRouteBlinding(node)
86✔
1457
        if err != nil {
86✔
1458
                return nil, false, err
×
1459
        }
×
1460
        if !supports {
92✔
1461
                return nil, false, nil
6✔
1462
        }
6✔
1463

1464
        // At this point, copy the alreadyVisited map.
1465
        visited := make(map[route.Vertex]bool, len(alreadyVisited))
80✔
1466
        for r := range alreadyVisited {
192✔
1467
                visited[r] = true
112✔
1468
        }
112✔
1469

1470
        // Add this node the visited set.
1471
        visited[node] = true
80✔
1472

80✔
1473
        var (
80✔
1474
                hopSets   [][]blindedHop
80✔
1475
                chanCount int
80✔
1476
        )
80✔
1477

80✔
1478
        // Now, iterate over the node's channels in search for paths to this
80✔
1479
        // node that can be used for blinded paths
80✔
1480
        err = g.ForEachNodeDirectedChannel(
80✔
1481
                node,
80✔
1482
                func(channel *graphdb.DirectedChannel) error {
297✔
1483
                        // Keep track of how many incoming channels this node
217✔
1484
                        // has. We only use a node as an introduction node if it
217✔
1485
                        // has channels other than the one that lead us to it.
217✔
1486
                        chanCount++
217✔
1487

217✔
1488
                        // Process each channel peer to gather any paths that
217✔
1489
                        // lead to the peer.
217✔
1490
                        nextPaths, hasMoreChans, err := processNodeForBlindedPath( //nolint:ll
217✔
1491
                                g, channel.OtherNode, supportsRouteBlinding,
217✔
1492
                                visited, restrictions,
217✔
1493
                        )
217✔
1494
                        if err != nil {
217✔
1495
                                return err
×
1496
                        }
×
1497

1498
                        hop := blindedHop{
217✔
1499
                                vertex:       channel.OtherNode,
217✔
1500
                                channelID:    channel.ChannelID,
217✔
1501
                                edgeCapacity: channel.Capacity,
217✔
1502
                        }
217✔
1503

217✔
1504
                        // For each of the paths returned, unwrap them and
217✔
1505
                        // append this hop to them.
217✔
1506
                        for _, path := range nextPaths {
250✔
1507
                                hopSets = append(
33✔
1508
                                        hopSets,
33✔
1509
                                        append([]blindedHop{hop}, path...),
33✔
1510
                                )
33✔
1511
                        }
33✔
1512

1513
                        // If this node does have channels other than the one
1514
                        // that lead to it, and if the hop count up to this node
1515
                        // meets the minHop requirement, then we also add a
1516
                        // path that starts at this node.
1517
                        if hasMoreChans &&
217✔
1518
                                len(visited) >= int(restrictions.minNumHops) {
256✔
1519

39✔
1520
                                hopSets = append(hopSets, []blindedHop{hop})
39✔
1521
                        }
39✔
1522

1523
                        return nil
217✔
1524
                }, func() {
×
1525
                        hopSets = nil
×
1526
                        chanCount = 0
×
1527
                },
×
1528
        )
1529
        if err != nil {
80✔
1530
                return nil, false, err
×
1531
        }
×
1532

1533
        return hopSets, chanCount > 1, nil
80✔
1534
}
1535

1536
// getProbabilityBasedDist converts a weight into a distance that takes into
1537
// account the success probability and the (virtual) cost of a failed payment
1538
// attempt.
1539
//
1540
// Derivation:
1541
//
1542
// Suppose there are two routes A and B with fees Fa and Fb and success
1543
// probabilities Pa and Pb.
1544
//
1545
// Is the expected cost of trying route A first and then B lower than trying the
1546
// other way around?
1547
//
1548
// The expected cost of A-then-B is: Pa*Fa + (1-Pa)*Pb*(c+Fb)
1549
//
1550
// The expected cost of B-then-A is: Pb*Fb + (1-Pb)*Pa*(c+Fa)
1551
//
1552
// In these equations, the term representing the case where both A and B fail is
1553
// left out because its value would be the same in both cases.
1554
//
1555
// Pa*Fa + (1-Pa)*Pb*(c+Fb) < Pb*Fb + (1-Pb)*Pa*(c+Fa)
1556
//
1557
// Pa*Fa + Pb*c + Pb*Fb - Pa*Pb*c - Pa*Pb*Fb < Pb*Fb + Pa*c + Pa*Fa - Pa*Pb*c - Pa*Pb*Fa
1558
//
1559
// Removing terms that cancel out:
1560
// Pb*c - Pa*Pb*Fb < Pa*c - Pa*Pb*Fa
1561
//
1562
// Divide by Pa*Pb:
1563
// c/Pa - Fb < c/Pb - Fa
1564
//
1565
// Move terms around:
1566
// Fa + c/Pa < Fb + c/Pb
1567
//
1568
// So the value of F + c/P can be used to compare routes.
1569
func getProbabilityBasedDist(weight int64, probability float64,
1570
        penalty float64) int64 {
1,135✔
1571

1,135✔
1572
        // Prevent divide by zero by returning early.
1,135✔
1573
        if probability == 0 {
1,135✔
1574
                return infinity
×
1575
        }
×
1576

1577
        // Calculate distance.
1578
        dist := float64(weight) + penalty/probability
1,135✔
1579

1,135✔
1580
        // Avoid cast if an overflow would occur. The maxFloat constant is
1,135✔
1581
        // chosen to stay well below the maximum float64 value that is still
1,135✔
1582
        // convertible to int64.
1,135✔
1583
        const maxFloat = 9000000000000000000
1,135✔
1584
        if dist > maxFloat {
1,135✔
1585
                return infinity
×
1586
        }
×
1587

1588
        return int64(dist)
1,135✔
1589
}
1590

1591
// lastHopPayloadSize calculates the payload size of the final hop in a route.
1592
// It depends on the tlv types which are present and also whether the hop is
1593
// part of a blinded route or not.
1594
func lastHopPayloadSize(r *RestrictParams, finalHtlcExpiry int32,
1595
        amount lnwire.MilliSatoshi) (uint64, error) {
179✔
1596

179✔
1597
        if r.BlindedPaymentPathSet != nil {
181✔
1598
                paymentPath, err := r.BlindedPaymentPathSet.
2✔
1599
                        LargestLastHopPayloadPath()
2✔
1600
                if err != nil {
2✔
1601
                        return 0, err
×
1602
                }
×
1603

1604
                blindedPath := paymentPath.BlindedPath.BlindedHops
2✔
1605
                blindedPoint := paymentPath.BlindedPath.BlindingPoint
2✔
1606

2✔
1607
                encryptedData := blindedPath[len(blindedPath)-1].CipherText
2✔
1608
                finalHop := route.Hop{
2✔
1609
                        AmtToForward:     amount,
2✔
1610
                        OutgoingTimeLock: uint32(finalHtlcExpiry),
2✔
1611
                        EncryptedData:    encryptedData,
2✔
1612
                }
2✔
1613
                if len(blindedPath) == 1 {
3✔
1614
                        finalHop.BlindingPoint = blindedPoint
1✔
1615
                }
1✔
1616

1617
                // The final hop does not have a short chanID set.
1618
                return finalHop.PayloadSize(0), nil
2✔
1619
        }
1620

1621
        var mpp *record.MPP
177✔
1622
        r.PaymentAddr.WhenSome(func(addr [32]byte) {
228✔
1623
                mpp = record.NewMPP(amount, addr)
51✔
1624
        })
51✔
1625

1626
        var amp *record.AMP
177✔
1627
        if r.Amp != nil {
178✔
1628
                // The AMP payload is not easy accessible at this point but we
1✔
1629
                // are only interested in the size of the payload so we just use
1✔
1630
                // the AMP record dummy.
1✔
1631
                amp = &record.MaxAmpPayLoadSize
1✔
1632
        }
1✔
1633

1634
        finalHop := route.Hop{
177✔
1635
                AmtToForward:     amount,
177✔
1636
                OutgoingTimeLock: uint32(finalHtlcExpiry),
177✔
1637
                CustomRecords:    r.DestCustomRecords,
177✔
1638
                MPP:              mpp,
177✔
1639
                AMP:              amp,
177✔
1640
                Metadata:         r.Metadata,
177✔
1641
        }
177✔
1642

177✔
1643
        // The final hop does not have a short chanID set.
177✔
1644
        return finalHop.PayloadSize(0), nil
177✔
1645
}
1646

1647
// overflowSafeAdd adds two MilliSatoshi values and returns the result. If an
1648
// overflow could occur, zero is returned instead and the boolean is set to
1649
// true.
1650
func overflowSafeAdd(x, y lnwire.MilliSatoshi) (lnwire.MilliSatoshi, bool) {
433✔
1651
        if y > math.MaxUint64-x {
433✔
1652
                // Overflow would occur, return 0 and set overflow flag.
×
1653
                return 0, true
×
1654
        }
×
1655

1656
        return x + y, false
433✔
1657
}
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