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

lightningnetwork / lnd / 16181619122

09 Jul 2025 10:33PM UTC coverage: 55.326% (-2.3%) from 57.611%
16181619122

Pull #10060

github

web-flow
Merge d15e8671f into 0e830da9d
Pull Request #10060: sweep: fix expected spending events being missed

9 of 26 new or added lines in 2 files covered. (34.62%)

23695 existing lines in 280 files now uncovered.

108518 of 196143 relevant lines covered (55.33%)

22354.81 hits per line

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

89.53
/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 {
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.IsSome() {
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
                        finalHop.paymentAddr.WhenSome(func(addr [32]byte) {
135✔
264
                                mpp = record.NewMPP(finalHop.totalAmt, addr)
42✔
265
                        })
42✔
266

267
                        metadata = finalHop.metadata
93✔
268

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

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

123✔
286
                        inboundFee := pathEdges[i].inboundFees.CalcFee(
123✔
287
                                amtToForward + outboundFee,
123✔
288
                        )
123✔
289

123✔
290
                        fee = int64(outboundFee) + inboundFee
123✔
291
                        if fee < 0 {
125✔
292
                                fee = 0
2✔
293
                        }
2✔
294

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

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

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

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

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

343
                var (
1✔
344
                        inBlindedRoute bool
1✔
345
                        dataIndex      = 0
1✔
346

1✔
347
                        blindedPath = blindedPayment.BlindedPath
1✔
348
                        introVertex = route.NewVertex(
1✔
349
                                blindedPath.IntroductionPoint,
1✔
350
                        )
1✔
351
                )
1✔
352

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

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

367
                        payload := blindedPath.BlindedHops[dataIndex].CipherText
3✔
368
                        hop.EncryptedData = payload
3✔
369

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

377
                        dataIndex++
3✔
378
                }
379
        }
380

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

390
        return newRoute, nil
93✔
391
}
392

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

1,135✔
408
        return int64(fee) + timeLockPenalty
1,135✔
409
}
1,135✔
410

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

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

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

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

440
        // FeeLimit is a maximum fee amount allowed to be used on the path from
441
        // the source to the target.
442
        FeeLimit lnwire.MilliSatoshi
443

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

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

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

457
        // DestCustomRecords contains the custom records to drop off at the
458
        // final hop, if any.
459
        DestCustomRecords record.CustomSet
460

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

466
        // PaymentAddr is a random 32-byte value generated by the receiver to
467
        // mitigate probing vectors and payment sniping attacks on overpaid
468
        // invoices.
469
        PaymentAddr fn.Option[[32]byte]
470

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

476
        // Metadata is additional data that is sent along with the payment to
477
        // the payee.
478
        Metadata []byte
479

480
        // BlindedPaymentPathSet is necessary to determine the hop size of the
481
        // last/exit hop.
482
        BlindedPaymentPathSet *BlindedPaymentPathSet
483

484
        // FirstHopCustomRecords includes any records that should be included in
485
        // the update_add_htlc message towards our peer.
486
        FirstHopCustomRecords lnwire.CustomRecords
487
}
488

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

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

503
        // MinProbability defines the minimum success probability of the
504
        // returned route.
505
        MinProbability float64
506
}
507

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

180✔
515
        var max, total lnwire.MilliSatoshi
180✔
516
        cb := func(channel *graphdb.DirectedChannel) error {
625✔
517
                shortID := lnwire.NewShortChanIDFromInt(channel.ChannelID)
445✔
518

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

445✔
525
                if !channel.OutPolicySet {
445✔
526
                        log.Debugf("ShortChannelID=%v: has no out policy set, "+
×
527
                                "skipping", shortID)
×
528

×
529
                        return nil
×
530
                }
×
531

532
                chanID := channel.ChannelID
445✔
533

445✔
534
                // Enforce outgoing channel restriction.
445✔
535
                if outgoingChans != nil {
465✔
536
                        if _, ok := outgoingChans[chanID]; !ok {
32✔
537
                                return nil
12✔
538
                        }
12✔
539
                }
540

541
                bandwidth, ok := bandwidthHints.availableChanBandwidth(
433✔
542
                        chanID, 0,
433✔
543
                )
433✔
544

433✔
545
                // If the bandwidth is not available, use the channel capacity.
433✔
546
                // This can happen when a channel is added to the graph after
433✔
547
                // we've already queried the bandwidth hints.
433✔
548
                if !ok {
675✔
549
                        bandwidth = lnwire.NewMSatFromSatoshis(channel.Capacity)
242✔
550

242✔
551
                        log.Warnf("ShortChannelID=%v: not found in the local "+
242✔
552
                                "channels map of the bandwidth manager, "+
242✔
553
                                "using channel capacity=%v as bandwidth for "+
242✔
554
                                "this channel", shortID, bandwidth)
242✔
555
                }
242✔
556

557
                if bandwidth > max {
658✔
558
                        max = bandwidth
225✔
559
                }
225✔
560

561
                var overflow bool
433✔
562
                total, overflow = overflowSafeAdd(total, bandwidth)
433✔
563
                if overflow {
433✔
564
                        log.Warnf("ShortChannelID=%v: overflow detected, "+
×
565
                                "setting total to max value", shortID)
×
566

×
567
                        // If the current total and the bandwidth would
×
568
                        // overflow the maximum value, we set the total to the
×
569
                        // maximum value. Which is more milli-satoshis than are
×
570
                        // in existence anyway, so the actual value is
×
571
                        // irrelevant.
×
572
                        total = lnwire.MilliSatoshi(math.MaxUint64)
×
573
                }
×
574

575
                return nil
433✔
576
        }
577

578
        // Iterate over all channels of the to node.
579
        err := g.ForEachNodeDirectedChannel(node, cb)
180✔
580
        if err != nil {
180✔
581
                return 0, 0, err
×
582
        }
×
583
        return max, total, err
180✔
584
}
585

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

186✔
602
        // Pathfinding can be a significant portion of the total payment
186✔
603
        // latency, especially on low-powered devices. Log several metrics to
186✔
604
        // aid in the analysis performance problems in this area.
186✔
605
        start := time.Now()
186✔
606
        nodesVisited := 0
186✔
607
        edgesExpanded := 0
186✔
608
        defer func() {
372✔
609
                timeElapsed := time.Since(start)
186✔
610
                log.Debugf("Pathfinding perf metrics: nodes=%v, edges=%v, "+
186✔
611
                        "time=%v", nodesVisited, edgesExpanded, timeElapsed)
186✔
612
        }()
186✔
613

