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

lightningnetwork / lnd / 14388908780

10 Apr 2025 07:39PM UTC coverage: 56.811% (-12.3%) from 69.08%
14388908780

Pull #9702

github

web-flow
Merge f006bbf4d into b732525a9
Pull Request #9702: multi: make payment address mandatory

28 of 42 new or added lines in 11 files covered. (66.67%)

23231 existing lines in 283 files now uncovered.

107286 of 188846 relevant lines covered (56.81%)

22749.28 hits per line

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

89.63
/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 *[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 {
309✔
221
                        // If this edge comes from router hints, the features
93✔
222
                        // could be nil.
93✔
223
                        if edge.ToNodeFeatures == nil {
93✔
224
                                return false
×
225
                        }
×
226
                        return edge.ToNodeFeatures.HasFeature(feature)
93✔
227
                }
228

229
                if i == len(pathEdges)-1 {
309✔
230
                        // If this is the last hop, then the hop payload will
93✔
231
                        // contain the exact amount. In BOLT #4: Onion Routing
93✔
232
                        // Protocol / "Payload for the Last Node", this is
93✔
233
                        // detailed.
93✔
234
                        amtToForward = finalHop.amt
93✔
235

93✔
236
                        // Fee is not part of the hop payload, but only used for
93✔
237
                        // reporting through RPC. Set to zero for the final hop.
93✔
238
                        fee = 0
93✔
239

93✔
240
                        if blindedPathSet == nil {
185✔
241
                                totalTimeLock += uint32(finalHop.cltvDelta)
92✔
242
                        } else {
93✔
243
                                totalTimeLock += uint32(
1✔
244
                                        blindedPathSet.FinalCLTVDelta(),
1✔
245
                                )
1✔
246
                        }
1✔
247
                        outgoingTimeLock = totalTimeLock
93✔
248

93✔
249
                        // Attach any custom records to the final hop.
93✔
250
                        customRecords = finalHop.records
93✔
251

93✔
252
                        // If we're attaching a payment addr but the receiver
93✔
253
                        // doesn't support both TLV and payment addrs, fail.
93✔
254
                        payAddr := supports(lnwire.PaymentAddrOptional)
93✔
255
                        if !payAddr && finalHop.paymentAddr != nil {
93✔
256
                                return nil, errors.New("cannot attach " +
×
257
                                        "payment addr")
×
258
                        }
×
259

260
                        // Otherwise attach the mpp record if it exists.
261
                        // TODO(halseth): move this to payment life cycle,
262
                        // where AMP options are set.
263
                        if finalHop.paymentAddr != nil {
135✔
264
                                mpp = record.NewMPP(
42✔
265
                                        finalHop.totalAmt,
42✔
266
                                        *finalHop.paymentAddr,
42✔
267
                                )
42✔
268
                        }
42✔
269

270
                        metadata = finalHop.metadata
93✔
271

93✔
272
                        if blindedPathSet != nil {
94✔
273
                                totalAmtMsatBlinded = finalHop.totalAmt
1✔
274
                        }
1✔
275
                } else {
123✔
276
                        // The amount that the current hop needs to forward is
123✔
277
                        // equal to the incoming amount of the next hop.
123✔
278
                        amtToForward = nextIncomingAmount
123✔
279

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

123✔
289
                        inboundFee := pathEdges[i].inboundFees.CalcFee(
123✔
290
                                amtToForward + outboundFee,
123✔
291
                        )
123✔
292

123✔
293
                        fee = int64(outboundFee) + inboundFee
123✔
294
                        if fee < 0 {
125✔
295
                                fee = 0
2✔
296
                        }
2✔
297

298
                        // We'll take the total timelock of the preceding hop as
299
                        // the outgoing timelock or this hop. Then we'll
300
                        // increment the total timelock incurred by this hop.
301
                        outgoingTimeLock = totalTimeLock
123✔
302
                        totalTimeLock += uint32(
123✔
303
                                pathEdges[i+1].policy.TimeLockDelta,
123✔
304
                        )
123✔
305
                }
306

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

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

216✔
323
                // Finally, we update the amount that needs to flow into the
216✔
324
                // *next* hop, which is the amount this hop needs to forward,
216✔
325
                // accounting for the fee that it takes.
216✔
326
                nextIncomingAmount = amtToForward + lnwire.MilliSatoshi(fee)
216✔
327
        }
328

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

346
                var (
1✔
347
                        inBlindedRoute bool
1✔
348
                        dataIndex      = 0
1✔
349

1✔
350
                        blindedPath = blindedPayment.BlindedPath
1✔
351
                        introVertex = route.NewVertex(
1✔
352
                                blindedPath.IntroductionPoint,
1✔
353
                        )
1✔
354
                )
1✔
355

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

364
                        // We don't need to modify edges outside of our blinded
365
                        // route.
366
                        if !inBlindedRoute {
5✔
367
                                continue
1✔
368
                        }
369

370
                        payload := blindedPath.BlindedHops[dataIndex].CipherText
3✔
371
                        hop.EncryptedData = payload
3✔
372

3✔
373
                        // All of the hops in a blinded route *except* the
3✔
374
                        // final hop should have zero amounts / time locks.
3✔
375
                        if i != len(hops)-1 {
5✔
376
                                hop.AmtToForward = 0
2✔
377
                                hop.OutgoingTimeLock = 0
2✔
378
                        }
2✔
379

380
                        dataIndex++
3✔
381
                }
382
        }
383

384
        // With the base routing data expressed as hops, build the full route
385
        newRoute, err := route.NewRouteFromHops(
93✔
386
                nextIncomingAmount, totalTimeLock, route.Vertex(sourceVertex),
93✔
387
                hops,
93✔
388
        )
93✔
389
        if err != nil {
93✔
390
                return nil, err
×
391
        }
×
392

393
        return newRoute, nil
93✔
394
}
395

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

1,135✔
411
        return int64(fee) + timeLockPenalty
1,135✔
412
}
1,135✔
413