614
        // If no destination features are provided, we will load what features
615
        // we have for the target node from our graph.
616
        features := r.DestFeatures
186✔
617
        if features == nil {
304✔
618
                var err error
118✔
619
                features, err = g.graph.FetchNodeFeatures(target)
118✔
620
                if err != nil {
118✔
621
                        return nil, 0, err
×
622
                }
×
623
        }
624

625
        // Ensure that the destination's features don't include unknown
626
        // required features.
627
        err := feature.ValidateRequired(features)
186✔
628
        if err != nil {
188✔
629
                log.Warnf("Pathfinding destination node features: %v", err)
2✔
630
                return nil, 0, errUnknownRequiredFeature
2✔
631
        }
2✔
632

633
        // Ensure that all transitive dependencies are set.
634
        err = feature.ValidateDeps(features)
184✔
635
        if err != nil {
186✔
636
                log.Warnf("Pathfinding destination node features: %v", err)
2✔
637
                return nil, 0, errMissingDependentFeature
2✔
638
        }
2✔
639

640
        // Now that we know the feature vector is well-formed, we'll proceed in
641
        // checking that it supports the features we need. If the caller has a
642
        // payment address to attach, check that our destination feature vector
643
        // supports them.
644
        if r.PaymentAddr.IsSome() &&
182✔
645
                !features.HasFeature(lnwire.PaymentAddrOptional) {
184✔
646

2✔
647
                return nil, 0, errNoPaymentAddr
2✔
648
        }
2✔
649

650
        // Set up outgoing channel map for quicker access.
651
        var outgoingChanMap map[uint64]struct{}
180✔
652
        if len(r.OutgoingChannelIDs) > 0 {
186✔
653
                outgoingChanMap = make(map[uint64]struct{})
6✔
654
                for _, outChan := range r.OutgoingChannelIDs {
14✔
655
                        outgoingChanMap[outChan] = struct{}{}
8✔
656
                }
8✔
657
        }
658

659
        // If we are routing from ourselves, check that we have enough local
660
        // balance available.
661
        if source == self {
360✔
662
                max, total, err := getOutgoingBalance(
180✔
663
                        self, outgoingChanMap, g.bandwidthHints, g.graph,
180✔
664
                )
180✔
665
                if err != nil {
180✔
666
                        return nil, 0, err
×
667
                }
×
668

669
                // If the total outgoing balance isn't sufficient, it will be
670
                // impossible to complete the payment.
671
                if total < amt {
183✔
672
                        log.Warnf("Not enough outbound balance to send "+
3✔
673
                                "htlc of amount: %v, only have local "+
3✔
674
                                "balance: %v", amt, total)
3✔
675

3✔
676
                        return nil, 0, errInsufficientBalance
3✔
677
                }
3✔
678

679
                // If there is only not enough capacity on a single route, it
680
                // may still be possible to complete the payment by splitting.
681
                if max < amt {
178✔
682
                        return nil, 0, errNoPathFound
1✔
683
                }
1✔
684
        }
685

686
        // First we'll initialize an empty heap which'll help us to quickly
687
        // locate the next edge we should visit next during our graph
688
        // traversal.
689
        nodeHeap := newDistanceHeap(estimatedNodeCount)
176✔
690

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

176✔
694
        additionalEdgesWithSrc := make(map[route.Vertex][]*edgePolicyWithSource)
176✔
695
        for vertex, additionalEdges := range g.additionalEdges {
196✔
696
                // Edges connected to self are always included in the graph,
20✔
697
                // therefore can be skipped. This prevents us from trying
20✔
698
                // routes to malformed hop hints.
20✔
699
                if vertex == self {
24✔
700
                        continue
4✔
701
                }
702

703
                // Build reverse lookup to find incoming edges. Needed because
704
                // search is taken place from target to source.
705
                for _, additionalEdge := range additionalEdges {
32✔
706
                        outgoingEdgePolicy := additionalEdge.EdgePolicy()
16✔
707
                        toVertex := outgoingEdgePolicy.ToNodePubKey()
16✔
708

16✔
709
                        incomingEdgePolicy := &edgePolicyWithSource{
16✔
710
                                sourceNode: vertex,
16✔
711
                                edge:       additionalEdge,
16✔
712
                        }
16✔
713

16✔
714
                        additionalEdgesWithSrc[toVertex] =
16✔
715
                                append(additionalEdgesWithSrc[toVertex],
16✔
716
                                        incomingEdgePolicy)
16✔
717
                }
16✔
718
        }
719

720
        // The payload size of the final hop differ from intermediate hops
721
        // and depends on whether the destination is blinded or not.
722
        lastHopPayloadSize, err := lastHopPayloadSize(r, finalHtlcExpiry, amt)
176✔
723
        if err != nil {
176✔
724
                return nil, 0, err
×
725
        }
×
726

727
        // We can't always assume that the end destination is publicly
728
        // advertised to the network so we'll manually include the target node.
729
        // The target node charges no fee. Distance is set to 0, because this is
730
        // the starting point of the graph traversal. We are searching backwards
731
        // to get the fees first time right and correctly match channel
732
        // bandwidth.
733
        //
734
        // Don't record the initial partial path in the distance map and reserve
735
        // that key for the source key in the case we route to ourselves.
736
        partialPath := &nodeWithDist{
176✔
737
                dist:              0,
176✔
738
                weight:            0,
176✔
739
                node:              target,
176✔
740
                netAmountReceived: amt,
176✔
741
                incomingCltv:      finalHtlcExpiry,
176✔
742
                probability:       1,
176✔
743
                routingInfoSize:   lastHopPayloadSize,
176✔
744
        }
176✔
745

176✔
746
        // Calculate the absolute cltv limit. Use uint64 to prevent an overflow
176✔
747
        // if the cltv limit is MaxUint32.
176✔
748
        absoluteCltvLimit := uint64(r.CltvLimit) + uint64(finalHtlcExpiry)
176✔
749

176✔
750
        // Calculate the default attempt cost as configured globally.
176✔
751
        defaultAttemptCost := float64(
176✔
752
                cfg.AttemptCost +
176✔
753
                        amt*lnwire.MilliSatoshi(cfg.AttemptCostPPM)/1000000,
176✔
754
        )
176✔
755

176✔
756
        // Validate time preference value.
176✔
757
        if math.Abs(timePref) > 1 {
176✔
758
                return nil, 0, fmt.Errorf("time preference %v out of range "+
×
759
                        "[-1, 1]", timePref)
×
760
        }
×
761

762
        // Scale to avoid the extremes -1 and 1 which run into infinity issues.
763
        timePref *= 0.9
176✔
764

176✔
765
        // Apply time preference. At 0, the default attempt cost will
176✔
766
        // be used.
176✔
767
        absoluteAttemptCost := defaultAttemptCost * (1/(0.5-timePref/2) - 1)
176✔
768

176✔
769
        log.Debugf("Pathfinding absolute attempt cost: %v sats",
176✔
770
                absoluteAttemptCost/1000)
176✔
771

176✔
772
        // processEdge is a helper closure that will be used to make sure edges
176✔
773
        // satisfy our specific requirements.
176✔
774
        processEdge := func(fromVertex route.Vertex,
176✔
775
                edge *unifiedEdge, toNodeDist *nodeWithDist) {
1,428✔
776

1,252✔
777
                edgesExpanded++
1,252✔
778

1,252✔
779
                // Calculate inbound fee charged by "to" node. The exit hop
1,252✔
780
                // doesn't charge inbound fees. If the "to" node is the exit
1,252✔
781
                // hop, its inbound fees have already been set to zero by
1,252✔
782
                // nodeEdgeUnifier.
1,252✔
783
                inboundFee := edge.inboundFees.CalcFee(
1,252✔
784
                        toNodeDist.netAmountReceived,
1,252✔
785
                )
1,252✔
786

1,252✔
787
                // Make sure that the node total fee is never negative.
1,252✔
788
                // Routing nodes treat a total fee that turns out
1,252✔
789
                // negative as a zero fee and pathfinding should do the
1,252✔
790
                // same.
1,252✔
791
                minInboundFee := -int64(toNodeDist.outboundFee)
1,252✔
792
                if inboundFee < minInboundFee {
1,254✔
793
                        inboundFee = minInboundFee
2✔
794
                }
2✔
795

796
                // Calculate amount that the candidate node would have to send
797
                // out.
798
                amountToSend := toNodeDist.netAmountReceived +
1,252✔
799
                        lnwire.MilliSatoshi(inboundFee)
1,252✔
800

1,252✔
801
                // Check if accumulated fees would exceed fee limit when this
1,252✔
802
                // node would be added to the path.
1,252✔
803
                totalFee := int64(amountToSend) - int64(amt)
1,252✔
804

1,252✔
805
                log.Trace(lnutils.NewLogClosure(func() string {
1,252✔
806
                        return fmt.Sprintf(
×
807
                                "Checking fromVertex (%v) with "+
×
808
                                        "minInboundFee=%v, inboundFee=%v, "+
×
809
                                        "amountToSend=%v, amt=%v, totalFee=%v",
×
810
                                fromVertex, minInboundFee, inboundFee,
×
811
                                amountToSend, amt, totalFee,
×
812
                        )
×
813
                }))
×
814

815
                if totalFee > 0 && lnwire.MilliSatoshi(totalFee) > r.FeeLimit {
1,256✔
816
                        return
4✔
817
                }
4✔
818

819
                // Request the success probability for this edge.
820
                edgeProbability := r.ProbabilitySource(
1,248✔
821
                        fromVertex, toNodeDist.node, amountToSend,
1,248✔
822
                        edge.capacity,
1,248✔
823
                )
1,248✔
824

1,248✔
825
                log.Trace(lnutils.NewLogClosure(func() string {
1,248✔
826
                        return fmt.Sprintf("path finding probability: fromnode=%v,"+
×
827
                                " tonode=%v, amt=%v, cap=%v, probability=%v",
×
828
                                fromVertex, toNodeDist.node, amountToSend,
×
829
                                edge.capacity, edgeProbability)
×
830
                }))
×
831

832
                // If the probability is zero, there is no point in trying.
833
                if edgeProbability == 0 {
1,248✔
834
                        return
×
835
                }
×
836

837
                // Compute fee that fromVertex is charging. It is based on the
838
                // amount that needs to be sent to the next node in the route.
839
                //
840
                // Source node has no predecessor to pay a fee. Therefore set
841
                // fee to zero, because it should not be included in the fee
842
                // limit check and edge weight.
843
                //
844
                // Also determine the time lock delta that will be added to the
845
                // route if fromVertex is selected. If fromVertex is the source
846
                // node, no additional timelock is required.
847
                var (
1,248✔
848
                        timeLockDelta uint16
1,248✔
849
                        outboundFee   int64
1,248✔
850
                )
1,248✔
851

1,248✔
852
                if fromVertex != source {
2,352✔
853
                        outboundFee = int64(
1,104✔
854
                                edge.policy.ComputeFee(amountToSend),
1,104✔
855
                        )
1,104✔
856
                        timeLockDelta = edge.policy.TimeLockDelta
1,104✔
857
                }
1,104✔
858

859
                incomingCltv := toNodeDist.incomingCltv + int32(timeLockDelta)
1,248✔
860

1,248✔
861
                // Check that we are within our CLTV limit.
1,248✔
862
                if uint64(incomingCltv) > absoluteCltvLimit {
1,260✔
863
                        return
12✔
864
                }
12✔
865

866
                // netAmountToReceive is the amount that the node that is added
867
                // to the distance map needs to receive from a (to be found)
868
                // previous node in the route. The inbound fee of the receiving
869
                // node is already subtracted from this value. The previous node
870
                // will need to pay the amount that this node forwards plus the
871
                // fee it charges plus this node's inbound fee.
872
                netAmountToReceive := amountToSend +
1,236✔
873
                        lnwire.MilliSatoshi(outboundFee)
1,236✔
874

1,236✔
875
                // Calculate total probability of successfully reaching target
1,236✔
876
                // by multiplying the probabilities. Both this edge and the rest
1,236✔
877
                // of the route must succeed.
1,236✔
878
                probability := toNodeDist.probability * edgeProbability
1,236✔
879

1,236✔
880
                // If the probability is below the specified lower bound, we can
1,236✔
881
                // abandon this direction. Adding further nodes can only lower
1,236✔
882
                // the probability more.
1,236✔
883
                if probability < cfg.MinProbability {
1,337✔
884
                        return
101✔
885
                }
101✔
886

887
                // Calculate the combined fee for this edge. Dijkstra does not
888
                // support negative edge weights. Because this fee feeds into
889
                // the edge weight calculation, we don't allow it to be
890
                // negative.
891
                signedFee := inboundFee + outboundFee
1,135✔
892
                fee := lnwire.MilliSatoshi(0)
1,135✔
893
                if signedFee > 0 {
1,693✔
894
                        fee = lnwire.MilliSatoshi(signedFee)
558✔
895
                }
558✔
896

897
                // By adding fromVertex in the route, there will be an extra
898
                // weight composed of the fee that this node will charge and
899
                // the amount that will be locked for timeLockDelta blocks in
900
                // the HTLC that is handed out to fromVertex.
901
                weight := edgeWeight(amountToSend, fee, timeLockDelta)
1,135✔
902

1,135✔
903
                // Compute the tentative weight to this new channel/edge
1,135✔
904
                // which is the weight from our toNode to the target node
1,135✔
905
                // plus the weight of this edge.
1,135✔
906
                tempWeight := toNodeDist.weight + weight
1,135✔
907

1,135✔
908
                // Add an extra factor to the weight to take into account the
1,135✔
909
                // probability. Another reason why we rounded the fee up to zero
1,135✔
910
                // is to prevent a highly negative fee from cancelling out the
1,135✔
911
                // extra factor. We don't want an always-failing node to attract
1,135✔
912
                // traffic using a highly negative fee and escape penalization.
1,135✔
913
                tempDist := getProbabilityBasedDist(
1,135✔
914
                        tempWeight, probability,
1,135✔
915
                        absoluteAttemptCost,
1,135✔
916
                )
1,135✔
917

1,135✔
918
                // If there is already a best route stored, compare this
1,135✔
919
                // candidate route with the best route so far.
1,135✔
920
                current, ok := distance[fromVertex]
1,135✔
921
                if ok {
1,530✔
922
                        // If this route is worse than what we already found,
395✔
923
                        // skip this route.
395✔
924
                        if tempDist > current.dist {
700✔
925
                                return
305✔
926
                        }
305✔
927

928
                        // If the route is equally good and the probability
929
                        // isn't better, skip this route. It is important to
930
                        // also return if both cost and probability are equal,
931
                        // because otherwise the algorithm could run into an
932
                        // endless loop.
933
                        probNotBetter := probability <= current.probability
90✔
934
                        if tempDist == current.dist && probNotBetter {
149✔
935
                                return
59✔
936
                        }
59✔
937
                }
938

939
                // Calculate the total routing info size if this hop were to be
940
                // included. If we are coming from the source hop, the payload
941
                // size is zero, because the original htlc isn't in the onion
942
                // blob.
943
                //
944
                // NOTE: For blinded paths with the NUMS key as the last hop,
945
                // the payload size accounts for this dummy hop which is of
946
                // the same size as the real last hop. So we account for a
947
                // bigger size than the route is however we accept this
948
                // little inaccuracy here because we are over estimating by
949
                // 1 hop.
950
                var payloadSize uint64
771✔
951
                if fromVertex != source {
1,402✔
952
                        // In case the unifiedEdge does not have a payload size
631✔
953
                        // function supplied we request a graceful shutdown
631✔
954
                        // because this should never happen.
631✔
955
                        if edge.hopPayloadSizeFn == nil {
631✔
956
                                log.Criticalf("No payload size function "+
×
957
                                        "available for edge=%v unable to "+
×
958
                                        "determine payload size: %v", edge,
×
959
                                        ErrNoPayLoadSizeFunc)
×
960

×
961
                                return
×
962
                        }
×
963

964
                        payloadSize = edge.hopPayloadSizeFn(
631✔
965
                                amountToSend,
631✔
966
                                uint32(toNodeDist.incomingCltv),
631✔
967
                                edge.policy.ChannelID,
631✔
968
                        )
631✔
969
                }
970

971
                routingInfoSize := toNodeDist.routingInfoSize + payloadSize
771✔
972
                // Skip paths that would exceed the maximum routing info size.
771✔
973
                if routingInfoSize > sphinx.MaxPayloadSize {
777✔
974
                        return
6✔
975
                }
6✔
976

977
                // All conditions are met and this new tentative distance is
978
                // better than the current best known distance to this node.
979
                // The new better distance is recorded, and also our "next hop"
980
                // map is populated with this edge.
981
                withDist := &nodeWithDist{
765✔
982
                        dist:              tempDist,
765✔
983
                        weight:            tempWeight,
765✔
984
                        node:              fromVertex,
765✔
985
                        netAmountReceived: netAmountToReceive,
765✔
986
                        outboundFee:       lnwire.MilliSatoshi(outboundFee),
765✔
987
                        incomingCltv:      incomingCltv,
765✔
988
                        probability:       probability,
765✔
989
                        nextHop:           edge,
765✔
990
                        routingInfoSize:   routingInfoSize,
765✔
991
                }
765✔
992
                distance[fromVertex] = withDist
765✔
993

765✔
994
                // Either push withDist onto the heap if the node
765✔
995
                // represented by fromVertex is not already on the heap OR adjust
765✔
996
                // its position within the heap via heap.Fix.
765✔
997
                nodeHeap.PushOrFix(withDist)
765✔
998
        }