414
// graphParams wraps the set of graph parameters passed to findPath.
415
type graphParams struct {
416
        // graph is the ChannelGraph to be used during path finding.
417
        graph Graph
418

419
        // additionalEdges is an optional set of edges that should be
420
        // considered during path finding, that is not already found in the
421
        // channel graph. These can either be private edges for bolt 11 invoices
422
        // or blinded edges when a payment to a blinded path is made.
423
        additionalEdges map[route.Vertex][]AdditionalEdge
424

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

435
// RestrictParams wraps the set of restrictions passed to findPath that the
436
// found path must adhere to.
437
type RestrictParams struct {
438
        // ProbabilitySource is a callback that is expected to return the
439
        // success probability of traversing the channel from the node.
440
        ProbabilitySource func(route.Vertex, route.Vertex,
441
                lnwire.MilliSatoshi, btcutil.Amount) float64
442

443
        // FeeLimit is a maximum fee amount allowed to be used on the path from
444
        // the source to the target.
445
        FeeLimit lnwire.MilliSatoshi
446

447
        // OutgoingChannelIDs is the list of channels that are allowed for the
448
        // first hop. If nil, any channel may be used.
449
        OutgoingChannelIDs []uint64
450

451
        // LastHop is the pubkey of the last node before the final destination
452
        // is reached. If nil, any node may be used.
453
        LastHop *route.Vertex
454

455
        // CltvLimit is the maximum time lock of the route excluding the final
456
        // ctlv. After path finding is complete, the caller needs to increase
457
        // all cltv expiry heights with the required final cltv delta.
458
        CltvLimit uint32
459

460
        // DestCustomRecords contains the custom records to drop off at the
461
        // final hop, if any.
462
        DestCustomRecords record.CustomSet
463

464
        // DestFeatures is a feature vector describing what the final hop
465
        // supports. If none are provided, pathfinding will try to inspect any
466
        // features on the node announcement instead.
467
        DestFeatures *lnwire.FeatureVector
468

469
        // PaymentAddr is a random 32-byte value generated by the receiver to
470
        // mitigate probing vectors and payment sniping attacks on overpaid
471
        // invoices.
472
        PaymentAddr *[32]byte
473

474
        // Amp signals to the pathfinder that this payment is an AMP payment
475
        // and therefore it needs to account for additional AMP data in the
476
        // final hop payload size calculation.
477
        Amp *AMPOptions
478

479
        // Metadata is additional data that is sent along with the payment to
480
        // the payee.
481
        Metadata []byte
482

483
        // BlindedPaymentPathSet is necessary to determine the hop size of the
484
        // last/exit hop.
485
        BlindedPaymentPathSet *BlindedPaymentPathSet
486

487
        // FirstHopCustomRecords includes any records that should be included in
488
        // the update_add_htlc message towards our peer.
489
        FirstHopCustomRecords lnwire.CustomRecords
490
}
491

492
// PathFindingConfig defines global parameters that control the trade-off in
493
// path finding between fees and probability.
494
type PathFindingConfig struct {
495
        // AttemptCost is the fixed virtual cost in path finding of a failed
496
        // payment attempt. It is used to trade off potentially better routes
497
        // against their probability of succeeding.
498
        AttemptCost lnwire.MilliSatoshi
499

500
        // AttemptCostPPM is the proportional virtual cost in path finding of a
501
        // failed payment attempt. It is used to trade off potentially better
502
        // routes against their probability of succeeding. This parameter is
503
        // expressed in parts per million of the total payment amount.
504
        AttemptCostPPM int64
505

506
        // MinProbability defines the minimum success probability of the
507
        // returned route.
508
        MinProbability float64
509
}
510

511
// getOutgoingBalance returns the maximum available balance in any of the
512
// channels of the given node. The second return parameters is the total
513
// available balance.
514
func getOutgoingBalance(node route.Vertex, outgoingChans map[uint64]struct{},
515
        bandwidthHints bandwidthHints,
516
        g Graph) (lnwire.MilliSatoshi, lnwire.MilliSatoshi, error) {
180✔
517

180✔
518
        var max, total lnwire.MilliSatoshi
180✔
519
        cb := func(channel *graphdb.DirectedChannel) error {
625✔
520
                if !channel.OutPolicySet {
445✔
521
                        return nil
×
522
                }
×
523

524
                chanID := channel.ChannelID
445✔
525

445✔
526
                // Enforce outgoing channel restriction.
445✔
527
                if outgoingChans != nil {
465✔
528
                        if _, ok := outgoingChans[chanID]; !ok {
32✔
529
                                return nil
12✔
530
                        }
12✔
531
                }
532

533
                bandwidth, ok := bandwidthHints.availableChanBandwidth(
433✔
534
                        chanID, 0,
433✔
535
                )
433✔
536

433✔
537
                // If the bandwidth is not available, use the channel capacity.
433✔
538
                // This can happen when a channel is added to the graph after
433✔
539
                // we've already queried the bandwidth hints.
433✔
540
                if !ok {
675✔
541
                        bandwidth = lnwire.NewMSatFromSatoshis(channel.Capacity)
242✔
542
                }
242✔
543

544
                if bandwidth > max {
665✔
545
                        max = bandwidth
232✔
546
                }
232✔
547

548
                var overflow bool
433✔
549
                total, overflow = overflowSafeAdd(total, bandwidth)
433✔
550
                if overflow {
433✔
551
                        // If the current total and the bandwidth would
×
552
                        // overflow the maximum value, we set the total to the
×
553
                        // maximum value. Which is more milli-satoshis than are
×
554
                        // in existence anyway, so the actual value is
×
555
                        // irrelevant.
×
556
                        total = lnwire.MilliSatoshi(math.MaxUint64)
×
557
                }
×
558

559
                return nil
433✔
560
        }
561

562
        // Iterate over all channels of the to node.
563
        err := g.ForEachNodeDirectedChannel(node, cb)
180✔
564
        if err != nil {
180✔
565
                return 0, 0, err
×
566
        }
×
567
        return max, total, err
180✔
568
}
569

570
// findPath attempts to find a path from the source node within the ChannelGraph
571
// to the target node that's capable of supporting a payment of `amt` value. The
572
// current approach implemented is modified version of Dijkstra's algorithm to
573
// find a single shortest path between the source node and the destination. The
574
// distance metric used for edges is related to the time-lock+fee costs along a
575
// particular edge. If a path is found, this function returns a slice of
576
// ChannelHop structs which encoded the chosen path from the target to the
577
// source. The search is performed backwards from destination node back to
578
// source. This is to properly accumulate fees that need to be paid along the
579
// path and accurately check the amount to forward at every node against the
580
// available bandwidth.
581
func findPath(g *graphParams, r *RestrictParams, cfg *PathFindingConfig,
582
        self, source, target route.Vertex, amt lnwire.MilliSatoshi,
583
        timePref float64, finalHtlcExpiry int32) ([]*unifiedEdge, float64,
584
        error) {
186✔
585

186✔
586
        // Pathfinding can be a significant portion of the total payment
186✔
587
        // latency, especially on low-powered devices. Log several metrics to
186✔
588
        // aid in the analysis performance problems in this area.
186✔
589
        start := time.Now()
186✔
590
        nodesVisited := 0
186✔
591
        edgesExpanded := 0
186✔
592
        defer func() {
372✔
593
                timeElapsed := time.Since(start)
186✔
594
                log.Debugf("Pathfinding perf metrics: nodes=%v, edges=%v, "+
186✔
595
                        "time=%v", nodesVisited, edgesExpanded, timeElapsed)
186✔
596
        }()
186✔
597

598
        // If no destination features are provided, we will load what features
599
        // we have for the target node from our graph.
600
        features := r.DestFeatures
186✔
601
        if features == nil {
304✔
602
                var err error
118✔
603
                features, err = g.graph.FetchNodeFeatures(target)
118✔
604
                if err != nil {
118✔
605
                        return nil, 0, err
×
606
                }
×
607
        }
608

609
        // Ensure that the destination's features don't include unknown
610
        // required features.
611
        err := feature.ValidateRequired(features)
186✔
612
        if err != nil {
188✔
613
                log.Warnf("Pathfinding destination node features: %v", err)
2✔
614
                return nil, 0, errUnknownRequiredFeature
2✔
615
        }
2✔
616

617
        // Ensure that all transitive dependencies are set.
618
        err = feature.ValidateDeps(features)
184✔
619
        if err != nil {
186✔
620
                log.Warnf("Pathfinding destination node features: %v", err)
2✔
621
                return nil, 0, errMissingDependentFeature
2✔
622
        }
2✔
623

624
        // Now that we know the feature vector is well-formed, we'll proceed in
625
        // checking that it supports the features we need. If the caller has a
626
        // payment address to attach, check that our destination feature vector
627
        // supports them.
628
        if r.PaymentAddr != nil &&
182✔
629
                !features.HasFeature(lnwire.PaymentAddrOptional) {
184✔
630

2✔
631
                return nil, 0, errNoPaymentAddr
2✔
632
        }
2✔
633

634
        // Set up outgoing channel map for quicker access.
635
        var outgoingChanMap map[uint64]struct{}
180✔
636
        if len(r.OutgoingChannelIDs) > 0 {
186✔
637
                outgoingChanMap = make(map[uint64]struct{})
6✔
638
                for _, outChan := range r.OutgoingChannelIDs {
14✔
639
                        outgoingChanMap[outChan] = struct{}{}
8✔
640
                }
8✔
641
        }
642

643
        // If we are routing from ourselves, check that we have enough local
644
        // balance available.
645
        if source == self {
360✔
646
                max, total, err := getOutgoingBalance(
180✔
647
                        self, outgoingChanMap, g.bandwidthHints, g.graph,
180✔
648
                )
180✔
649
                if err != nil {
180✔
650
                        return nil, 0, err
×
651
                }
×
652

653
                // If the total outgoing balance isn't sufficient, it will be
654
                // impossible to complete the payment.
655
                if total < amt {
183✔
656
                        log.Warnf("Not enough outbound balance to send "+
3✔
657
                                "htlc of amount: %v, only have local "+
3✔
658
                                "balance: %v", amt, total)
3✔
659

3✔
660
                        return nil, 0, errInsufficientBalance
3✔
661
                }
3✔
662

663
                // If there is only not enough capacity on a single route, it
664
                // may still be possible to complete the payment by splitting.
665
                if max < amt {
178✔
666
                        return nil, 0, errNoPathFound
1✔
667
                }
1✔
668
        }
669

670
        // First we'll initialize an empty heap which'll help us to quickly
671
        // locate the next edge we should visit next during our graph
672
        // traversal.
673
        nodeHeap := newDistanceHeap(estimatedNodeCount)
176✔
674

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

176✔
678
        additionalEdgesWithSrc := make(map[route.Vertex][]*edgePolicyWithSource)
176✔
679
        for vertex, additionalEdges := range g.additionalEdges {
196✔
680
                // Edges connected to self are always included in the graph,
20✔
681
                // therefore can be skipped. This prevents us from trying
20✔
682
                // routes to malformed hop hints.
20✔
683
                if vertex == self {
24✔
684
                        continue
4✔
685
                }
686

687
                // Build reverse lookup to find incoming edges. Needed because
688
                // search is taken place from target to source.
689
                for _, additionalEdge := range additionalEdges {
32✔
690
                        outgoingEdgePolicy := additionalEdge.EdgePolicy()
16✔
691
                        toVertex := outgoingEdgePolicy.ToNodePubKey()
16✔
692

16✔
693
                        incomingEdgePolicy := &edgePolicyWithSource{
16✔
694
                                sourceNode: vertex,
16✔
695
                                edge:       additionalEdge,
16✔
696
                        }
16✔
697

16✔
698
                        additionalEdgesWithSrc[toVertex] =
16✔
699
                                append(additionalEdgesWithSrc[toVertex],
16✔
700
                                        incomingEdgePolicy)
16✔
701
                }
16✔
702
        }
703

704
        // The payload size of the final hop differ from intermediate hops
705
        // and depends on whether the destination is blinded or not.
706
        lastHopPayloadSize, err := lastHopPayloadSize(r, finalHtlcExpiry, amt)
176✔
707
        if err != nil {
176✔
708
                return nil, 0, err
×
709
        }
×
710

711
        // We can't always assume that the end destination is publicly
712
        // advertised to the network so we'll manually include the target node.
713
        // The target node charges no fee. Distance is set to 0, because this is
714
        // the starting point of the graph traversal. We are searching backwards
715
        // to get the fees first time right and correctly match channel
716
        // bandwidth.
717
        //
718
        // Don't record the initial partial path in the distance map and reserve
719
        // that key for the source key in the case we route to ourselves.
720
        partialPath := &nodeWithDist{
176✔
721
                dist:              0,
176✔
722
                weight:            0,
176✔
723
                node:              target,
176✔
724
                netAmountReceived: amt,
176✔
725
                incomingCltv:      finalHtlcExpiry,
176✔
726
                probability:       1,
176✔
727
                routingInfoSize:   lastHopPayloadSize,
176✔
728
        }
176✔
729

176✔
730
        // Calculate the absolute cltv limit. Use uint64 to prevent an overflow
176✔
731
        // if the cltv limit is MaxUint32.
176✔
732
        absoluteCltvLimit := uint64(r.CltvLimit) + uint64(finalHtlcExpiry)
176✔
733

176✔
734
        // Calculate the default attempt cost as configured globally.
176✔
735
        defaultAttemptCost := float64(
176✔
736
                cfg.AttemptCost +
176✔
737
                        amt*lnwire.MilliSatoshi(cfg.AttemptCostPPM)/1000000,
176✔
738
        )
176✔
739

176✔
740
        // Validate time preference value.
176✔
741
        if math.Abs(timePref) > 1 {
176✔
742
                return nil, 0, fmt.Errorf("time preference %v out of range "+
×
743
                        "[-1, 1]", timePref)
×
744
        }
×
745

746
        // Scale to avoid the extremes -1 and 1 which run into infinity issues.
747
        timePref *= 0.9
176✔
748

176✔
749
        // Apply time preference. At 0, the default attempt cost will
176✔
750
        // be used.
176✔
751
        absoluteAttemptCost := defaultAttemptCost * (1/(0.5-timePref/2) - 1)
176✔
752

176✔
753
        log.Debugf("Pathfinding absolute attempt cost: %v sats",
176✔
754
                absoluteAttemptCost/1000)
176✔
755

176✔
756
        // processEdge is a helper closure that will be used to make sure edges
176✔
757
        // satisfy our specific requirements.
176✔
758
        processEdge := func(fromVertex route.Vertex,
176✔
759
                edge *unifiedEdge, toNodeDist *nodeWithDist) {
1,428✔
760

1,252✔
761
                edgesExpanded++
1,252✔
762

1,252✔
763
                // Calculate inbound fee charged by "to" node. The exit hop
1,252✔
764
                // doesn't charge inbound fees. If the "to" node is the exit
1,252✔
765
                // hop, its inbound fees have already been set to zero by
1,252✔
766
                // nodeEdgeUnifier.
1,252✔
767
                inboundFee := edge.inboundFees.CalcFee(
1,252✔
768
                        toNodeDist.netAmountReceived,
1,252✔
769
                )
1,252✔
770

1,252✔
771
                // Make sure that the node total fee is never negative.
1,252✔
772
                // Routing nodes treat a total fee that turns out
1,252✔
773
                // negative as a zero fee and pathfinding should do the
1,252✔
774
                // same.
1,252✔
775
                minInboundFee := -int64(toNodeDist.outboundFee)
1,252✔
776
                if inboundFee < minInboundFee {
1,254✔
777
                        inboundFee = minInboundFee
2✔
778
                }
2✔
779

780
                // Calculate amount that the candidate node would have to send
781
                // out.
782
                amountToSend := toNodeDist.netAmountReceived +
1,252✔
783
                        lnwire.MilliSatoshi(inboundFee)
1,252✔
784

1,252✔
785
                // Check if accumulated fees would exceed fee limit when this
1,252✔
786
                // node would be added to the path.
1,252✔
787
                totalFee := int64(amountToSend) - int64(amt)
1,252✔
788

1,252✔
789
                log.Trace(lnutils.NewLogClosure(func() string {
1,252✔
790
                        return fmt.Sprintf(
×
791
                                "Checking fromVertex (%v) with "+
×
792
                                        "minInboundFee=%v, inboundFee=%v, "+
×
793
                                        "amountToSend=%v, amt=%v, totalFee=%v",
×
794
                                fromVertex, minInboundFee, inboundFee,
×
795
                                amountToSend, amt, totalFee,
×
796
                        )
×
797
                }))
×
798

799
                if totalFee > 0 && lnwire.MilliSatoshi(totalFee) > r.FeeLimit {
1,256✔
800
                        return
4✔
801
                }
4✔
802

803
                // Request the success probability for this edge.
804
                edgeProbability := r.ProbabilitySource(
1,248✔
805
                        fromVertex, toNodeDist.node, amountToSend,
1,248✔
806
                        edge.capacity,
1,248✔
807
                )
1,248✔
808

1,248✔
809
                log.Trace(lnutils.NewLogClosure(func() string {
1,248✔
810
                        return fmt.Sprintf("path finding probability: fromnode=%v,"+
×
811
                                " tonode=%v, amt=%v, cap=%v, probability=%v",
×
812
                                fromVertex, toNodeDist.node, amountToSend,
×
813
                                edge.capacity, edgeProbability)
×
814
                }))
×
815

816
                // If the probability is zero, there is no point in trying.
817
                if edgeProbability == 0 {
1,248✔
818
                        return
×
819
                }
×
820

821
                // Compute fee that fromVertex is charging. It is based on the
822
                // amount that needs to be sent to the next node in the route.
823
                //
824
                // Source node has no predecessor to pay a fee. Therefore set
825
                // fee to zero, because it should not be included in the fee
826
                // limit check and edge weight.
827
                //
828
                // Also determine the time lock delta that will be added to the
829
                // route if fromVertex is selected. If fromVertex is the source
830
                // node, no additional timelock is required.
831
                var (
1,248✔
832
                        timeLockDelta uint16
1,248✔
833
                        outboundFee   int64
1,248✔
834
                )
1,248✔
835

1,248✔
836
                if fromVertex != source {
2,352✔
837
                        outboundFee = int64(
1,104✔
838
                                edge.policy.ComputeFee(amountToSend),
1,104✔
839
                        )
1,104✔
840
                        timeLockDelta = edge.policy.TimeLockDelta
1,104✔
841
                }
1,104✔
842

843
                incomingCltv := toNodeDist.incomingCltv + int32(timeLockDelta)
1,248✔
844

1,248✔
845
                // Check that we are within our CLTV limit.
1,248✔
846
                if uint64(incomingCltv) > absoluteCltvLimit {
1,260✔
847
                        return
12✔
848
                }
12✔
849

850
                // netAmountToReceive is the amount that the node that is added
851
                // to the distance map needs to receive from a (to be found)
852
                // previous node in the route. The inbound fee of the receiving
853
                // node is already subtracted from this value. The previous node
854
                // will need to pay the amount that this node forwards plus the
855
                // fee it charges plus this node's inbound fee.
856
                netAmountToReceive := amountToSend +
1,236✔
857
                        lnwire.MilliSatoshi(outboundFee)
1,236✔
858

1,236✔
859
                // Calculate total probability of successfully reaching target
1,236✔
860
                // by multiplying the probabilities. Both this edge and the rest
1,236✔
861
                // of the route must succeed.
1,236✔
862
                probability := toNodeDist.probability * edgeProbability
1,236✔
863

1,236✔
864
                // If the probability is below the specified lower bound, we can
1,236✔
865
                // abandon this direction. Adding further nodes can only lower
1,236✔
866
                // the probability more.
1,236✔
867
                if probability < cfg.MinProbability {
1,337✔
868
                        return
101✔
869
                }
101✔
870

871
                // Calculate the combined fee for this edge. Dijkstra does not
872
                // support negative edge weights. Because this fee feeds into
873
                // the edge weight calculation, we don't allow it to be
874
                // negative.
875
                signedFee := inboundFee + outboundFee
1,135✔
876
                fee := lnwire.MilliSatoshi(0)
1,135✔
877
                if signedFee > 0 {
1,693✔
878
                        fee = lnwire.MilliSatoshi(signedFee)
558✔
879
                }
558✔
880

881
                // By adding fromVertex in the route, there will be an extra
882
                // weight composed of the fee that this node will charge and
883
                // the amount that will be locked for timeLockDelta blocks in
884
                // the HTLC that is handed out to fromVertex.
885
                weight := edgeWeight(amountToSend, fee, timeLockDelta)
1,135✔
886

1,135✔
887
                // Compute the tentative weight to this new channel/edge
1,135✔
888
                // which is the weight from our toNode to the target node
1,135✔
889
                // plus the weight of this edge.
1,135✔
890
                tempWeight := toNodeDist.weight + weight
1,135✔
891

1,135✔
892
                // Add an extra factor to the weight to take into account the
1,135✔
893
                // probability. Another reason why we rounded the fee up to zero
1,135✔
894
                // is to prevent a highly negative fee from cancelling out the
1,135✔
895
                // extra factor. We don't want an always-failing node to attract
1,135✔
896
                // traffic using a highly negative fee and escape penalization.
1,135✔
897
                tempDist := getProbabilityBasedDist(
1,135✔
898
                        tempWeight, probability,
1,135✔
899
                        absoluteAttemptCost,
1,135✔
900
                )
1,135✔
901

1,135✔
902
                // If there is already a best route stored, compare this
1,135✔
903
                // candidate route with the best route so far.
1,135✔
904
                current, ok := distance[fromVertex]
1,135✔
905
                if ok {
1,530✔
906
                        // If this route is worse than what we already found,
395✔
907
                        // skip this route.
395✔
908
                        if tempDist > current.dist {
700✔
909
                                return
305✔
910
                        }
305✔
911

912
                        // If the route is equally good and the probability
913
                        // isn't better, skip this route. It is important to
914
                        // also return if both cost and probability are equal,
915
                        // because otherwise the algorithm could run into an
916
                        // endless loop.
917
                        probNotBetter := probability <= current.probability
90✔
918
                        if tempDist == current.dist && probNotBetter {
149✔
919
                                return
59✔
920
                        }
59✔
921
                }
922

923
                // Calculate the total routing info size if this hop were to be
924
                // included. If we are coming from the source hop, the payload
925
                // size is zero, because the original htlc isn't in the onion
926
                // blob.
927
                //
928
                // NOTE: For blinded paths with the NUMS key as the last hop,
929
                // the payload size accounts for this dummy hop which is of
930
                // the same size as the real last hop. So we account for a
931
                // bigger size than the route is however we accept this
932
                // little inaccuracy here because we are over estimating by
933
                // 1 hop.
934
                var payloadSize uint64
771✔
935
                if fromVertex != source {
1,402✔
936
                        // In case the unifiedEdge does not have a payload size
631✔
937
                        // function supplied we request a graceful shutdown
631✔
938
                        // because this should never happen.
631✔
939
                        if edge.hopPayloadSizeFn == nil {
631✔
940
                                log.Criticalf("No payload size function "+
×
941
                                        "available for edge=%v unable to "+
×
942
                                        "determine payload size: %v", edge,
×
943
                                        ErrNoPayLoadSizeFunc)
×
944

×
945
                                return
×
946
                        }
×
947

948
                        payloadSize = edge.hopPayloadSizeFn(
631✔
949
                                amountToSend,
631✔
950
                                uint32(toNodeDist.incomingCltv),
631✔
951
                                edge.policy.ChannelID,
631✔
952
                        )
631✔
953
                }
954

955
                routingInfoSize := toNodeDist.routingInfoSize + payloadSize
771✔
956
                // Skip paths that would exceed the maximum routing info size.
771✔
957
                if routingInfoSize > sphinx.MaxPayloadSize {
777✔
958
                        return
6✔
959
                }
6✔
960

961
                // All conditions are met and this new tentative distance is
962
                // better than the current best known distance to this node.
963
                // The new better distance is recorded, and also our "next hop"
964
                // map is populated with this edge.
965
                withDist := &nodeWithDist{
765✔
966
                        dist:              tempDist,
765✔
967
                        weight:            tempWeight,
765✔
968
                        node:              fromVertex,
765✔
969
                        netAmountReceived: netAmountToReceive,
765✔
970
                        outboundFee:       lnwire.MilliSatoshi(outboundFee),
765✔
971
                        incomingCltv:      incomingCltv,
765✔
972
                        probability:       probability,
765✔
973
                        nextHop:           edge,
765✔
974
                        routingInfoSize:   routingInfoSize,
765✔
975
                }
765✔
976
                distance[fromVertex] = withDist
765✔
977

765✔
978
                // Either push withDist onto the heap if the node
765✔
979
                // represented by fromVertex is not already on the heap OR adjust
765✔
980
                // its position within the heap via heap.Fix.
765✔
981
                nodeHeap.PushOrFix(withDist)
765✔
982
        }
983

984
        // TODO(roasbeef): also add path caching
985
        //  * similar to route caching, but doesn't factor in the amount
986

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

176✔
990
        // getGraphFeatures returns (cached) node features from the graph.
176✔
991
        getGraphFeatures := func(node route.Vertex) (*lnwire.FeatureVector,
176✔
992
                error) {
1,432✔
993

1,256✔
994
                // Check cache for features of the fromNode.
1,256✔
995
                fromFeatures, ok := featureCache[node]
1,256✔
996
                if ok {
1,719✔
997
                        return fromFeatures, nil
463✔
998
                }
463✔
999

1000
                // Fetch node features fresh from the graph.
1001
                fromFeatures, err := g.graph.FetchNodeFeatures(node)
793✔
1002
                if err != nil {
793✔
1003
                        return nil, err
×
1004
                }
×
1005

1006
                // Don't route through nodes that contain unknown required
1007
                // features and mark as nil in the cache.
1008
                err = feature.ValidateRequired(fromFeatures)
793✔
1009
                if err != nil {
795✔
1010
                        featureCache[node] = nil
2✔
1011
                        return nil, nil
2✔
1012
                }
2✔
1013

1014
                // Don't route through nodes that don't properly set all
1015
                // transitive feature dependencies and mark as nil in the cache.
1016
                err = feature.ValidateDeps(fromFeatures)
791✔
1017
                if err != nil {
793✔
1018
                        featureCache[node] = nil
2✔
1019
                        return nil, nil
2✔
1020
                }
2✔
1021

1022
                // Update cache.
1023
                featureCache[node] = fromFeatures
789✔
1024

789✔
1025
                return fromFeatures, nil
789✔
1026
        }
1027

1028
        routeToSelf := source == target
176✔
1029
        for {
872✔
1030
                nodesVisited++
696✔
1031

696✔
1032
                pivot := partialPath.node
696✔
1033
                isExitHop := partialPath.nextHop == nil
696✔
1034

696✔
1035
                // Create unified policies for all incoming connections. Don't
696✔
1036
                // use inbound fees for the exit hop.
696✔
1037
                u := newNodeEdgeUnifier(
696✔
1038
                        self, pivot, !isExitHop, outgoingChanMap,
696✔
1039
                )
696✔
1040

696✔
1041
                err := u.addGraphPolicies(g.graph)
696✔
1042
                if err != nil {
696✔
1043
                        return nil, 0, err
×
1044
                }
×
1045

1046
                // We add hop hints that were supplied externally.
1047
                for _, reverseEdge := range additionalEdgesWithSrc[pivot] {
712✔
1048
                        // Assume zero inbound fees for route hints. If inbound
16✔
1049
                        // fees would apply, they couldn't be communicated in
16✔
1050
                        // bolt11 invoices currently.
16✔
1051
                        inboundFee := models.InboundFee{}
16✔
1052

16✔
1053
                        // Hop hints don't contain a capacity. We set one here,
16✔
1054
                        // since a capacity is needed for probability
16✔
1055
                        // calculations. We set a high capacity to act as if
16✔
1056
                        // there is enough liquidity, otherwise the hint would
16✔
1057
                        // not have been added by a wallet.
16✔
1058
                        // We also pass the payload size function to the
16✔
1059
                        // graph data so that we calculate the exact payload
16✔
1060
                        // size when evaluating this hop for a route.
16✔
1061
                        u.addPolicy(
16✔
1062
                                reverseEdge.sourceNode,
16✔
1063
                                reverseEdge.edge.EdgePolicy(),
16✔
1064
                                inboundFee,
16✔
1065
                                fakeHopHintCapacity,
16✔
1066
                                reverseEdge.edge.IntermediatePayloadSize,
16✔
1067
                                reverseEdge.edge.BlindedPayment(),
16✔
1068
                        )
16✔
1069
                }
16✔
1070

1071
                netAmountReceived := partialPath.netAmountReceived
696✔
1072

696✔
1073
                // Expand all connections using the optimal policy for each
696✔
1074
                // connection.
696✔
1075
                for fromNode, edgeUnifier := range u.edgeUnifiers {
2,316✔
1076
                        // The target node is not recorded in the distance map.
1,620✔
1077
                        // Therefore we need to have this check to prevent
1,620✔
1078
                        // creating a cycle. Only when we intend to route to
1,620✔
1079
                        // self, we allow this cycle to form. In that case we'll
1,620✔
1080
                        // also break out of the search loop below.
1,620✔
1081
                        if !routeToSelf && fromNode == target {
1,950✔
1082
                                continue
330✔
1083
                        }
1084

1085
                        // Apply last hop restriction if set.
1086
                        if r.LastHop != nil &&
1,290✔
1087
                                pivot == target && fromNode != *r.LastHop {
1,294✔
1088

4✔
1089
                                continue
4✔
1090
                        }
1091

1092
                        edge := edgeUnifier.getEdge(
1,286✔
1093
                                netAmountReceived, g.bandwidthHints,
1,286✔
1094
                                partialPath.outboundFee,
1,286✔
1095
                        )
1,286✔
1096

1,286✔
1097
                        if edge == nil {
1,316✔
1098
                                continue
30✔
1099
                        }
1100

1101
                        // Get feature vector for fromNode.
1102
                        fromFeatures, err := getGraphFeatures(fromNode)
1,256✔
1103
                        if err != nil {
1,256✔
1104
                                return nil, 0, err
×
1105
                        }
×
1106

1107
                        // If there are no valid features, skip this node.
1108
                        if fromFeatures == nil {
1,260✔
1109
                                continue
4✔
1110
                        }
1111

1112
                        // Check if this candidate node is better than what we
1113
                        // already have.
1114
                        processEdge(fromNode, edge, partialPath)
1,252✔
1115
                }
1116

1117
                if nodeHeap.Len() == 0 {
736✔
1118
                        break
40✔
1119
                }
1120

1121
                // Fetch the node within the smallest distance from our source
1122
                // from the heap.
1123
                partialPath = heap.Pop(&nodeHeap).(*nodeWithDist)
656✔
1124

656✔
1125
                // If we've reached our source (or we don't have any incoming
656✔
1126
                // edges), then we're done here and can exit the graph
656✔
1127
                // traversal early.
656✔
1128
                if partialPath.node == source {
792✔
1129
                        break
136✔
1130
                }
1131
        }
1132

1133
        // Use the distance map to unravel the forward path from source to
1134
        // target.
1135
        var pathEdges []*unifiedEdge
176✔
1136
        currentNode := source
176✔
1137
        for {
556✔
1138
                // Determine the next hop forward using the next map.
380✔
1139
                currentNodeWithDist, ok := distance[currentNode]
380✔
1140
                if !ok {
420✔
1141
                        // If the node doesn't have a next hop it means we
40✔
1142
                        // didn't find a path.
40✔
1143
                        return nil, 0, errNoPathFound
40✔
1144
                }
40✔
1145

1146
                // Add the next hop to the list of path edges.
1147
                pathEdges = append(pathEdges, currentNodeWithDist.nextHop)
340✔
1148

340✔
1149
                // Advance current node.
340✔
1150
                currentNode = currentNodeWithDist.nextHop.policy.ToNodePubKey()
340✔
1151

340✔
1152
                // Check stop condition at the end of this loop. This prevents
340✔
1153
                // breaking out too soon for self-payments that have target set
340✔
1154
                // to source.
340✔
1155
                if currentNode == target {
476✔
1156
                        break
136✔
1157
                }
1158
        }
1159

1160
        // For the final hop, we'll set the node features to those determined
1161
        // above. These are either taken from the destination features, e.g.
1162
        // virtual or invoice features, or loaded as a fallback from the graph.
1163
        // The transitive dependencies were already validated above, so no need
1164
        // to do so now.
1165
        //
1166
        // NOTE: This may overwrite features loaded from the graph if
1167
        // destination features were provided. This is fine though, since our
1168
        // route construction does not care where the features are actually
1169
        // taken from. In the future we may wish to do route construction within
1170
        // findPath, and avoid using ChannelEdgePolicy altogether.
1171
        pathEdges[len(pathEdges)-1].policy.ToNodeFeatures = features
136✔
1172

136✔
1173
        log.Debugf("Found route: probability=%v, hops=%v, fee=%v",
136✔
1174
                distance[source].probability, len(pathEdges),
136✔
1175
                distance[source].netAmountReceived-amt)
136✔
1176

136✔
1177
        return pathEdges, distance[source].probability, nil
136✔
1178
}
1179

1180
// blindedPathRestrictions are a set of constraints to adhere to when
1181
// choosing a set of blinded paths to this node.
1182
type blindedPathRestrictions struct {
1183
        // minNumHops is the minimum number of hops to include in a blinded
1184
        // path. This doesn't include our node, so if the minimum is 1, then
1185
        // the path will contain at minimum our node along with an introduction
1186
        // node hop. A minimum of 0 will include paths where this node is the
1187
        // introduction node and so should be used with caution.
1188
        minNumHops uint8
1189

1190
        // maxNumHops is the maximum number of hops to include in a blinded
1191
        // path. This doesn't include our node, so if the maximum is 1, then
1192
        // the path will contain our node along with an introduction node hop.
1193
        maxNumHops uint8
1194

1195
        // nodeOmissionSet holds a set of node IDs of nodes that we should
1196
        // ignore during blinded path selection.
1197
        nodeOmissionSet fn.Set[route.Vertex]
1198
}
1199

1200
// blindedHop holds the information about a hop we have selected for a blinded
1201
// path.
1202
type blindedHop struct {
1203
        vertex       route.Vertex
1204
        channelID    uint64
1205
        edgeCapacity btcutil.Amount
1206
}
1207

1208
// findBlindedPaths does a depth first search from the target node to find a set
1209
// of blinded paths to the target node given the set of restrictions. This
1210
// function will select and return any candidate path. A candidate path is a
1211
// path to the target node with a size determined by the given hop number
1212
// constraints where all the nodes on the path signal the route blinding feature
1213
// _and_ the introduction node for the path has more than one public channel.
1214
// Any filtering of paths based on payment value or success probabilities is
1215
// left to the caller.
1216
func findBlindedPaths(g Graph, target route.Vertex,
1217
        restrictions *blindedPathRestrictions) ([][]blindedHop, error) {
12✔
1218

12✔
1219
        // Sanity check the restrictions.
12✔
1220
        if restrictions.minNumHops > restrictions.maxNumHops {
12✔
1221
                return nil, fmt.Errorf("maximum number of blinded path hops "+
×
1222
                        "(%d) must be greater than or equal to the minimum "+
×
1223
                        "number of hops (%d)", restrictions.maxNumHops,
×
1224
                        restrictions.minNumHops)
×
1225
        }
×
1226

1227
        // If the node is not the destination node, then it is required that the
1228
        // node advertise the route blinding feature-bit in order for it to be
1229
        // chosen as a node on the blinded path.
1230
        supportsRouteBlinding := func(node route.Vertex) (bool, error) {
85✔
1231
                if node == target {
85✔
1232
                        return true, nil
12✔
1233
                }
12✔
1234

1235
                features, err := g.FetchNodeFeatures(node)
61✔
1236
                if err != nil {
61✔
1237
                        return false, err
×
1238
                }
×
1239

1240
                return features.HasFeature(lnwire.RouteBlindingOptional), nil
61✔
1241
        }
1242

1243
        // This function will have some recursion. We will spin out from the
1244
        // target node & append edges to the paths until we reach various exit
1245
        // conditions such as: The maxHops number being reached or reaching
1246
        // a node that doesn't have any other edges - in that final case, the
1247
        // whole path should be ignored.
1248
        paths, _, err := processNodeForBlindedPath(
12✔
1249
                g, target, supportsRouteBlinding, nil, restrictions,
12✔
1250
        )
12✔
1251
        if err != nil {
12✔
1252
                return nil, err
×
1253
        }
×
1254

1255
        // Reverse each path so that the order is correct (from introduction
1256
        // node to last hop node) and then append this node on as the
1257
        // destination of each path.
1258
        orderedPaths := make([][]blindedHop, len(paths))
12✔
1259
        for i, path := range paths {
43✔
1260
                sort.Slice(path, func(i, j int) bool {
62✔
1261
                        return j < i
31✔
1262
                })
31✔
1263

1264
                orderedPaths[i] = append(path, blindedHop{vertex: target})
31✔
1265
        }
1266

1267
        // Handle the special case that allows a blinded path with the
1268
        // introduction node as the destination node.
1269
        if restrictions.minNumHops == 0 {
14✔
1270
                singleHopPath := [][]blindedHop{{{vertex: target}}}
2✔
1271

2✔
1272
                //nolint:makezero
2✔
1273
                orderedPaths = append(
2✔
1274
                        orderedPaths, singleHopPath...,
2✔
1275
                )
2✔
1276
        }
2✔
1277

1278
        return orderedPaths, err
12✔
1279
}
1280

1281
// processNodeForBlindedPath is a recursive function that traverses the graph
1282
// in a depth first manner searching for a set of blinded paths to the given
1283
// node.
1284
func processNodeForBlindedPath(g Graph, node route.Vertex,
1285
        supportsRouteBlinding func(vertex route.Vertex) (bool, error),
1286
        alreadyVisited map[route.Vertex]bool,
1287
        restrictions *blindedPathRestrictions) ([][]blindedHop, bool, error) {
198✔
1288

198✔
1289
        // If we have already visited the maximum number of hops, then this path
198✔
1290
        // is complete and we can exit now.
198✔
1291
        if len(alreadyVisited) > int(restrictions.maxNumHops) {
290✔
1292
                return nil, false, nil
92✔
1293
        }
92✔
1294

1295
        // If we have already visited this peer on this path, then we skip
1296
        // processing it again.
1297
        if alreadyVisited[node] {
136✔
1298
                return nil, false, nil
30✔
1299
        }
30✔
1300

1301
        // If we have explicitly been told to ignore this node for blinded paths
1302
        // then we skip it too.
1303
        if restrictions.nodeOmissionSet.Contains(node) {
79✔
1304
                return nil, false, nil
3✔
1305
        }
3✔
1306

1307
        supports, err := supportsRouteBlinding(node)
73✔
1308
        if err != nil {
73✔
1309
                return nil, false, err
×
1310
        }
×
1311
        if !supports {
79✔
1312
                return nil, false, nil
6✔
1313
        }
6✔
1314

1315
        // At this point, copy the alreadyVisited map.
1316
        visited := make(map[route.Vertex]bool, len(alreadyVisited))
67✔
1317
        for r := range alreadyVisited {
151✔
1318
                visited[r] = true
84✔
1319
        }
84✔
1320

1321
        // Add this node the visited set.
1322
        visited[node] = true
67✔
1323

67✔
1324
        var (
67✔
1325
                hopSets   [][]blindedHop
67✔
1326
                chanCount int
67✔
1327
        )
67✔
1328

67✔
1329
        // Now, iterate over the node's channels in search for paths to this
67✔
1330
        // node that can be used for blinded paths
67✔
1331
        err = g.ForEachNodeDirectedChannel(node,
67✔
1332
                func(channel *graphdb.DirectedChannel) error {
253✔
1333
                        // Keep track of how many incoming channels this node
186✔
1334
                        // has. We only use a node as an introduction node if it
186✔
1335
                        // has channels other than the one that lead us to it.
186✔
1336
                        chanCount++
186✔
1337

186✔
1338
                        // Process each channel peer to gather any paths that
186✔
1339
                        // lead to the peer.
186✔
1340
                        nextPaths, hasMoreChans, err := processNodeForBlindedPath( //nolint:ll
186✔
1341
                                g, channel.OtherNode, supportsRouteBlinding,
186✔
1342
                                visited, restrictions,
186✔
1343
                        )
186✔
1344
                        if err != nil {
186✔
1345
                                return err
×
1346
                        }
×
1347

1348
                        hop := blindedHop{
186✔
1349
                                vertex:       channel.OtherNode,
186✔
1350
                                channelID:    channel.ChannelID,
186✔
1351
                                edgeCapacity: channel.Capacity,
186✔
1352
                        }
186✔
1353

186✔
1354
                        // For each of the paths returned, unwrap them and
186✔
1355
                        // append this hop to them.
186✔
1356
                        for _, path := range nextPaths {
215✔
1357
                                hopSets = append(
29✔
1358
                                        hopSets,
29✔
1359
                                        append([]blindedHop{hop}, path...),
29✔
1360
                                )
29✔
1361
                        }
29✔
1362

1363
                        // If this node does have channels other than the one
1364
                        // that lead to it, and if the hop count up to this node
1365
                        // meets the minHop requirement, then we also add a
1366
                        // path that starts at this node.
1367
                        if hasMoreChans &&
186✔
1368
                                len(visited) >= int(restrictions.minNumHops) {
217✔
1369

31✔
1370
                                hopSets = append(hopSets, []blindedHop{hop})
31✔
1371
                        }
31✔
1372

1373
                        return nil
186✔
1374
                },
1375
        )
1376
        if err != nil {
67✔
1377
                return nil, false, err
×
1378
        }
×
1379

1380
        return hopSets, chanCount > 1, nil
67✔
1381
}
1382

1383
// getProbabilityBasedDist converts a weight into a distance that takes into
1384
// account the success probability and the (virtual) cost of a failed payment
1385
// attempt.
1386
//
1387
// Derivation:
1388
//
1389
// Suppose there are two routes A and B with fees Fa and Fb and success
1390
// probabilities Pa and Pb.
1391
//
1392
// Is the expected cost of trying route A first and then B lower than trying the
1393
// other way around?
1394
//
1395
// The expected cost of A-then-B is: Pa*Fa + (1-Pa)*Pb*(c+Fb)
1396
//
1397
// The expected cost of B-then-A is: Pb*Fb + (1-Pb)*Pa*(c+Fa)
1398
//
1399
// In these equations, the term representing the case where both A and B fail is
1400
// left out because its value would be the same in both cases.
1401
//
1402
// Pa*Fa + (1-Pa)*Pb*(c+Fb) < Pb*Fb + (1-Pb)*Pa*(c+Fa)
1403
//
1404
// Pa*Fa + Pb*c + Pb*Fb - Pa*Pb*c - Pa*Pb*Fb < Pb*Fb + Pa*c + Pa*Fa - Pa*Pb*c - Pa*Pb*Fa
1405
//
1406
// Removing terms that cancel out:
1407
// Pb*c - Pa*Pb*Fb < Pa*c - Pa*Pb*Fa
1408
//
1409
// Divide by Pa*Pb:
1410
// c/Pa - Fb < c/Pb - Fa
1411
//
1412
// Move terms around:
1413
// Fa + c/Pa < Fb + c/Pb
1414
//
1415
// So the value of F + c/P can be used to compare routes.
1416
func getProbabilityBasedDist(weight int64, probability float64,
1417
        penalty float64) int64 {
1,135✔
1418

1,135✔
1419
        // Prevent divide by zero by returning early.
1,135✔
1420
        if probability == 0 {
1,135✔
1421
                return infinity
×
1422
        }
×
1423

1424
        // Calculate distance.
1425
        dist := float64(weight) + penalty/probability
1,135✔
1426

1,135✔
1427
        // Avoid cast if an overflow would occur. The maxFloat constant is
1,135✔
1428
        // chosen to stay well below the maximum float64 value that is still
1,135✔
1429
        // convertible to int64.
1,135✔
1430
        const maxFloat = 9000000000000000000
1,135✔
1431
        if dist > maxFloat {
1,135✔
1432
                return infinity
×
1433
        }
×
1434

1435
        return int64(dist)
1,135✔
1436
}
1437

1438
// lastHopPayloadSize calculates the payload size of the final hop in a route.
1439
// It depends on the tlv types which are present and also whether the hop is
1440
// part of a blinded route or not.
1441
func lastHopPayloadSize(r *RestrictParams, finalHtlcExpiry int32,
1442
        amount lnwire.MilliSatoshi) (uint64, error) {
179✔
1443

179✔
1444
        if r.BlindedPaymentPathSet != nil {
181✔
1445
                paymentPath, err := r.BlindedPaymentPathSet.
2✔
1446
                        LargestLastHopPayloadPath()
2✔
1447
                if err != nil {
2✔
1448
                        return 0, err
×
1449
                }
×
1450

1451
                blindedPath := paymentPath.BlindedPath.BlindedHops
2✔
1452
                blindedPoint := paymentPath.BlindedPath.BlindingPoint
2✔
1453

2✔
1454
                encryptedData := blindedPath[len(blindedPath)-1].CipherText
2✔
1455
                finalHop := route.Hop{
2✔
1456
                        AmtToForward:     amount,
2✔
1457
                        OutgoingTimeLock: uint32(finalHtlcExpiry),
2✔
1458
                        EncryptedData:    encryptedData,
2✔
1459
                }
2✔
1460
                if len(blindedPath) == 1 {
3✔
1461
                        finalHop.BlindingPoint = blindedPoint
1✔
1462
                }
1✔
1463

1464
                // The final hop does not have a short chanID set.
1465
                return finalHop.PayloadSize(0), nil
2✔
1466
        }
1467

1468
        var mpp *record.MPP
177✔
1469
        if r.PaymentAddr != nil {
228✔
1470
                mpp = record.NewMPP(amount, *r.PaymentAddr)
51✔
1471
        }
51✔
1472

1473
        var amp *record.AMP
177✔
1474
        if r.Amp != nil {
178✔
1475
                // The AMP payload is not easy accessible at this point but we
1✔
1476
                // are only interested in the size of the payload so we just use
1✔
1477
                // the AMP record dummy.
1✔
1478
                amp = &record.MaxAmpPayLoadSize
1✔
1479
        }
1✔
1480

1481
        finalHop := route.Hop{
177✔
1482
                AmtToForward:     amount,
177✔
1483
                OutgoingTimeLock: uint32(finalHtlcExpiry),
177✔
1484
                CustomRecords:    r.DestCustomRecords,
177✔
1485
                MPP:              mpp,
177✔
1486
                AMP:              amp,
177✔
1487
                Metadata:         r.Metadata,
177✔
1488
        }
177✔
1489

177✔
1490
        // The final hop does not have a short chanID set.
177✔
1491
        return finalHop.PayloadSize(0), nil
177✔
1492
}
1493

1494
// overflowSafeAdd adds two MilliSatoshi values and returns the result. If an
1495
// overflow could occur, zero is returned instead and the boolean is set to
1496
// true.
1497
func overflowSafeAdd(x, y lnwire.MilliSatoshi) (lnwire.MilliSatoshi, bool) {
433✔
1498
        if y > math.MaxUint64-x {
433✔
1499
                // Overflow would occur, return 0 and set overflow flag.
×
1500
                return 0, true
×
1501
        }
×
1502

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