999

1000
        // TODO(roasbeef): also add path caching
1001
        //  * similar to route caching, but doesn't factor in the amount
1002

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

176✔
1006
        // getGraphFeatures returns (cached) node features from the graph.
176✔
1007
        getGraphFeatures := func(node route.Vertex) (*lnwire.FeatureVector,
176✔
1008
                error) {
1,432✔
1009

1,256✔
1010
                // Check cache for features of the fromNode.
1,256✔
1011
                fromFeatures, ok := featureCache[node]
1,256✔
1012
                if ok {
1,719✔
1013
                        return fromFeatures, nil
463✔
1014
                }
463✔
1015

1016
                // Fetch node features fresh from the graph.
1017
                fromFeatures, err := g.graph.FetchNodeFeatures(node)
793✔
1018
                if err != nil {
793✔
1019
                        return nil, err
×
1020
                }
×
1021

1022
                // Don't route through nodes that contain unknown required
1023
                // features and mark as nil in the cache.
1024
                err = feature.ValidateRequired(fromFeatures)
793✔
1025
                if err != nil {
795✔
1026
                        featureCache[node] = nil
2✔
1027
                        return nil, nil
2✔
1028
                }
2✔
1029

1030
                // Don't route through nodes that don't properly set all
1031
                // transitive feature dependencies and mark as nil in the cache.
1032
                err = feature.ValidateDeps(fromFeatures)
791✔
1033
                if err != nil {
793✔
1034
                        featureCache[node] = nil
2✔
1035
                        return nil, nil
2✔
1036
                }
2✔
1037

1038
                // Update cache.
1039
                featureCache[node] = fromFeatures
789✔
1040

789✔
1041
                return fromFeatures, nil
789✔
1042
        }
1043

1044
        routeToSelf := source == target
176✔
1045
        for {
871✔
1046
                nodesVisited++
695✔
1047

695✔
1048
                pivot := partialPath.node
695✔
1049
                isExitHop := partialPath.nextHop == nil
695✔
1050

695✔
1051
                // Create unified policies for all incoming connections. Don't
695✔
1052
                // use inbound fees for the exit hop.
695✔
1053
                u := newNodeEdgeUnifier(
695✔
1054
                        self, pivot, !isExitHop, outgoingChanMap,
695✔
1055
                )
695✔
1056

695✔
1057
                err := u.addGraphPolicies(g.graph)
695✔
1058
                if err != nil {
695✔
1059
                        return nil, 0, err
×
1060
                }
×
1061

1062
                // We add hop hints that were supplied externally.
1063
                for _, reverseEdge := range additionalEdgesWithSrc[pivot] {
711✔
1064
                        // Assume zero inbound fees for route hints. If inbound
16✔
1065
                        // fees would apply, they couldn't be communicated in
16✔
1066
                        // bolt11 invoices currently.
16✔
1067
                        inboundFee := models.InboundFee{}
16✔
1068

16✔
1069
                        // Hop hints don't contain a capacity. We set one here,
16✔
1070
                        // since a capacity is needed for probability
16✔
1071
                        // calculations. We set a high capacity to act as if
16✔
1072
                        // there is enough liquidity, otherwise the hint would
16✔
1073
                        // not have been added by a wallet.
16✔
1074
                        // We also pass the payload size function to the
16✔
1075
                        // graph data so that we calculate the exact payload
16✔
1076
                        // size when evaluating this hop for a route.
16✔
1077
                        u.addPolicy(
16✔
1078
                                reverseEdge.sourceNode,
16✔
1079
                                reverseEdge.edge.EdgePolicy(),
16✔
1080
                                inboundFee,
16✔
1081
                                fakeHopHintCapacity,
16✔
1082
                                reverseEdge.edge.IntermediatePayloadSize,
16✔
1083
                                reverseEdge.edge.BlindedPayment(),
16✔
1084
                        )
16✔
1085
                }
16✔
1086

1087
                netAmountReceived := partialPath.netAmountReceived
695✔
1088

695✔
1089
                // Expand all connections using the optimal policy for each
695✔
1090
                // connection.
695✔
1091
                for fromNode, edgeUnifier := range u.edgeUnifiers {
2,314✔
1092
                        // The target node is not recorded in the distance map.
1,619✔
1093
                        // Therefore we need to have this check to prevent
1,619✔
1094
                        // creating a cycle. Only when we intend to route to
1,619✔
1095
                        // self, we allow this cycle to form. In that case we'll
1,619✔
1096
                        // also break out of the search loop below.
1,619✔
1097
                        if !routeToSelf && fromNode == target {
1,948✔
1098
                                continue
329✔
1099
                        }
1100

1101
                        // Apply last hop restriction if set.
1102
                        if r.LastHop != nil &&
1,290✔
1103
                                pivot == target && fromNode != *r.LastHop {
1,294✔
1104

4✔
1105
                                continue
4✔
1106
                        }
1107

1108
                        edge := edgeUnifier.getEdge(
1,286✔
1109
                                netAmountReceived, g.bandwidthHints,
1,286✔
1110
                                partialPath.outboundFee,
1,286✔
1111
                        )
1,286✔
1112

1,286✔
1113
                        if edge == nil {
1,316✔
1114
                                continue
30✔
1115
                        }
1116

1117
                        // Get feature vector for fromNode.
1118
                        fromFeatures, err := getGraphFeatures(fromNode)
1,256✔
1119
                        if err != nil {
1,256✔
1120
                                return nil, 0, err
×
1121
                        }
×
1122

1123
                        // If there are no valid features, skip this node.
1124
                        if fromFeatures == nil {
1,260✔
1125
                                continue
4✔
1126
                        }
1127

1128
                        // Check if this candidate node is better than what we
1129
                        // already have.
1130
                        processEdge(fromNode, edge, partialPath)
1,252✔
1131
                }
1132

1133
                if nodeHeap.Len() == 0 {
735✔
1134
                        break
40✔
1135
                }
1136

1137
                // Fetch the node within the smallest distance from our source
1138
                // from the heap.
1139
                partialPath = heap.Pop(&nodeHeap).(*nodeWithDist)
655✔
1140

655✔
1141
                // If we've reached our source (or we don't have any incoming
655✔
1142
                // edges), then we're done here and can exit the graph
655✔
1143
                // traversal early.
655✔
1144
                if partialPath.node == source {
791✔
1145
                        break
136✔
1146
                }
1147
        }
1148

1149
        // Use the distance map to unravel the forward path from source to
1150
        // target.
1151
        var pathEdges []*unifiedEdge
176✔
1152
        currentNode := source
176✔
1153
        for {
556✔
1154
                // Determine the next hop forward using the next map.
380✔
1155
                currentNodeWithDist, ok := distance[currentNode]
380✔
1156
                if !ok {
420✔
1157
                        // If the node doesn't have a next hop it means we
40✔
1158
                        // didn't find a path.
40✔
1159
                        return nil, 0, errNoPathFound
40✔
1160
                }
40✔
1161

1162
                // Add the next hop to the list of path edges.
1163
                pathEdges = append(pathEdges, currentNodeWithDist.nextHop)
340✔
1164

340✔
1165
                // Advance current node.
340✔
1166
                currentNode = currentNodeWithDist.nextHop.policy.ToNodePubKey()
340✔
1167

340✔
1168
                // Check stop condition at the end of this loop. This prevents
340✔
1169
                // breaking out too soon for self-payments that have target set
340✔
1170
                // to source.
340✔
1171
                if currentNode == target {
476✔
1172
                        break
136✔
1173
                }
1174
        }
1175

1176
        // For the final hop, we'll set the node features to those determined
1177
        // above. These are either taken from the destination features, e.g.
1178
        // virtual or invoice features, or loaded as a fallback from the graph.
1179
        // The transitive dependencies were already validated above, so no need
1180
        // to do so now.
1181
        //
1182
        // NOTE: This may overwrite features loaded from the graph if
1183
        // destination features were provided. This is fine though, since our
1184
        // route construction does not care where the features are actually
1185
        // taken from. In the future we may wish to do route construction within
1186
        // findPath, and avoid using ChannelEdgePolicy altogether.
1187
        pathEdges[len(pathEdges)-1].policy.ToNodeFeatures = features
136✔
1188

136✔
1189
        log.Debugf("Found route: probability=%v, hops=%v, fee=%v",
136✔
1190
                distance[source].probability, len(pathEdges),
136✔
1191
                distance[source].netAmountReceived-amt)
136✔
1192

136✔
1193
        return pathEdges, distance[source].probability, nil
136✔
1194
}
1195

1196
// blindedPathRestrictions are a set of constraints to adhere to when
1197
// choosing a set of blinded paths to this node.
1198
type blindedPathRestrictions struct {
1199
        // minNumHops is the minimum number of hops to include in a blinded
1200
        // path. This doesn't include our node, so if the minimum is 1, then
1201
        // the path will contain at minimum our node along with an introduction
1202
        // node hop. A minimum of 0 will include paths where this node is the
1203
        // introduction node and so should be used with caution.
1204
        minNumHops uint8
1205

1206
        // maxNumHops is the maximum number of hops to include in a blinded
1207
        // path. This doesn't include our node, so if the maximum is 1, then
1208
        // the path will contain our node along with an introduction node hop.
1209
        maxNumHops uint8
1210

1211
        // nodeOmissionSet holds a set of node IDs of nodes that we should
1212
        // ignore during blinded path selection.
1213
        nodeOmissionSet fn.Set[route.Vertex]
1214

1215
        // incomingChainedChannels holds the chained channels list specified
1216
        // via scid (short channel id) starting from a channel which points to
1217
        // the receiver node.
1218
        incomingChainedChannels []uint64
1219
}
1220

1221
// blindedHop holds the information about a hop we have selected for a blinded
1222
// path.
1223
type blindedHop struct {
1224
        vertex       route.Vertex
1225
        channelID    uint64
1226
        edgeCapacity btcutil.Amount
1227
}
1228

1229
// findBlindedPaths does a depth first search from the target node to find a set
1230
// of blinded paths to the target node given the set of restrictions. This
1231
// function will select and return any candidate path. A candidate path is a
1232
// path to the target node with a size determined by the given hop number
1233
// constraints where all the nodes on the path signal the route blinding feature
1234
// _and_ the introduction node for the path has more than one public channel.
1235
// Any filtering of paths based on payment value or success probabilities is
1236
// left to the caller.
1237
func findBlindedPaths(g Graph, target route.Vertex,
1238
        restrictions *blindedPathRestrictions) ([][]blindedHop, error) {
19✔
1239

19✔
1240
        // Sanity check the restrictions.
19✔
1241
        if restrictions.minNumHops > restrictions.maxNumHops {
19✔
1242
                return nil, fmt.Errorf("maximum number of blinded path hops "+
×
1243
                        "(%d) must be greater than or equal to the minimum "+
×
1244
                        "number of hops (%d)", restrictions.maxNumHops,
×
1245
                        restrictions.minNumHops)
×
1246
        }
×
1247

1248
        var (
19✔
1249
                // The target node is always the last hop in the path, and so
19✔
1250
                // we add it to the incoming path from the get-go. Any additions
19✔
1251
                // to the slice should be prepended.
19✔
1252
                incomingPath = []blindedHop{{
19✔
1253
                        vertex: target,
19✔
1254
                }}
19✔
1255

19✔
1256
                // supportsRouteBlinding is a list of nodes that we can assume
19✔
1257
                // support route blinding without needing to rely on the feature
19✔
1258
                // bits announced in their node announcement. Since we are
19✔
1259
                // finding a path to the target node, we can assume it supports
19✔
1260
                // route blinding.
19✔
1261
                supportsRouteBlinding = map[route.Vertex]bool{
19✔
1262
                        target: true,
19✔
1263
                }
19✔
1264

19✔
1265
                visited          = make(map[route.Vertex]bool)
19✔
1266
                nextTarget       = target
19✔
1267
                haveIncomingPath = len(restrictions.incomingChainedChannels) > 0
19✔
1268

19✔
1269
                // errChanFound is an error variable we return from the DB
19✔
1270
                // iteration call below when we have found the channel we are
19✔
1271
                // looking for. This lets us exit the iteration early.
19✔
1272
                errChanFound = errors.New("found incoming channel")
19✔
1273
        )
19✔
1274
        for _, chanID := range restrictions.incomingChainedChannels {
30✔
1275
                // Mark that we have visited this node so that we don't revisit
11✔
1276
                // it later on when we call "processNodeForBlindedPath".
11✔
1277
                visited[nextTarget] = true
11✔
1278

11✔
1279
                err := g.ForEachNodeDirectedChannel(nextTarget,
11✔
1280
                        func(channel *graphdb.DirectedChannel) error {
34✔
1281
                                // This is not the right channel, continue to
23✔
1282
                                // the node's other channels.
23✔
1283
                                if channel.ChannelID != chanID {
35✔
1284
                                        return nil
12✔
1285
                                }
12✔
1286

1287
                                // We found the channel in question. Prepend it
1288
                                // to the incoming path.
1289
                                incomingPath = append([]blindedHop{
11✔
1290
                                        {
11✔
1291
                                                vertex:       channel.OtherNode,
11✔
1292
                                                channelID:    channel.ChannelID,
11✔
1293
                                                edgeCapacity: channel.Capacity,
11✔
1294
                                        },
11✔
1295
                                }, incomingPath...)
11✔
1296

11✔
1297
                                // Update the target node.
11✔
1298
                                nextTarget = channel.OtherNode
11✔
1299

11✔
1300
                                return errChanFound
11✔
1301
                        },
1302
                )
1303
                // We expect errChanFound to be returned if the channel in
1304
                // question was found.
1305
                if !errors.Is(err, errChanFound) && err != nil {
11✔
1306
                        return nil, err
×
1307
                } else if err == nil {
11✔
UNCOV
1308
                        return nil, fmt.Errorf("incoming channel %d is not "+
×
UNCOV
1309
                                "seen as owned by node %v", chanID, nextTarget)
×
UNCOV
1310
                }
×
1311

1312
                // Check that the user didn't accidentally add a channel that
1313
                // is owned by a node in the node omission set.
1314
                if restrictions.nodeOmissionSet.Contains(nextTarget) {
12✔
1315
                        return nil, fmt.Errorf("node %v cannot simultaneously "+
1✔
1316
                                "be included in the omission set and in the "+
1✔
1317
                                "partially specified path", nextTarget)
1✔
1318
                }
1✔
1319

1320
                // Check that we have not already visited the next target node
1321
                // since this would mean a circular incoming path.
1322
                if visited[nextTarget] {
11✔
1323
                        return nil, fmt.Errorf("a circular route cannot be " +
1✔
1324
                                "specified for the incoming blinded path")
1✔
1325
                }
1✔
1326

1327
                supportsRouteBlinding[nextTarget] = true
9✔
1328
        }
1329

1330
        // A helper closure which checks if the node in question has advertised
1331
        // that it supports route blinding.
1332
        nodeSupportsRouteBlinding := func(node route.Vertex) (bool, error) {
103✔
1333
                if supportsRouteBlinding[node] {
103✔
1334
                        return true, nil
17✔
1335
                }
17✔
1336

1337
                features, err := g.FetchNodeFeatures(node)
69✔
1338
                if err != nil {
69✔
1339
                        return false, err
×
1340
                }
×
1341

1342
                return features.HasFeature(lnwire.RouteBlindingOptional), nil
69✔
1343
        }
1344

1345
        // This function will have some recursion. We will spin out from the
1346
        // target node & append edges to the paths until we reach various exit
1347
        // conditions such as: The maxHops number being reached or reaching
1348
        // a node that doesn't have any other edges - in that final case, the
1349
        // whole path should be ignored.
1350
        //
1351
        // NOTE: any paths returned will end at the "nextTarget" node meaning
1352
        // that if we have a fixed list of incoming chained channels, then this
1353
        // fixed list must be appended to any of the returned paths.
1354
        paths, _, err := processNodeForBlindedPath(
17✔
1355
                g, nextTarget, nodeSupportsRouteBlinding, visited, restrictions,
17✔
1356
        )
17✔
1357
        if err != nil {
17✔
1358
                return nil, err
×
1359
        }
×
1360

1361
        // Reverse each path so that the order is correct (from introduction
1362
        // node to last hop node) and then append the incoming path (if any was
1363
        // specified) to the end of the path.
1364
        orderedPaths := make([][]blindedHop, 0, len(paths))
17✔
1365
        for _, path := range paths {
56✔
1366
                sort.Slice(path, func(i, j int) bool {
75✔
1367
                        return j < i
36✔
1368
                })
36✔
1369

1370
                orderedPaths = append(
39✔
1371
                        orderedPaths, append(path, incomingPath...),
39✔
1372
                )
39✔
1373
        }
1374

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

5✔
1380
                orderedPaths = append(orderedPaths, incomingPath)
5✔
1381
        }
5✔
1382

1383
        // Handle the special case that allows a blinded path with the
1384
        // introduction node as the destination node. This only applies if no
1385
        // incoming path was specified since in that case, by definition, the
1386
        // caller wants a non-zero length blinded path.
1387
        if restrictions.minNumHops == 0 && !haveIncomingPath {
19✔
1388
                singleHopPath := [][]blindedHop{{{vertex: target}}}
2✔
1389

2✔
1390
                orderedPaths = append(
2✔
1391
                        orderedPaths, singleHopPath...,
2✔
1392
                )
2✔
1393
        }
2✔
1394

1395
        return orderedPaths, err
17✔
1396
}
1397

1398
// processNodeForBlindedPath is a recursive function that traverses the graph
1399
// in a depth first manner searching for a set of blinded paths to the given
1400
// node.
1401
func processNodeForBlindedPath(g Graph, node route.Vertex,
1402
        supportsRouteBlinding func(vertex route.Vertex) (bool, error),
1403
        alreadyVisited map[route.Vertex]bool,
1404
        restrictions *blindedPathRestrictions) ([][]blindedHop, bool, error) {
234✔
1405

234✔
1406
        // If we have already visited the maximum number of hops, then this path
234✔
1407
        // is complete and we can exit now.
234✔
1408
        if len(alreadyVisited) > int(restrictions.maxNumHops) {
339✔
1409
                return nil, false, nil
105✔
1410
        }
105✔
1411

1412
        // If we have already visited this peer on this path, then we skip
1413
        // processing it again.
1414
        if alreadyVisited[node] {
168✔
1415
                return nil, false, nil
39✔
1416
        }
39✔
1417

1418
        // If we have explicitly been told to ignore this node for blinded paths
1419
        // then we skip it too.
1420
        if restrictions.nodeOmissionSet.Contains(node) {
94✔
1421
                return nil, false, nil
4✔
1422
        }
4✔
1423

1424
        supports, err := supportsRouteBlinding(node)
86✔
1425
        if err != nil {
86✔
1426
                return nil, false, err
×
1427
        }
×
1428
        if !supports {
92✔
1429
                return nil, false, nil
6✔
1430
        }
6✔
1431

1432
        // At this point, copy the alreadyVisited map.
1433
        visited := make(map[route.Vertex]bool, len(alreadyVisited))
80✔
1434
        for r := range alreadyVisited {
192✔
1435
                visited[r] = true
112✔
1436
        }
112✔
1437

1438
        // Add this node the visited set.
1439
        visited[node] = true
80✔
1440

80✔
1441
        var (
80✔
1442
                hopSets   [][]blindedHop
80✔
1443
                chanCount int
80✔
1444
        )
80✔
1445

80✔
1446
        // Now, iterate over the node's channels in search for paths to this
80✔
1447
        // node that can be used for blinded paths
80✔
1448
        err = g.ForEachNodeDirectedChannel(node,
80✔
1449
                func(channel *graphdb.DirectedChannel) error {
297✔
1450
                        // Keep track of how many incoming channels this node
217✔
1451
                        // has. We only use a node as an introduction node if it
217✔
1452
                        // has channels other than the one that lead us to it.
217✔
1453
                        chanCount++
217✔
1454

217✔
1455
                        // Process each channel peer to gather any paths that
217✔
1456
                        // lead to the peer.
217✔
1457
                        nextPaths, hasMoreChans, err := processNodeForBlindedPath( //nolint:ll
217✔
1458
                                g, channel.OtherNode, supportsRouteBlinding,
217✔
1459
                                visited, restrictions,
217✔
1460
                        )
217✔
1461
                        if err != nil {
217✔
1462
                                return err
×
1463
                        }
×
1464

1465
                        hop := blindedHop{
217✔
1466
                                vertex:       channel.OtherNode,
217✔
1467
                                channelID:    channel.ChannelID,
217✔
1468
                                edgeCapacity: channel.Capacity,
217✔
1469
                        }
217✔
1470

217✔
1471
                        // For each of the paths returned, unwrap them and
217✔
1472
                        // append this hop to them.
217✔
1473
                        for _, path := range nextPaths {
250✔
1474
                                hopSets = append(
33✔
1475
                                        hopSets,
33✔
1476
                                        append([]blindedHop{hop}, path...),
33✔
1477
                                )
33✔
1478
                        }
33✔
1479

1480
                        // If this node does have channels other than the one
1481
                        // that lead to it, and if the hop count up to this node
1482
                        // meets the minHop requirement, then we also add a
1483
                        // path that starts at this node.
1484
                        if hasMoreChans &&
217✔
1485
                                len(visited) >= int(restrictions.minNumHops) {
256✔
1486

39✔
1487
                                hopSets = append(hopSets, []blindedHop{hop})
39✔
1488
                        }
39✔
1489

1490
                        return nil
217✔
1491
                },
1492
        )
1493
        if err != nil {
80✔
1494
                return nil, false, err
×
1495
        }
×
1496

1497
        return hopSets, chanCount > 1, nil
80✔
1498
}
1499

1500
// getProbabilityBasedDist converts a weight into a distance that takes into
1501
// account the success probability and the (virtual) cost of a failed payment
1502
// attempt.
1503
//
1504
// Derivation:
1505
//
1506
// Suppose there are two routes A and B with fees Fa and Fb and success
1507
// probabilities Pa and Pb.
1508
//
1509
// Is the expected cost of trying route A first and then B lower than trying the
1510
// other way around?
1511
//
1512
// The expected cost of A-then-B is: Pa*Fa + (1-Pa)*Pb*(c+Fb)
1513
//
1514
// The expected cost of B-then-A is: Pb*Fb + (1-Pb)*Pa*(c+Fa)
1515
//
1516
// In these equations, the term representing the case where both A and B fail is
1517
// left out because its value would be the same in both cases.
1518
//
1519
// Pa*Fa + (1-Pa)*Pb*(c+Fb) < Pb*Fb + (1-Pb)*Pa*(c+Fa)
1520
//
1521
// Pa*Fa + Pb*c + Pb*Fb - Pa*Pb*c - Pa*Pb*Fb < Pb*Fb + Pa*c + Pa*Fa - Pa*Pb*c - Pa*Pb*Fa
1522
//
1523
// Removing terms that cancel out:
1524
// Pb*c - Pa*Pb*Fb < Pa*c - Pa*Pb*Fa
1525
//
1526
// Divide by Pa*Pb:
1527
// c/Pa - Fb < c/Pb - Fa
1528
//
1529
// Move terms around:
1530
// Fa + c/Pa < Fb + c/Pb
1531
//
1532
// So the value of F + c/P can be used to compare routes.
1533
func getProbabilityBasedDist(weight int64, probability float64,
1534
        penalty float64) int64 {
1,135✔
1535

1,135✔
1536
        // Prevent divide by zero by returning early.
1,135✔
1537
        if probability == 0 {
1,135✔
1538
                return infinity
×
1539
        }
×
1540

1541
        // Calculate distance.
1542
        dist := float64(weight) + penalty/probability
1,135✔
1543

1,135✔
1544
        // Avoid cast if an overflow would occur. The maxFloat constant is
1,135✔
1545
        // chosen to stay well below the maximum float64 value that is still
1,135✔
1546
        // convertible to int64.
1,135✔
1547
        const maxFloat = 9000000000000000000
1,135✔
1548
        if dist > maxFloat {
1,135✔
1549
                return infinity
×
1550
        }
×
1551

1552
        return int64(dist)
1,135✔
1553
}
1554

1555
// lastHopPayloadSize calculates the payload size of the final hop in a route.
1556
// It depends on the tlv types which are present and also whether the hop is
1557
// part of a blinded route or not.
1558
func lastHopPayloadSize(r *RestrictParams, finalHtlcExpiry int32,
1559
        amount lnwire.MilliSatoshi) (uint64, error) {
179✔
1560

179✔
1561
        if r.BlindedPaymentPathSet != nil {
181✔
1562
                paymentPath, err := r.BlindedPaymentPathSet.
2✔
1563
                        LargestLastHopPayloadPath()
2✔
1564
                if err != nil {
2✔
1565
                        return 0, err
×
1566
                }
×
1567

1568
                blindedPath := paymentPath.BlindedPath.BlindedHops
2✔
1569
                blindedPoint := paymentPath.BlindedPath.BlindingPoint
2✔
1570

2✔
1571
                encryptedData := blindedPath[len(blindedPath)-1].CipherText
2✔
1572
                finalHop := route.Hop{
2✔
1573
                        AmtToForward:     amount,
2✔
1574
                        OutgoingTimeLock: uint32(finalHtlcExpiry),
2✔
1575
                        EncryptedData:    encryptedData,
2✔
1576
                }
2✔
1577
                if len(blindedPath) == 1 {
3✔
1578
                        finalHop.BlindingPoint = blindedPoint
1✔
1579
                }
1✔
1580

1581
                // The final hop does not have a short chanID set.
1582
                return finalHop.PayloadSize(0), nil
2✔
1583
        }
1584

1585
        var mpp *record.MPP
177✔
1586
        r.PaymentAddr.WhenSome(func(addr [32]byte) {
228✔
1587
                mpp = record.NewMPP(amount, addr)
51✔
1588
        })
51✔
1589

1590
        var amp *record.AMP
177✔
1591
        if r.Amp != nil {
178✔
1592
                // The AMP payload is not easy accessible at this point but we
1✔
1593
                // are only interested in the size of the payload so we just use
1✔
1594
                // the AMP record dummy.
1✔
1595
                amp = &record.MaxAmpPayLoadSize
1✔
1596
        }
1✔
1597

1598
        finalHop := route.Hop{
177✔
1599
                AmtToForward:     amount,
177✔
1600
                OutgoingTimeLock: uint32(finalHtlcExpiry),
177✔
1601
                CustomRecords:    r.DestCustomRecords,
177✔
1602
                MPP:              mpp,
177✔
1603
                AMP:              amp,
177✔
1604
                Metadata:         r.Metadata,
177✔
1605
        }
177✔
1606

177✔
1607
        // The final hop does not have a short chanID set.
177✔
1608
        return finalHop.PayloadSize(0), nil
177✔
1609
}
1610

1611
// overflowSafeAdd adds two MilliSatoshi values and returns the result. If an
1612
// overflow could occur, zero is returned instead and the boolean is set to
1613
// true.
1614
func overflowSafeAdd(x, y lnwire.MilliSatoshi) (lnwire.MilliSatoshi, bool) {
433✔
1615
        if y > math.MaxUint64-x {
433✔
1616
                // Overflow would occur, return 0 and set overflow flag.
×
1617
                return 0, true
×
1618
        }
×
1619

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